In a nutshell, you could do this with a user reference field, but you would be exposing everyone in the system (assuming all of these people are Drupal users). Maybe that isn't a big deal, maybe it is. I would create a view reference for the user reference field to only show users who are of a given role only, which should limit results. Furthermore, they would have to know the Drupal username - but you can get around that by installing RealName which swaps usernames for a realname field.

A reason for tying nodes to user accounts would be built-in permissions. "Owner" as just a Drupal textfield wouldn't really cut it in terms of true ownership.

I have done this in the past, similar scenario, different circumstance, where the system would create listings for businesses in the local area, and the business owners would come, register, and 'claim ownership' of their listing node by contacting us (webform). After vetting, we would change the node author (owner) from the admin to their Drupal account. Since they could have multiple, their user account dashboard listed all nodes that belong to them, free to edit and update.

I would also advise using a revision workflow so admins can track the history of a node and revert mistakes (as they are bound to happen from time to time).

Note, I am assuming your game pieces are custom entities or content types. It will work in either case.

You would need to give users enough permission to 'edit own ____' entity, and be able to update the user reference field. On submit, you could fire a custom rule with Rules that looks at the user reference field value, and updates the entity owner to that value (uid). Alternatively, you could implement a custom submit handler via hook_form_alter on specific forms, and do the logic yourself. The referenced UID value gets set as the owner, and once that happens, that user will no longer have access to edit or anything.

See:

https://www.drupal.org/project/realname
https://www.drupal.org/project/rules


The query_alter function allows build a custom module with the posibility of change sort order of a view. With this function you can add directly to your sql the respective declaration to sort results.

look this guide http://www.adworkshop.com/blog/2011/05/drupal-6-tutorial-exposed-sort-views-2 that show you how to create your query_alter and create the respective html control to your view (in this case is a dropdown menu).

this is the query_alter function:

function example_exposed_sort_views_query_alter(&$view, &$query) {
if( isset( $_GET['sortoptions'] ) ) {
if ( $_GET['sortoptions'] == 'az' )
 $query->orderby[0] = 'node_title ASC';
else if ( $_GET['sortoptions'] == 'za' )
$query->orderby[0] = 'node_title DESC'; } }

and this is the example of html control using a dropdown menu using in this case the template views-exposed-form.tpl.php.

<?php
$sortOp = '';
if ( isset($_GET['sortoptions']) ) $sortOp = $_GET['sortoptions'] ;
?>
<label>Sort Name</label>:
<input type="radio" id="sortoptionsA" name="sortoptions" onchange="javascript:$(this.form).submit();" class="form-submit" value="az" <?php if ($sortOp == 'az') print "checked"; ?> />A-Z
<input type="radio" id="sortoptionsZ" name="sortoptions" onchange="javascript:$(this.form).submit();" class="form-submit" value="za" <?php if ($sortOp == 'za') print "checked"; ?> />Z-A


Customize autocomplete field to show children terms depending on another field

You can drop using entity_autocomplete and instead it use custom autocomplete field. Here is an example of using, you can translate this page from Russian to your language. Also the example contains the attached source files.

https://niklan.net/blog/77

In the example you can see a controller what creates the list with values.
I suppose that you can pass a parameter to the controller (city_id) and SQL query will return set of resuts according the parameter.

You can add the parameter to the controller inside function buildForm() of your form. Also you can recreate the autocomplete element with new parameter after you selected a city from the list.


As I've not gotten anywhere with this, I'm working around it.  I'm only interested in bringing in the most recent article from a site that's on our own servers - so I'm writing a script that will import it into the node table and I'll use Views for the block.

I'll set the script to run nightly. Thanks for the help guys.


Invalidate the twig cache first, like this:

drush php-eval "\Drupal::service('twig')->invalidate();"
drush cc render


I would add the necessary reformatting of the badly formatted XML to the input processing of the custom module (the one you're writing).

If that is not an option (e.g. if the client insists that the XML feed is saved verbatim), then I would create a custom filter for this content.  Drupal filters do not change the input - it only changes the presentation.


Allowing users to add taxonomy terms but requiring administrators to verify them

Brainstorming here...now that taxonomy is part of the entity system, it should be possible to do something like this:

Install http://drupal.org/project/workflow
Add a field to your taxonomy called "Published" or "Approved" that is a boolean checkbox
Setup a workflow that is triggered on taxonomy term creation with Approved as a field only accessible to admins
Write a hook into taxonomy terms that removes a term unless it is approved (this is the tricky part - there are a lot of ways to get to taxonomy terms, so this might make this approach moot).

Alternative:
Since you mentioned a user filling out a form - you could pretty easily have a content type called "Taxonomy Term" or something with the needed Taxonomy fields, then use workflow/Rules to send the submission to an admin, upon approval use Rules or custom code to create a new taxonomy term.


Google Analytics Reports with Background Process module (non-blocking http request)

This is not possible in the manner that you described. Sure you can make a chain of asynchronous calls, the browser AJAX request to Drupal then Drupal making a non-blocking HTTP request to the GA API. However, your AJAX call won't have data to use.

The Background Process & HTTPRL (check out the project page image) work by the request being one way; they are calling out to a URL that will trigger some background action that doesn't need to communicate back (e.g. some batch job or page crawler cron task). In your case, you need the GA API to communicate back with Drupal then Drupal to communicate back with the browser. There's no getting around that.


Panels vs. Entity View Attachments (EVA)

Whether you need a module or not depends on your use case; you certainly don't want to install and enable a bunch of modules that you don't need, as this will slow down your site and can cause other problems.

In this context, if Panels does what you need alone, then you don't need any other modules (and Panels can do so many things that it generally is sufficient by itself).

If you're committed to Panels, there's probably no need to use EVA-- and certainly if you're asking whether there's a need, you should try doing everything in Panels first, as that will be easier to maintain long-term.

EVA would be better if you wanted something more lightweight and just want to make changes for a few things; Panels is more useful if you want to take full control over the layout.  EVA can also be used in circumstances where Panels integration isn't finished (e.g., Revisioning module and Panels' node add/edit forms).

That said, these two modules really aren't all that similar.  Usually the layout modules are considered to be Panels and Context.  Entity View Attachments is really just an extension of the attachment feature provided by the Views module.  In that way, you could think of it as competing with content panes, another type of display provided by Views specifically for Panels (for reference, this question relates to the differences between attachments and content panes).


Add new field to custom content entity type

After installation, you need to handle updating the schema yourself. There are some different scenarios, some are more easy to deal with than others. The most complex is moving data from one field type to another which means you would have to do a migration of data.

Anyways Drupal core has the entityDefinitionUpdateManager() which can be accessed doing \Drupal::entityDefinitionUpdateManager(). This manager can do a lot of the things you need to do when you change the base fields of content entities.

Creation of a new field is pretty easy, and all you need to make your own update hook:

function hook_update_8xxx() {
  \Drupal::entityDefinitionUpdateManager()->applyUpdates();
}

This will apply all updates to all entities. This can generally be used for most things, but if there are data in Drupal has a failsafe that throws an exception to make sure it doesn't accidentally mess data up. During the beta the system attempted to handle data migration as well, but it didn't work well so it was decided that this is something module maintainers should do themselves.


With a WSOD upon deployment of a site, should I first clear the cache, check watchdog logs, or check the Apache logs?

Yes. Because of the variety of possible Drupal stack configurations, it's impossible to say you'll always find your error in an Apache log. However, a WSOD generally means PHP has hit a fatal error and it's configured not to dump sensitive debug info to screen.

If that's the case, you might not even have a working Drupal app to make use of its tools like cache clearing, watchdog, etc., so it's best to find where those PHP errors are dumped so you can get Drupal into a bootstrapped state.

Of course, you should know your stack better than anyone else so a cache clear could eliminate the issue if you know the source of the problem. But if you're unsure, Apache logs are a good first start.


Changed Comment Module and database table - how to revert changes?

First: Do not hack core!

To restore your site to a stable state, revert to the default theme, back-up your database and the sites/ sub-directory and anything below it.  Then download a fresh copy of the core and install it. Finally, restore the sites/ sub-directory, your database, and the theme.

Having extra tables in the database that Drupal does not know about does not do any harm, but you may drop those tables that you created yourself before backing up the database.


An easier way to address multiple CSS loads, is to cache and compress the CSS. You can do so by going to /admin/config/development/performance and selecting "Aggregate and compress CSS files"

But if you must have them load on separate pages I'd recommend doing it the Drupal way; separating them by content types or blocks, forms, not by URI. The simplest way to do it, is to use Theme Hooks.

For instance, to include a yourthemedirecotry/css/MYTYPE.css for content type MYTYPE;

Copy /modules/node/node.tpl.php into your theme directory and rename it to node--mytype.tpl.php.
Insert <?php drupal_add_css(path_to_theme() . '/css/mytype.css', array ('group' => CSS_THEME)); ?>
Don't forget to flush cache.

From now on, nodes with content type MYTYPE will include a yourtheme/css/mytype.css.

Likewise, you can insert CSS into specific blocks, fields, page. For more options, see Theme Hooks and drupal_add_css.


view infinite scroll: how to exec a js function after loading items ?

You should be able to use Drupal JS Behaviors. Views Infinite Scroll should fire off Drupal behaviors on an AJAX request. You would need to add custom JS to your pages that use infinite scrolling.

Here's an example where someone uses this to add a class to views rows loaded from Views Infinite Scroll.

Drupal.behaviors.myBehaviorName = {
  attach: function (context, settings) {
    // run your code here
  }
};


how to add username and password field in commerce order

This is currently being handled via the Rules module. The rule that is enabled by default creates the user via the "Create a new account for an anonymous order" rule. There is no way to insert a password in here but is up to the user to open the link in their email and set their password manually.


The path_processor_outbound service only work after clearing the cache

That's because those links get cached and Drupal doesn't know by what to vary those caches.

That's why you receive that additional argument, $bubbleable_metadata. You need to use it to specify that our changes depend on a certain url parameter. See https://www.drupal.org/docs/8/api/cache-api/cache-contexts and https://www.drupal.org/docs/8/api/render-api/cacheability-of-render-arrays.

You need something like this:

if ($bubbleable_metadata) {
  $bubbleable_metadata->addCacheContexts(['url.query_args:your_parameter']);
}


"Content Type Edit/Add" gives Whitescreen, no errors loged, what to do?

OK, resolved. Thanks for your help,  Triskelion - thanks to you, I understand  xampp better.
There were two things
1) xampp giving no error messages. After looking in vain for error messages, I upgraded to xampp 1.8.0, and when I tried to get to the page that caused problems, I got a full error message.

 Additional uncaught exception thrown while handling exception.Original ODOException: SQLSTATE[HY000]: General error: 2006 MySQL server has gone away: SELECT * FROM {system} WHERE type = &#039;theme&#039; OR (type = &#039;module&#039; AND status = 1) ORDER BY weight ASC, name ASC; Array ( ) in system_list() (line 165 of /opt/lampp/htdocs/twotrees/includes/module.inc). Additional
PDOException: SQLSTATE[HY000]: General error: 2006 MySQL server has gone away: SELECT ff.* FROM {filter_format} ff WHERE (status = :db_condition_placeholder_0) ORDER BY weight ASC; Array ( [:db_condition_placeholder_0] =&gt; 1 ) in filter_formats() (line 409 of /opt/lampp/htdocs/twotrees/modules/filter/filter.module).
Uncaught exception thrown in session handler.
PDOException: SQLSTATE[HY000]: General error: 2006 MySQL server has gone away in _drupal_session_write() (line 209 of /opt/lampp/htdocs/twotrees/includes/session.inc).

Still, no messages in error_log. Where should I look for them?

2) I searched through the web, and found similar problems for example [http://drupal.org/node/1542432]. It turned out this is a XAMPP mysql memomry limit problem. I changed the value 'max_allowed_packet' to 100M in 'my.cnf'.

My site works now. I was really scared!


Views has a cache plugin for no caching which you can configure in UI. Better use this method, setting a cache max-age in a hook might not be enough to disable all caching in a view. Also you can't control traffic from anonymous users by this. If you have dynamic views you want to deliver to anonymous users uninstall the Internal Page Cache and set the Cache-Control headers in /admin/config/development/performance accordingly.


Why do I get "Undefined index: mail en comment_form_validate()"?

From your error messages it seems you are calling something like this

$form['field_name']['en'][0]['value']

Or something like that.  Which means the array key "en" is not available.  If you are not using languages, then I suggest using LANGUAGE_NONE as your key selector.

To prevent these types of messages you should perform an isset on the array element to make sure it exists before trying to retrieve a value from it.


Take a look at the Login Destination and the LoginToboggan modules. They should do what you want.
The first module allows you to customize the destination to which a user is redirected after logging in, registering to the site (7.x), using a one-time login link or logging out (7.x). The destination can be an internal page or an external URL. It is possible to specify certain conditions like referring pages, or user roles, and make the destination depend upon them. You may use PHP snippets to provide custom conditions and destinations. It is also possible to keep users on the currently visited page after logging in or out.


Disable Ubercart download limits accumulation

Set the download limit as Unlimited, then at the next time user click on add to cart button, then check this product is he already checkout or not (for this you can use order table). If it is already purchased by that user, then you can redirect him separate page or you can display a message about the same.


'The alias is already in use' when editing a node that had an alias generated programmatically

Turns out whenever you perform this

\Drupal::service('path.alias_storage')->save("/node/" . $node->id(), $url_alias, "en");

It generates a new alias every time even if the path alias already exists. I was able to resolve the issue by performing checks to see if the path already exists like so:

if (!\Drupal::service('path.alias_storage')->pathHasMatchingAlias('/node/' . $node->id()) && !empty($node->id())) {
    $path = \Drupal::service('path.alias_storage')->save("/node/" . $node->id(), $url_alias, "en");
}


How Do I Change My Drupal Admin Password From a Drupal Test Install on My Local Machine

short version use "drush uli"
longer version have a local install with known password, go to your cpannel -> phpMyAdmin change the password to the known one. - done


Custom sort to preserve order of referenced nodes

Draggable Views will let you define your own manual sort, and keep it consistent across different displays.


Comment template for specific comment type

Enable Twig Debugging, then you'll get template suggestions printed as HTML comments directly into the markup.

I did that and got the following output:

<!-- THEME DEBUG -->
<!-- THEME HOOK: 'comment__field_my_comment_field__article' -->
<!-- FILE NAME SUGGESTIONS:
   * comment--field-my-comment-field--article.html.twig
   * comment--field-my-comment-field.html.twig
   x comment.html.twig
-->
<!-- BEGIN OUTPUT from 'core/themes/classy/templates/content/comment.html.twig' -->

So, the templates are supposed to be named like the following pattern:

comment--field-name-of-the-comment-field-in-the-content-type--content-type.html.twig
comment--field-name-of-the-comment-field-in-the-content-type.html.twig


Set image format of field_view_field image field

Yes, you can set the field value display settings as a parameter to field_view_field

e.g:

// Customize field display settings.
$display_settings = array(
  'label' => 'hidden',
  'settings' => array(
    'field_multiple_limit' => '1',
    'field_multiple_limit_offset' => '0',
    'image_link' => 'content',
    'image_style' => 'thumbnail',
  ),
  'type' => 'image',
  'weight' => 0,
);
// Get field value
$logo_var = field_view_field('user', $user, 'field_business_logo', $display_settings);


Automatically importing module-provided translations during installation

Per the documentation:
https://api.drupal.org/api/drupal/core%21modules%21locale%21locale.api.php/group/interface_translation_properties/8.4.x

  Streamwrappers can be used in the server pattern definition. The interface translations directory (Configuration > Media > File system) can be addressed using the "translations://" streamwrapper. But also other streamwrappers can be used.

There are several examples given for valid server pattern definitions using different stream wrappers.

EDIT

I see what you mean about not wanting to use the translations:// stream wrapper.

Have you tried using the pattern definition exactly as given in the answer you cited?

modules/custom/example_module/translations/%language.po

If you do that, you should also take the name of your module out and just name the file fr.po.

Then make sure that you update translations with Drush:

drush locale-check && drush locale-update && drush cr

If that doesn't work, hopefully someone else can help, because I'm stumped.


You need to use:

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

Then, dump the $account object and you will see profile field.


How should I configure the trusted hosts setting?

I don't know if I was introducing a problem by editing the settings.php off line and then uploading it but decided to edit it with the editor in the file manager on cpanel.  I first changed the permissions on the default folder to 755 and opened the folder.  Then I highlighted the settings file and changed the permissions to 755.  Then I clicked the edit button and located the Trusted Host settings and copied the code.  I then pasted it AT THE END of the settings.php file and made the necessary changes to reflect my domain and saved the file and closed the setting file.  In a different window, I had the website status page loaded and just refreshed it.  IT worked!  I don't know why doing it this way worked (editing the file on the server vs offline and uploading it.) but it did! Then I just change the file permissions back to what they were .


Token Filter module to work on Menu URL and Title

No, not by itself. The Token Filter module's functionality adds a token input filter to text formats in Drupal. The only field types that can use text formats are the 3 Text (formatted) field types, not the Link field type.

One can only speculate on the comment's solution you refer to. Text Formats/Input filters are designed to allow HTML input that should be filtered for presentation. It would be an odd-use-scenario to apply that to a link field.


i think you should return a  render array in your theme function
  array('render element' => 'form')


How to create a module wide variable that refreshes every page load?

The variable_set() and variable_get() functions are made to set/get a persistent variable. So they should not be used to persist data within a single page request. The drupal_static() function is made for this task and is well documented. Off course, you could also go with a static variable without bothering about drupal_static(). But drupal_static() will make your code more maintainable and future proof.

/**
 * Set or get the shared foo variable.
 *
 * @param $new_value
 *  (optional) If set, the new value to assign to the foo variable.
 *
 * @return
 *  The value of the foo variable. If $new_value is set this would be
 *  the previous value.
 */
function MODULE_foo($new_value = NULL) {
  $value = drupal_static(__FUNCTION__, NULL);
  $previous_value = $value;
  if ($new_value !== NULL) {
    $value = $new_value;
  }
  return $previous_value;
}


Create multiple users roles and views at the same time

If you set up Drush, which is is a command line shell and Unix scripting interface for Drupal, then you can create a role with the command:

drush role-create

This command accepts and requires 2 arguments, the first one defines the machine name of the role and the second one the human readable name. For example:

drush role-create 'my_new_role' 'My New Role'

Would create the role 'My New Role' with a machine name 'my_new_role'

Drush can also be used to quickly create views. Due to the variety of possible setups depending on your use case, it is probably best to start by looking at the documentation on https://drushcommands.com


Based on the comments, and narrowing down the problem to the Rules module itself, or its integration with the mail system:

Tokens work elsewhere
Tokens within the body of the message work but not the from field
No templates are used
Core mail as well as third-party mail are affected
Clearing the cache, including the rules one, had no effect

It would appear to be a bug in the Rules module or the mail delivery part of it. I would suggest adding an issue to the Rules issue queue and see if they can further explore options for correcting the problem.


Append filter info to URL when using AJAX in 'View' module

What you want to do is manipulate the browser's URL even though there are no page reloads, only AJAX requests taking place.

You are actually in need of the HTML5 History API.

And luckily there seems to be a module available, specific to your case:

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

Give this a try and good luck!


Replacement pattern in view field template

In view template file of body field, write this code;

$nid = $row->nid;
$body = $row->body;
if($nid == 1):
  $view = views_get_view('VIEWS_MACHINE_NAME');
  $view->set_display('DISPLAY_ID');
  $new_view = $view->preview('DISPLAY_ID');
  print render($new_view);
else :
  print $body;
endif;


The image path changes to absoulute path.


Drupal 7 e-mail driven forum (mailcomment)

This is in no way trivial since you will need to setup an email SERVER to react to certain emails and trigger a drupal 7 process. I have been tinkering with a bunch of modules and the most promising is og_mailinglist Within the module you will find a lot of information and Documentation of how to achieve this. You might even want to read through this to meet the makers

Even so the requirements are really tough and it is a project of several weeks if not months. most customers think this should be easy, well it is not. And it has security implications that have to be thoroughly solved. You are allowing an email to add content!

Good luck.


How can I add a simple node creation form to a page?

the only way I can see this being possible, would be creating a custom node/add page for your content (see How can I theme the template for edit or add a node for a specific content type?) and then using Panels to create a custom page with your node on top and then your view directly below.

I would be interested to know if anyone else has any better/easier suggestions of course. +1 for question :)


How do i attach a an element to user account?

As reported in users.data column replaced with user_data API, the equivalent of using the user.data column, in Drupal 8, is using the user.data service.

So, if in Drupal 7 you used $value = $account->data['mymodule_xyz'];, in Drupal 8 you will use the following code.

$value = \Drupal::service('user.data')->get('mymodule', $account->id(), 'xyz');

The code to set its value is the following one.

\Drupal::service('user.data')->set('mymodule', $account->id(), 'xyz', $value);

As usual, when possible, use dependency injection to get the service, instead of using the \Drupal class.


Ajax reloading a view with ajax mini pager

After going through ajax_views.js and understanding view-dom-id element structure, finally I could able to get this done.

In ajax response object, there are 3 callbacks, In the last 'insert' callback, I got data with command to 'replacewith' and a DOM selector (unique dom for views wrapper with '.view-dom-id-xxxxx'). So I did replace the new content like :

$(".view-dom-id-" + vDomId).replaceWith(response[2].data);

Then I got the content with existing context, all I had to do then is re-attach the 'ViewsAjaxView' behavior as found in ajax_view.js

Drupal.attachBehaviors('ViewsAjaxView');

This attachBehaviors function will take care of binding ajax pagination to my newly altered views data.

I still feel, as if this can be more simpler like running all callbacks I get in response variable in success. I will post more if I get into. Hopefully someone gets some help from this.

Anybody have idea to run those commands?


How can I display the block only to the content types and a specific page?

There is another way to answer your question, without PHP in the block settings: you can use the Rules block visibility module for this. Here is a quote from its project page:

  The Rules block visibility module allows Rules components to be used to control block visibility. This provides Drupal administrators and developers extreme flexibility in controlling when blocks should be displayed on their websites, in addition to the default visibility options provided by Drupal.

  The general idea is that if you can do it with Rules, you can use it to control block visibility, so the possibilities are limitless.

  Need to show a block only for users registered more than a month ago?

  Perhaps you have a block that must be shown only between 8am-5pm on weekdays?

  What about displaying or hiding a block based on current weather conditions?

  All of this can be done by using Rules block visibility.

With that, and as per the "if you can do it with Rules, you can use it to control block visibility" above, you've reduced your question to making Rules "check the path of the current page" (so that the appropriate menu block is shown on the appropriate pages). And combine this with a check in such rule for your specific content type ("Cities we serve").

For an illustration of how to use this module, refer to my answer to "How to show blocks by url, when nodes have multiple paths?". It includes some Rules Components (in Rules export format), which you should replace by your variations to make it match your specific question.

To actually "determine the path structure in rules", you might want to use a Rules Condition using a regular expression. Similar to the Rules Condition in the rule I included in my answer to "How to automatically skip intermediate redirects?".

Using regular expressions opens up many more situations (on top of the Rules block visibility module) where this solution can work. If you're not familiar with Regular Expressions (not obvious ...), then maybe you also want to look at my answer to "How do I suppress a warning or error message for site users?".

Bonus:

This approach does NOT require the PHP filter to be enabled either (which you should try to avoid whenever possible) ... Refer to "PHP in database: bad practice but" for more details about this.


Setting a Twig to a specific Form Container

You could try to add your own template suggestion via hook_theme_suggestions_HOOK_alter, which would mean hook_theme_suggestions_container_alter. There you might target the container by id or some other attribute (id does not seem promising here).

The container.html.twig does only provide a wrapping div around other content. While you could add more html to this, you might have to think about if container.html.twig is the right place to start here.


Complex View Contextual Filter with User Relationships — how would I achieve this?

Fixed it.

Last night I noticed that I have the ability to add PHP Filter Criteria (which I'd somehow not noticed before!), coming from the Views PHP Module. It turns out that this allows me to enter arbitrary PHP and it will take anything that returns TRUE as meaning the row should be removed from the resultset.

So I added a Filter Criterion that checks the SQL query Select * From user_relationships Where requester_id = :current_uid And requestee_id = :follower_uid and I return TRUE; if that query results in more than zero rows.

To do this, I needed to add new Fields, both set to be "Excluded from display":

User: User ID (bound to Requester), with an administrative title of "Follower UID (not displayed)". This gets passed as the variable $row->uid
User: User ID (bound to Requestee), with an administrative title of "Current UID (not displayed)". This gets passed as the variable $row->uid_1

Then in a new PHP Filter Criterion, I created a filter as follows:

$filter_result = db_query('Select * From user_relationships '.
  'Where requester_id = :current_uid And requestee_id = :follower_uid',
    array(
        ':current_uid' => $row->uid_1,
        ':follower_uid' => $row->uid,
    ));

$count = $filter_result->rowCount();

return $count > 0;

Then those superfluous rows no longer appear in my output.

For some reason, I do need to assign $filter_result->rowCount() to the variable $count; trying return $filter_result->rowCount() > 0; directly didn't want to work for some reason.

But problem solved. At last  :o)

Edit: I've just corrected the Field bindings, having noticed I was doing it differently in two different places and  I'd put the wrong one in my answer here. Note that the User Relationships fields "UR: Requester user ID" and "UR: Requestee user ID" do not output user IDs, so do not work in this query; you do have to use two different "User: User ID" Fields, one bound to each end of the relationship. (Irritatingly, this means they have the really unhelpful variable names of $row->uid and $row->uid_1 when passed to the PHP Field; I haven't yet found a way around this.)


Again, I will give my own answer here:

After reading about tokens, pathauto and views, it appears that exposed filters DO NOT work with path (dixit Merlinofchaos in https://drupal.org/node/1257952#comment-4898854 .) So what I am experiencing is normal.

However, views have a "Use Ajax" option that is specifically there for exposed filters. Enabling it solves the issue and keep the url clean (without the *0?items_per_page=30* part.)

It does so because ajax does not refresh the page, so the url remains the same (www.example.com/videos/sports in this case.)   :)


How to pass the Body field from a View to Rules?

I assume you performed the steps similar to what is documented in my answer to "How to send out email based on matching taxonomy terms in user profiles?". And while doing so, you probably used a field name like body-from-view in the "Rules" display of your view. I'm not sure if it is the only way to get it to work, but below is a possible solution to answer your question ...

Part 1 - Getting it to work

Define the body field 3 times in your view

When adding the "body" as a field in your view, add that field 3 times. And when configuring these Views fields, make sure to use these field formatters:

Default (for the 1st "body" field).
Trimmed (for the 2nd "body" field).
Summary or trimmed (for the 3rd "body" field).

Select the 3 body fields 3 times in your view

When you edit the Rules settings of your view (by using the link that says "edit field info"), use 3 separate variables for each of the 3 body fields, e.g using machine names that look something like so:

body-default
body-trimmed
body-summary-or-trimmed

I'm not sure (yet) about the most appropriate "data type" to use for these 3 variables, but in my case I just used "text".

Create your Rules Component using appropriate tokens

Within the Rules Actions of your Rules Component, use the link that says Add view loop to add a Views loop, and select the "Rules" display created in the previous step.
Within that Views loop add whatever Rules Action that fits your needs. E.g. to get started, just perform "Show a message on the site". At that point, you should have access to these token values that you're looking for (if you use the same machine names as suggested above):
[body-default:value]
[body-trimmed:value]
[body-summary-or-trimmed:value]

Part 2 - Showtime

Here is an example of the execution of a rules component, in which I implemented what's mentioned in "Part 1", using a Rules Action to show a message on the site, and which looks like so:

Details about node with id = [node-nid:value] and title = [node-title:value]:

- body-summary-or-trimmed = [body-summary-or-trimmed:value]

- body-trimmed = [body-trimmed:value]

- body-default = [body-default:value]

After executing it, and with 3 nodes that were included in my Views result, the result looks like so:

Details about node with id = 163 and title = Node with summary and separator line:

- body-summary-or-trimmed =
This is the summary of this node ... and there is really nothing else after this (in this summary) ...

- body-trimmed =
This is the body of this node, which does have a summary also ...

It has multiple lines, and the separator line is inserted right here ...

- body-default =
This is the body of this node, which does have a summary also ...

It has multiple lines, and the separator line is inserted right here ...

And from here on there is even more content (after the separator line ...)

Some more lines (1).

Some more lines (2).

Some more lines (3).

Some more lines (4).

Details about node with id = 162 and title = Node without a summary but with a separator line:

- body-summary-or-trimmed =
This is the body of a node which does not have a summary ...

It has multiple lines, and the separator line is inserted right here ...

- body-trimmed =
This is the body of a node which does not have a summary ...

It has multiple lines, and the separator line is inserted right here ...

- body-default =
This is the body of a node which does not have a summary ...

It has multiple lines, and the separator line is inserted right here ...

And from here on there is even more content (after the separator line ...)

Some more lines (1).

Some more lines (2).

Some more lines (3).

Some more lines (4).

Details about node with id = 161 and title = Node without a summary and without a separator line :

- body-summary-or-trimmed =
This is the body of this node, which does NOT have a summary ...

It has multiple lines, but no separator line  ...

- body-trimmed =
This is the body of this node, which does NOT have a summary ...

It has multiple lines, but no separator line  ...

- body-default =
This is the body of this node, which does NOT have a summary ...

It has multiple lines, but no separator line  ...

And there is even more content ...

Some more lines (1).

Some more lines (2).

Some more lines (3).

Some more lines (4).

Component rule: Views Rules demonstration has been executed.

Part 3 - Pieces of the puzzle

Exported View

Here is an export of the view I created (use the Views UI to import it in your own site, adapt the filter criteria to fit your needs):

$view = new view();
$view->name = 'details_about_nodes';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'node';
$view->human_name = 'Details about nodes';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'Details about nodes';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '10';
$handler->display->display_options['style_plugin'] = 'table';
$handler->display->display_options['style_options']['columns'] = array(
  'title' => 'title',
);
$handler->display->display_options['style_options']['default'] = '-1';
$handler->display->display_options['style_options']['info'] = array(
  'title' => array(
    'sortable' => 0,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
);
/* Field: Content: Title */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'node';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['label'] = '';
$handler->display->display_options['fields']['title']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['title']['alter']['ellipsis'] = FALSE;
/* Field: Content: Nid */
$handler->display->display_options['fields']['nid']['id'] = 'nid';
$handler->display->display_options['fields']['nid']['table'] = 'node';
$handler->display->display_options['fields']['nid']['field'] = 'nid';
/* Field: Content: Body */
$handler->display->display_options['fields']['body_1']['id'] = 'body_1';
$handler->display->display_options['fields']['body_1']['table'] = 'field_data_body';
$handler->display->display_options['fields']['body_1']['field'] = 'body';
$handler->display->display_options['fields']['body_1']['label'] = 'Body - Summary or trimmed';
$handler->display->display_options['fields']['body_1']['type'] = 'text_summary_or_trimmed';
$handler->display->display_options['fields']['body_1']['settings'] = array(
  'trim_length' => '200',
);
/* Field: Content: Body */
$handler->display->display_options['fields']['body_2']['id'] = 'body_2';
$handler->display->display_options['fields']['body_2']['table'] = 'field_data_body';
$handler->display->display_options['fields']['body_2']['field'] = 'body';
$handler->display->display_options['fields']['body_2']['label'] = 'Body - Trimmed';
$handler->display->display_options['fields']['body_2']['type'] = 'text_trimmed';
$handler->display->display_options['fields']['body_2']['settings'] = array(
  'trim_length' => '200',
);
/* Field: Content: Body */
$handler->display->display_options['fields']['body']['id'] = 'body';
$handler->display->display_options['fields']['body']['table'] = 'field_data_body';
$handler->display->display_options['fields']['body']['field'] = 'body';
$handler->display->display_options['fields']['body']['label'] = 'Body - Default';
/* Sort criterion: Content: Post date */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'node';
$handler->display->display_options['sorts']['created']['field'] = 'created';
$handler->display->display_options['sorts']['created']['order'] = 'DESC';
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'node';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = 1;
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;
/* Filter criterion: Content: Type */
$handler->display->display_options['filters']['type']['id'] = 'type';
$handler->display->display_options['filters']['type']['table'] = 'node';
$handler->display->display_options['filters']['type']['field'] = 'type';
$handler->display->display_options['filters']['type']['value'] = array(
  'page' => 'page',
);
/* Filter criterion: Content: Nid */
$handler->display->display_options['filters']['nid']['id'] = 'nid';
$handler->display->display_options['filters']['nid']['table'] = 'node';
$handler->display->display_options['filters']['nid']['field'] = 'nid';
$handler->display->display_options['filters']['nid']['operator'] = '>';
$handler->display->display_options['filters']['nid']['value']['value'] = '10';

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['path'] = 'details-about-nodes';

/* Display: ListToCreateRulesLoop */
$handler = $view->new_display('views_rules', 'ListToCreateRulesLoop', 'views_rules_1');
$handler->display->display_options['pager']['type'] = 'some';
$handler->display->display_options['rules_variables'] = array(
  'title' => array(
    'enabled' => 1,
    'rendered' => 0,
    'type' => 'text',
    'label' => 'Content: Title',
    'name' => 'node_title',
  ),
  'nid' => array(
    'enabled' => 1,
    'rendered' => 0,
    'type' => 'integer',
    'label' => 'Nid',
    'name' => 'node_nid',
  ),
  'body_1' => array(
    'enabled' => 1,
    'rendered' => 1,
    'type' => 'text',
    'label' => 'Body - Summary or trimmed',
    'name' => 'body_summary_or_trimmed',
  ),
  'body_2' => array(
    'enabled' => 1,
    'rendered' => 1,
    'type' => 'text',
    'label' => 'Body - Trimmed',
    'name' => 'body_trimmed',
  ),
  'body' => array(
    'enabled' => 1,
    'rendered' => 1,
    'type' => 'text',
    'label' => 'Body - Default',
    'name' => 'body_default',
  ),
);

Exported Rules Component

Here is an export of the Rules Component I created (use the Rules UI to import it in your own site, adapt the Rules Conditions to fit your needs):

{ "rules_views_rules_demonstration" : {
    "LABEL" : "Views Rules demonstration",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "IF" : [
      { "user_has_role" : {
          "account" : [ "site:current-user" ],
          "roles" : { "value" : { "3" : "3" } }
        }
      }
    ],
    "DO" : [
      { "VIEW LOOP" : {
          "VIEW" : "details_about_nodes",
          "DISPLAY" : "views_rules_1",
          "ROW VARIABLES" : {
            "node_title" : { "node_title" : "Content: Title" },
            "node_nid" : { "node_nid" : "Nid" },
            "body_summary_or_trimmed" : { "body_summary_or_trimmed" : "Body - Summary or trimmed" },
            "body_trimmed" : { "body_trimmed" : "Body - Trimmed" },
            "body_default" : { "body_default" : "Body - Default" }
          },
          "DO" : [
            { "drupal_message" : { "message" : "\u003Chr \/\u003E\r\nDetails about node with id = [node-nid:value] and title = [node-title:value]:\u003Cbr \/\u003E\u003Cbr \/\u003E\r\n- \u003Cstrong\u003Ebody-summary-or-trimmed\u003C\/strong\u003E = [body-summary-or-trimmed:value]\u003Cbr \/\u003E\r\n- \u003Cstrong\u003Ebody-trimmed\u003C\/strong\u003E = [body-trimmed:value]\u003Cbr \/\u003E\r\n- \u003Cstrong\u003Ebody-default\u003C\/strong\u003E = [body-default:value]\u003Cbr \/\u003E\r\n\u003Cbr \/\u003E\u003Chr \/\u003E" } }
          ]
        }
      }
    ]
  }
}


Change remove from cart button to an image button

You need to unset the #value on your image_buttons:

  $item['#type']='image_button';
  $item['#src']='sites/all/themes/mytheme/images/trash.svg';
  $item['#alt']='Remove';
  unset($item['#value']); // this line here

The line item that is deleted is determined by the #triggering_element in your $form_data. This element is determined by a function _form_button_was_clicked($element, &$form_state) in form.inc in the core.

It seems that when you a #value has been set on your image_button, every image button is detected to have been clicked.

  // line 2227 in form.inc
  elseif (!empty($element['#has_garbage_value']) && isset($element['#value']) && $element['#value'] !== '') {
    return TRUE;
  }

That means at the end of the ride, the last image button is always set as the #triggering_element, and the last line item is always removed.

Unsetting the #value fixes that. Setting it to an empty string doesn't, somehow.


Is there a way to provide theme name suggestion for form elements?

Seems you have to implement two hooks. One to add the suggestion, and one to define a template. hook_theme_suggestions_HOOK_alter and template_preprocess_form_element (aka hook_preprocess_HOOK).

/**
 * Implementation of hook_theme_suggestions_form_element_alter().
 */
function MYTHEME_theme_suggestions_form_element_alter(array &$suggestions, array $variables) {
  if (\Drupal::service('path.current')->getPath() == '/user/login') {
    $suggestions[] = $variables['theme_hook_original'] . '--user-login';
  }
}

/**
 * Implementation of hook_preprocess_form_element().
 */
function MYTHEME_preprocess_form_element(&$variables, $hook, &$info) {
  $info['template'] = 'form-element--user-login';
}

Source: Form element template suggestion has no effect.


How do I make the bootstrap dropdown menu work?

Add dependency in libraries.yml file just below the bootstrap js file:

dependencies:
    - core/jquery
    - core/drupal.ajax
    - core/drupal
    - core/drupalSettings
    - core/jquery.once


How do I generate a list of "standard" clean URLs?

Those are paths in Drupal lingo. Clean URLs come from a server configuration that rewrites the path query parameter away (e.g. http://example.com/?q=user/login vs http://example.com/user/login ).

To get at the heart of your question, registered paths can be found in the menu_router table of your Drupal installation. There is no one standard set of paths since any module can register a path. Thus, the "standard" result will vary based on what type of install you have (e.g. minimal vs standard vs contrib installation profile) plus other configurations.

For example, this code snippet will dump the list of paths that the 6 core modules are registering.

  $implementations = module_implements('menu');
  $core = array('field', 'field_sql_storage', 'filter', 'node', 'system', 'user');
  $paths = array();
  foreach($implementations as $implementation) {
    if(in_array($implementation, $core)) {
      $paths = array_merge(array_keys(call_user_func("${implementation}_menu")), $paths);
    }
  }
  var_dump($paths);

However, you'll find the node paths will vary across your installation based on the your defined node types (e.g. node/add/NODE_TYPE ).


Try the Services node resource extension module

Extends functionality for the node resource available through services module.
Additional Resources:
-lookup - provides a resource to request a node through the url alias.
-POST data = [ 'alias' => the url alias. ]


"Is all of" view search doesn't work with the module "Better exposed filter"

No, It's a bug with the Better Exposed Filter module. From the looks of it, something is causing a '0' value to be added as a part of the WHERE clause.

You can see this in action by toggling the Allow multiple selections filter option; when the option is off you can select a non - Any - value to filter the view as expected; when the option is on any selection appends '0' value to the filter.

From looking at your linked issues, they look potentially related but not the same. You should look through the BEF module issue queue and if it's not posted yet, post it there to be reviewed.


help using hook_url_outbound_alter() to append "#id" to node/edit url

The $options parameter passed by reference to the hook_url_outbound_alter() implementations is described as follows. (Emphasis is mine.)

  $options: A set of URL options for the URL so elements such as a fragment or a query string can be added to the URL.

What that documentation page doesn't explicitly say is that $options is the same array url() accepts, which includes the following array indexes.

  'query': An array of query key/value-pairs (without any URL-encoding) to append to the URL.
  'fragment': A fragment identifier (named anchor) to append to the URL. Do not include the leading '#' character.


more than one content type in a condition?

You can use in_array.

$types = array('one', 'two', 'three');

if (!in_array($variables['node']->getType(), $types)) {
  // code
}


You can also use fields to add additional fields to a user or user the profile2 module. There's a good chance, that you don't even have to code a line ;-).

If you need: You can change any form in Drupal with hook_form_alter. This way you can add more functionality to the sign up form.


If revisions aren't important you might want to fork your website codebase and try installing Field SQL NoRevisions module, by removing the "revisions" of Nodes node creation and fetching takes half the number of normal drupal queries.

Depending on you Read vs Write ratio you also might want to consider moving some of your Fields into a NoSQL database such as MongoDB.


You need to create that file - copy the node.tpl.php file to

node--your_content_type.tpl.php

and take it from there. Here's the relevant page from the handbook for Drupal 7

https://drupal.org/node/1089656

Alternatively, if you're just getting started with node templates, you may find it easier to install and enable the content templates module so you can add and modify node templates from the administrator backend:

https://drupal.org/project/contemplate

  The Content Template (a.k.a. ConTemplate) module allows modification of Drupal's teaser and body fields using administrator defined templates. These templates use PHP code and all of the node object variables are available for use in the template. An example node object is displayed and it is as simple as clicking on its properties to add them to the current template.


Thanks to Tyler. I follow his suggestion and have solved this by adding the theme_pager_link() to app/themes/my_theme/my_theme.js. Here is what I added:

function my_theme_pager_next(variables) {
  try {
    var html;
    variables.page = parseInt(variables.results.view.page) + 1;
    var link_vars = {
      text: 'Next Page',
      attributes: {
        'class': 'pager_next',
        'data-icon': 'fast-forward'
      }
    };
    html = theme_pager_link(variables, link_vars);
    return html;
  }
  catch (error) { console.log('my_theme_pager_next - ' + error); }
}

function my_theme_pager_previous(variables) {
  try {
    var html;
    variables.page = parseInt(variables.results.view.page) - 1;
    var link_vars = {
      text: 'Previous Page',
      attributes: {
        'class': 'pager_previous',
        'data-icon': 'fast-backward'
      }
    };
    html = theme_pager_link(variables, link_vars);
    return html;
  }
  catch (error) { console.log('my_theme_pager_previous - ' + error); }
}

now the pager become like this:


Search page summary customization using views

Yes you need to use fields. One for the title, one for the teaser and any additional fields you want to add in. You can configure the amount of text that appears in the teaser so you can get your two lines of text.


Is there any reason Backup & Migrate leaves all the .info files around?

There doesn't appear to be any value to keeping them.  To get rid of them, you can do something like this

cd /private/backup_migrate/scheduled  # where ever you keep this
for file in *.info; do gz_file=`echo "$file" | sed -e 's/.info//'`; if [[ ! -f "${gz_file}" ]]; then rm -f "${file}"; fi; done

This will preserve all *.info files that correspond to a *.gz file, and delete the rest.  It appears to be an oversight on the part of the Backup & Migrate module to leave all of these lying around.   (Apologies in advance to the module's maintainers if I'm mistaken on this:  I do not mean to be critical, and I appreciate your work!)

If you want to wrap all this up into a quick alias or function, you can put something like this into your ~/.bashrc or ~/.zshrc or whatever:

function cleanup_backups(){
  pushd /<youfillinthispart>/private/backup_migrate/scheduled
  for file in *.info; do
    gz_file=`echo "$file" | sed -e 's/.info//'`
    if [[ ! -f "${gz_file}" ]]; then
      rm -f "${file}"
    fi
  done
  pushd
}

(You'll have to make it a bit more complicated if you have subdirectories in your scheduled backups folder, but this should get you started.)


field_type_of_content is presumably a term reference field, so the value to set for it would be a term ID, not a term name. If you know the IDs for the destination terms, you can map them directly:

source:
  plugin: d7_node
  node_type: article
process:
  field_type_of_content:
    plugin: default_value
    default_value: 5   # Known D8 ID for the "Article" term

More robustly, you can use migrate_plus's entity_lookup plugin to translate the term name to a term ID:

source:
  plugin: d7_node
  node_type: article
  constants:
    term_name: Article
process:
  field_type_of_content:
    plugin: entity_lookup
    source: constants/term_name
    value_key: name
    entity_type: taxonomy_term
    bundle: type_of_content
    bundle_key: vid


You have to include phpunit/phpunit package in composer, alredy done if you took default drupal installation :

composer require phpunit/phpunit --dev

A file should be filled which describe yours testsuites, generally phpunit.xml

It looks like this ./phpunit.xml :

<phpunit bootstrap="web/core/tests/bootstrap.php" colors="true"
         beStrictAboutTestsThatDoNotTestAnything="true"
         beStrictAboutOutputDuringTests="true"
         beStrictAboutChangesToGlobalState="true"
         checkForUnintentionallyCoveredCode="false"
         printerClass="\Drupal\Tests\Listeners\HtmlOutputPrinter">

<php>
  <ini name="error_reporting" value="32767"/>
  <ini name="memory_limit" value="-1"/>
  <env name="SIMPLETEST_BASE_URL" value="http://drupal-8.localhost"/>
  <env name="SIMPLETEST_DB" value="mysql://drupal-8:drupal-8@localhost/drupal-8"/>
  <env name="BROWSERTEST_OUTPUT_DIRECTORY" value="/var/www/sites/default/simpletest"/>
</php>
  <testsuites>
    <testsuite name="testname1">
      <directory>web/modules/custom/your_module/tests</directory>
    </testsuite>
    <testsuite name="testname2">
      <directory>web/modules/custom/your_module2/tests</directory>
    </testsuite>
  </testsuites>
</phpunit>

In this example, drupal is located in ./web/ directory with ./vendor/, both in root path (./) .

You can add test for contrib module, but they are already tested (if they contain tests) when authors are pushing their sources to drupal.org ( https://www.drupal.org/pift-ci-job/1339317 ) :

<testsuite name="toolbar">
    <directory>./web/modules/contrib/admin_toolbar/tests/src/FunctionalJavascript</directory>
</testsuite>

Then you can run tests with :

./vendor/phpunit/phpunit/phpunit

To use a specific description file :

./vendor/phpunit/phpunit/phpunit -c phpunit-other.xml

To run a specific testsuite :

./vendor/phpunit/phpunit/phpunit --testsuite=testname1


How to delete 1600 users and 2500 posts?

You can use Views Bulk Operations, a module that allows to execute bulk operations on nodes, users, comments; it also permits to apply the selected operation to all the nodes, users, or comments using the Batch API. The batch API allows forms processing to be spread out over several page requests, thus ensuring that the processing does not get interrupted because of a PHP timeout, while allowing the user to receive feedback on the progress of the ongoing operations.


How to display block with term image field when viewing term node

I found my error: In the Format: Settings I had Grouping field N1 selected with the category term image field, which caused the duplication of the image.

Contextual Filters: Content has taxonomy term ID (with depth), Depth:0, Provide Default Value: Taxonomy term ID from URL > Load default filter from term page
Relationships: Entity Reference: VocabularyName - Require this relationship
Fields: Taxonomy Term - the term image field - using Views Distinct I select Filter Repeats


How to find the viewid and view-display-id?

Anyhow, I've created a new folder inside the theme root called views

This might not work if it's not inside the /templates folder. You should create a /templates folder if there isn't one already and then create a /views folder inside there.

So should be mytheme/templates/views and then you put all your Views' template files here.

  I don't understand how to find viewid or view-display-id

You can find the view name at the top left. Although if your view name were to have an empty space you would have to add a dash. Ex: If it was named "Front Page" then the view-id would be front-page

You can find the Display ID under Advanced, machine name.

Another way would be to right mouse click and inspect element with your browser


Use l() to construct URLs in Drupal.
$next_link = l('Next', 'node/' . $nids[$next]);
$previous_link = l('Previous', 'node/' . $nids[$previous]);


The Broken Link module seems to have views support, so you can use the Views Data Export module and a View of the data to export it.

If you'd prefer to go directly to the database, the module stores information in a table called broken_link so you can query that and use tools to move database results into a csv/excel if you'd like.


Trying to install Drupal modules and themes: keep getting error "does not contain any .info.yml files."

TL;DR you're trying to install a theme or module in Drupal 8, which doesn't contain the required files. You might be trying to install a Drupal 7 (or earlier) module by mistake, or it may not be a Drupal module at all.

The 8.x-dev branch of the Beale Street theme is most definitely not Drupal 8 compatible. It's a straight copy of the current 7.x-dev branch, so it hasn't been converted yet. The maintainer has said as much.

Converting a module/theme from 7.x to 8.x requires a lot more work than just adding a yaml file, and if you don't find one in a particular release you can safely assume it hasn't been converted yet.

There are lists of modules and themes on Drupal.org that are tagged with 8.x. As you've seen, not all of them are ready yet. Bear in mind quite a few will still be in -dev, so they're not expected to be useable.


How to create a select list that contains url links

With views you van create jump menu's: http://nodeone.se/en/learn-views-with-nodeone-part-18-jump-menu

You can use that view as a block on your page.

If you want to use it between your other fields, you can use the module https://www.drupal.org/project/viewfield. Add a field of type viewfield on your content type, choose the view you created earlier and pass the nid as parameter.


Is there a way to force drush to enable a module and ignore dependencies?

No, you can't.

But, https://www.drupal.org/node/2655104 was committed today, and it allows you to see what exactly is missing. Try patching your site with that to see the problem.


Modules are typically found in sites/site_name/module. That's often sites/default/modules.

If your site was installed by a non-standard installation profile, they could also be at /profiles/profile_name/modules, or somewhere else under the profile folder, instead.

To find it quickly, run this from your web root:

find . -name file_entity.info


Display related nodes with taxonomy hierarchy in a View

I was able to accomplish this functionality through the use of two separate views combined into one. I could not find a way for Drupal to handle this out of the box. Essentially I am using one view to show the nodes related to the child terms, and using another view to bring in the View displaying child related nodes and sort it under the parent term.
The modules I used were: Views PHP, entity reference
Create your taxonomy vocabulary:

 * Parent term
     * Child term1
     * Child term2

Create a content type
Once created add a Entity Reference field of type Term Reference referencing your taxonomy vocabulary's children terms you have created. Create a handful of nodes.
Create a View Block displaying content (related Nodes)
After creating the View Block of content (the content type with the reference, show fields, HTML list), include the fields you want to show for the related node and give that view a contextual filter of the Entity reference field you used for the content type. Simply set the settings of the contextual filter under When the filter value is NOT available to Hide View. You can optionally set the no results behavior as well.
Create a view displaying taxonomy terms (Master view)
Create a view of taxonomy (HTML List, Show fields), add a relationship of Taxonomy term: Parent term and require this relationship. Add field Taxonomy term: Term ID and hide from display. Add field taxonomy term: Name and under the field setttings, set the relationship to Parent, then hide from display. Add field Taxonomy term: Name to display the name of the term. Finally add a Global: PHP field and under the Output code provide the following snippet:
<?php
   $viewNodeDetail = views_get_view('YOUR_VIEW_BLOCK_MACHINE_NAME');
   $viewNodeDetail->set_arguments(array($row->tid));
   print $viewNodeDetail->preview('BLOCK_MACHINE_NAME');
?>

Under the view format settings set the Grouping field Nr.1 to the (Parent) Taxonomy term: Name.
This will treat the view block as a field (the view block is the child term + node and the master view sorts by the parent term). This will give you an end result of:

Parent term

Child term

Related node
Related node
Related node

Parent term

Child term

Related node


I think you have to use your field name instead of field type in the name of your .tpl.php file. Assuming the label of your field is 'Voucher code', then the machine name of this field would normally be field_voucher_code and your template file should be named field--field-voucher-code--add-deal.tpl.php See theme_field documentation for more details.

Don't forget to clear the caches (i.e., rebuild the theme registry) after creating this file in your (custom) theme.


Drupal alter some javascript of contrib module?

I believe this has already been answered here: How to override jQuery from contrib module

To override the JavaScript file added to a page from a module, you need to implement hook_js_alter()....


Extract hex colors from image field for taxonomy vocabulary

If your happy to use a custom module then something a simple as this would do the trick:

$colours = db_query("SELECT field_my_colour_field_value FROM field_data_field_my_colour_field")->fetchCol();


Per the commerce.api.php file, there is a document hook which allows you to add currencies.

function hook_commerce_currency_info() {
  return array (
    'CHF' => array(
      'code' => 'CHF',
      'numeric_code' => '756',
      'symbol' => 'Fr.',
      'name' => t('Swiss Franc'),
      'symbol_placement' => 'before',
      'code_placement' => 'before',
      'minor_unit' => t('Rappen'),
      'major_unit' => t('Franc'),
      'rounding_step' => '0.05',
    ),
  );
}

http://cgit.drupalcode.org/commerce/tree/commerce.api.php


How to order nodes with a number like 1.1.1

You can do this with hook_views_query_alter(). I had a similar requirement few time ago where i have to sort nodes where title those have numbers should display before the nodes those have alphabets.
Here is a snippet i created at dropbucket.rog

http://dropbucket.org/node/1484

Steps:

Add one new text field to the content type you using for files. use textfield because integer or float type field will not allow you value in format 1.1.1.
Create a view.
Add a sort criteria the field you added either desc or asc. because you are going to alter this in hook_views_query_alter().

I tried with textfield name "sort". Change the field name whatever you use in content type, in query alter. You can get field name in view query display if query display is enabled in views settings.

Create a custom module.

function custom_views_query_alter(&$view, &$query) {
  if($view->name == 'your_view_name'){
      // Remove all the sort order fields.
      $query->orderby = array();
      // Show number before the alphabets in titles.
      // This is trick which add 0 to the field to cast it to number then check the not equal to condition.
      $query->orderby['0']['field'] = 'field_data_field_sort_field_sort_value+0<>0';
      $query->orderby['0']['direction'] = 'DESC';
      $query->orderby['1']['field'] = 'field_data_field_sort_field_sort_value';
      $query->orderby['1']['direction'] = 'ASC';
  }
}


How to allow a client to do specialized styling for a single node?

If it is a page with unique structure and no other pages will have same structure, I usually do this by creating an empty page (not a node, just a page - an item in drupal menu system).

You can create a page in your module like so:

function YOUR_MODULE_menu() {
    $items = array();
    $items['your-page-url'] = array(
        'type' => MENU_NORMAL_ITEM,
        'title' => t('Page title'),
        'page callback' => 'your_callback_function_name',
        'access callback' => TRUE
    );
    return $items;
}

function your_callback_function_name() {
    return '';
}

the code above will provide an empty page. If you need custom page structure for this page you can always declare a template specifically for this page just put:

page--your-page-url.tpl.php

to your theme template folder.

Then you can create blocks for each piece of content and assign them to proper regions. Your users will be able to edit content through blocks edit while all styling and layout tags will be built into template file.


Notice: Trying to get property of non-object

$form_state['view'] is not defined for all the forms, and it is not a value set by Drupal core modules. Before to access $form_state['view']->name you should verify $form_state['view'] is defined, and it is an object (and not an array, for example).


This has been addressed here: https://www.drupal.org/node/2295541

Short answer: You can't create your own space content types because it breaks the architecture set up by organic groups. Better to use the stock space content type and add a term reference field where the terms delineate different space "types", or make use of the standard "space type" term reference field.


HTTP/2 does not allows to write in folders in Drupal 7, how can I fix?

Solution found, just needed to install suPHP module and configure it so apache could execute php with owner permissions instead of default user


To answer the question of "where" do you add the AJAX functionality in a node form, the answer is in a form_alter. That can be done in a custom module or the theme's template.php file. I recommend a module so the functionality remains even if you change your theme.

A great resource is the examples module which is a group of example modules with great comments that assist developers in implementing Drupal functionality. In fact, there's is a submodule called ajax_example that adds ajax functionality to a a field in a node (exactly what you are looking for!). Here's an excerpt from ajax_examples_node_form_alter.inc:

/**
 * Implements hook_form_FORM_ID_alter() for the node form.
 *
 * Adds two fields to the node form, second only appears after first is enabled.
 */
function ajax_example_form_node_form_alter(&$form, &$form_state, $form_id) {
  $node = $form['#node'];
  $form['ajax_example_1'] = array(
    '#type' => 'checkbox',
    '#title' => t('AJAX Example 1'),
    '#description' => t('Enable to show second field.'),
    '#default_value' => $node->ajax_example['example_1'],
    '#ajax' => array(
      'callback' => 'ajax_example_form_node_callback',
      'wrapper' => 'ajax-example-form-node',
      'effect' => 'fade',
    )
  );
  $form['container'] = array(
    '#prefix' => '
',
    '#suffix' => '
',
  );

  // If the state values exist and 'ajax_example_1' state value is 1 or
  // if the state values don't exist and 'example1' variable is 1 then
  // display the ajax_example_2 field.
  if (!empty($form_state['values']['ajax_example_1']) && $form_state['values']['ajax_example_1'] == 1
      || empty($form_state['values']) && $node->ajax_example['example_1']) {

    $form['container']['ajax_example_2'] = array(
      '#type' => 'textfield',
      '#title' => t('AJAX Example 2'),
      '#description' => t('AJAX Example 2'),
      '#default_value' => empty($form_state['values']['ajax_example_2']) ?
                          $node->ajax_example['example_2'] :
                          $form_state['values']['ajax_example_2'],
    );
  }
}

/**
 * Returns changed part of the form.
 *
 * @return renderable array
 *
 * @see ajax_example_form_node_form_alter()
 */
function ajax_example_form_node_callback($form, $form_state) {
  return $form['container'];
}


Disable the Global Redirect module.  This module is specifically built to do the behavior you are describing, because search engines like it.

Unless you are using those path segments as contextual filters somewhere, there should be no reason to do this.  If you are using those path segments as contextual filters, there should be a better way to do this.  Either a view page or a panel page would be able to hold that page open, use wildcards for those address segments, and get the functionality that you want without having to upset the search engine bots.


Is there a way to export all roles and permissions from testing environment to be imported/deployed on production environment?

Check out these modules Export Roles & Permissions or Features Roles & Permission


How would I hide a form and display thank you content in the same area - drupal 6

Or use $form_state['rebuild'] in the submit handler and check for submitted values in the form builder. That way you can display the form the first time the user hit's the page, and after submission you display your message. This is something like a multistep form, so you could take any of the numerous tutorials for multistep forms in drupal.
Also have look at the official example in form_example_tutorial.inc


Patch Status for 'cweagans/composer-patches'?

I found no available solution, so I've created a new Drush Command for this: https://github.com/SeoGow/patch_overview/tree/master.

I hope this helps somebody.


Using variable_set with associative array

The problem is not variable_get()/set(). It stores whatever you pass to it as a serialized array.

However, what you are saving are the keys of your array, because that's what is passed from the browser when submitting the form. This is also what is expected in the #default_value so it needs to be like this.

When accessing the information, all you need to do is get the intersection of your $details and the selected keys like this:

$selected_details = array_intersect_key($details, array_flip(variable_get('livembo_classes_details', array('c_id','c_cd_name')));

I would recommend to add a helper function which returns $details if you haven't already, so you can re-use that definition and a second helper function which contains the above code.


How do I print an individual field in block.html.twig?

If you have a field called field_test you schould be able to do like this

{{ content.field_test }}

and if you want to only print the value you can do like:

{{ content.field_test[0] }}

If you want to see what is inside the field you can do like this:

{{ kint(content.field_test) }}

But only if you have Devel module installed and have Devel Kint enabled you should be able to do that.

Hope this helps :)


In Drupal 8 jQuery is added in the non intrusive way, this means that $ is not defined in the global space.

What you should do is to use closures (this is a very good idea, as it makes it easy for you to fix potential issues with colliding variables names. $ is used by other frameworks as well.

This is done by wrapping your code in a anonymous function so you don't need to get variables from the window object but can get them from the function definition. This means that you can easily change the source one place and it will effect all of the script you have written.

(function ($, Drupal) {

  // It's best practice to use strict mode, can help avoid some browser issues.
  'use strict';

  // Generally you always want to use behaviors, remember to depend on Drupal js.
  Drupal.behaviors.name = {
    // Called on document ready and when no elements is added to the page.
    attach: function (context, settings) {
      $(".selector", context)...
    }
  }

  // Sometimes you just want to do something when DOM is ready.
  $(document).ready(function() {
    // Stuff to do as soon as the DOM is ready;
  });

})(window.jQuery, window.Drupal);


render or print image in a drupal 7 node.tpl?

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

If you want to change how the image is displayed (dimensions, link, etc), set them in Manage Display tab in the node type settings.

You can also do an imagecache preset like this:

<?php
print theme('image_style', array('path' => $node->field_image[LANGUAGE_NONE][0]['uri'], 'style_name' => [STYLE NAME]));
?>

But that's not the recommended way!

if you want to build URL from URI,

<img src="<?php print file_create_url($node->field_image[LANGUAGE_NONE][0]['uri']); ?>" />


Ok, if somebody are interested in it I've found this post that solve my question:

Auto-Fill from on content type to another


Real-time preview of node/form in Drupal 7

I have started development of a module - Live preview which might be more along the lines of what you're after.

This module provides a more comprehensive, genuine and interactive version of the built-in node preview feature.
The live preview feature requires JavaScript; if JavaScript is disabled it will not apply its triggers, effectively retaining the built-in preview.

It hasn't yet reached a stable release, but it's worth checking out (-dev version should work just fine).


How can i change the confirm page text in simplenews

A grep on the simplenews module shows the text is coming from simplenews.subscription.inc file from following code.

on around line #582

/**
 * Generate the confirm subscription form.
 *
 * @see simplenews_confirm_add_form_submit()
 */
function simplenews_confirm_add_form($form, &$form_state, $mail, $newsletter) {
  $form = array();
  $form['question'] = array(
    '#markup' => '<p>' . t('Are you sure you want to add %user to the %newsletter mailing list?', array('%user' => simplenews_mask_mail($mail), '%newsletter' => _simplenews_newsletter_name($newsletter))) . "<p>\n",
  );
  $form['mail'] = array(
    '#type' => 'value',
    '#value' => $mail,
  );
  $form['newsletter'] = array(
    '#type' => 'value',
    '#value' => $newsletter,
  );

  return confirm_form($form, t('Confirm subscription'), '', t('You can always unsubscribe later.'), t('Subscribe'), t('Cancel')
  );
}

since it is a form, you can simply implement hook_form_alter() to override 'question' field markup from your custom module, something of following sort

function my_module_name_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == 'simplenews_confirm_add_form') {
      $form['question'] = array(
       '#markup' => t('Your Custom Confirmation Message Here'),
      );
  }
}


How to create multiple user account types in drupal 7

Anonymous user, and authenticated user are two default roles used by Drupal (what other CMS's would call account types).

You can add custom roles from admin/people/permissions/roles.

Once you created the new role, you can change the permissions given to that role using the "edit permissions" link that appears to the right side.

If you then need to add new fields for user accounts having a specific role, you can use the Field Permissions module.
Drupal allows you to add new fields to the user accounts, from admin/config/people/accounts/fields, but the fields are visible for every user account, independently from the roles those accounts have.

The Field Permissions module allows you to set who can enter a value for a field, who can edit a value for a field, and who can view the value of that field.
For example, if you want a "Editor ID" field that needs to be filled only from users with the editor role, you can add the permission of creating a value for that field, and editing it to users with the editor role; other users should be allowed to see that field, as well as the users with the editor role.


In the view, there is an 'allow settings' link (bottom right of your screen shot). This allows you to select which settings can be changed within panels, including the title.

You can then, in panels, override the title with an empty string.


mail() is a PHP function, that will never use SMTP.

You need to use the drupal mail manager and its mail function. See https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Mail%21MailManager.php/function/MailManager%3A%3Amail/8.4.x and the example code ther.


Yes, it is.

$tid = 1; // Term id
$term = taxonomy_term_load($tid); // Load term
// Output term data with debug()
// See watchdog log at /admin/reports/dblog
debug($term, 'Taxonomy Term');

For example, file fid will be

$fid = $term->field_image[LANGUAGE_NONE][0]['fid'];

You could also get the rendered image, or url with something like:

// Get rendered HTML image tag using image styles.
$image = theme('image_style', 'medium', $term->field_image[LANGUAGE_NONE][0]['uri']);

// Get path to image style image
$path = image_style_url('medium', $term->field_image[LANGUAGE_NONE][0]['uri']);


Hide webform components after submission

I managed to do so with a hook_form_FORM_ID_alter:

function mymodule_form_myformid_alter(&$form, &$form_state, $form_id) {
    if(!empty($form_state['input'])) {
      $items = array('name', 'firstname', 'zip', 'phone', 'email');

      foreach ($items as $value) {
        $form['submitted'][$value]['#type']     = 'hidden';
        $form['submitted'][$value]['#title']    = '';
        $form['submitted'][$value]['#required'] = 0;
      }
      $form['actions']['#type'] = 'hidden';
    }
  }

It's not the most clean way to do so, but it does the trick :)


import csv to build several nodes all at once

Yes there is, you can using:
Feeds

Import or aggregate data as nodes, users, taxonomy terms or simple
database records.

One-off imports and periodic aggregation of content
Import or aggregate RSS/Atom feeds
Import or aggregate CSV files
Import or aggregate OPML files
PubSubHubbub support
Create nodes, users, taxonomy terms or simple database records from import
Extensible to import any other kind of content
Granular mapping of input elements to Drupal content elements
Exportable configurations
Batched import for large files

Video Tutorial


Most simple way to integrate a html/jquery block into the system?

Surely you could just build the HTML form as you normally would, and set the Filter Format to Full HTML (if you're using the WYSIWYG).  Seems an odd way of doing things though to be honest!

You could also take a look at the Webform module.  That'll allow you to store form submissions easily as well!  Or Form Builder, but I've never used it before and it doesn't appear to have a 1.0 release.

On another note, the form API in Drupal is not only REALLY powerful, but actually easier than it looks!  It's definitely worth taking time to learn, as you'll find yourself coming back to it again and again!


Based on your question, I would recommend you use the devel module to auto-generate random users.

OR if you really want to auto-submit the user form (or any form) then attach JavaScript to the page that does so via #attached in a hook_form_alter or via drupal_add_js() or simply in your theme via a .js file included in your .info file.

The javascript would be as Eugene Fidelin has posted above – $('#user-register-form').submit();or potentially by extending the Drupal.behaviors object, which is recommended for a number of reasons I won't get into here:

(function ($) {

  Drupal.behaviors.myModule = {
    attach: function (context) {
      $('#user-register-form').submit();
    }
  };

})(jQuery);


Allow creation of new content type just like taxonomy

Do you mean the Node Reference Create module?


Suggest a page template for a specific view

In case of Views 2, One of the option would be to name your template file "views-view--news.tpl.php".

There are  other useful options like "views-view--news--page.tpl.php" or  "views-view--news--block.tpl.php" depending on your display type.

You may find This tutorial useful .


Add value to field using Entity Metadata Wrapper

One issue may be that get_object_vars() returns an array with keys that the file field does not understand.  The EntityMetadataWrapper documentation provides two options for setting file reference values, though it appears to use single value fields in the examples:

Setting the file directly:

$w_containing_node->field_attachment_content->file->set( $file_obj );

Providing an array with just fid:

$w_containing_node->field_attachment_content->set( array('fid' => $fid) )

One of the comments provides the following examples from the entity tests which apply to a multi-value field, though I'm not sure if setting the full file object will work appending a new item:

$wrapper->field_file[0] = array('fid' => $file->fid, 'display' => TRUE);
$wrapper->field_file[1]->file = $file;


How can I check the user status of node author in Rules condition?

You need to use the double equation sign. What your code does right now, is that it assigns the value 0 to $author->status.

Here's updated code:

return $author->status == 0;


What's the easiest way to add a contact form for all nodes of a certain content type?

I ended using Webforms, passing the node author's e-mail using the token [current-page:node:author:mail] for passing the e-mail via a hidden field. I enabled the option to use the webform as a block and Context module for showing that block only in the desired content type.

With the lastest stable versions of Webforms and Token, I had to patch Token module as it's explained in this forum because the token wasn't working with Webforms.

http://doublemthemes.com/comment/3307#comment-3307


Yes those are most likely bots; you can never be 100% sure but if you're seeing a pattern, and these users aren't contributing to the site in the same way regular users do, it's likely.

I think anyone who's ever administered a medium-large Drupal site has experienced this at one time or another. Standard tools for the arsenal include:

Botcha

  BOTCHA is a highly configurable non-CAPTCHA spam protection framework.

Spambot

  Spambot protects the user registration form from spammers and spambots by verifying registration attempts against the Stop Forum Spam (www.stopforumspam.com) online database. It also adds some useful features to help deal with spam accounts.

Both are very effective in my experience, though Spambot can get fairly intense on outgoing http requests if you get a lot of registration attempts. There are some others listed on the Spam control modules page too.


Drupal 7 - Programmatically create field collection within field collection

I just figured this out, please see field collection module issue:

http://drupal.org/node/1393552#comment-5428548


Inserting PDF files via the Image icon in ckeditor. Is there a better way?

The canonical "Drupal way" is to keep files in file fields. You are free not to display them in your theme for readers and only keep links in body. Having them explicitly linked to a node has some advantages: you can keep track if files are used or should be deleted, you can display them in views, in search you can possibly add "with attachment" option and so on.

You can write a CKEditor plugin - copy image uploading one, change output from <img src=" to <a href=" and you have what you wanted. It's what you want, but be careful, you might regret it in the future if you'll ever need that node-file relation.


Others have advised you not to do this. I too remain in that idea, but to answer your question:

Can Drupal even run without index.php? Can it be a different file name?

Technically it's possible for Drupal to run on any different directory index file name. But you need to configure your web server for that first. Unfortunately you will need to hack core as well, which is considered without-doubt a bad idea.

.htaccess changes

Assuming you are using Apache, and because it can automatically detect http://example.com?q=node and http://example.com/drupal.php?q=node if the DirectoryIndex drupal.php, you will only need to change the .htaccess file.

if your web server is not Apache and if you can't configure it to above URL patterns, you have to modify line 1518 in common.inc as well (Drupal 6.31).
Things will get much complex in Drupal 7.x. You will have to make several hacks which you will find difficult to maintain patches for.

In your .htaccess, change these (using "drupal.php" as the new file name).

ErrorDocument 404 /index.php to ErrorDocument 404 /drupal.php
DirectoryIndex index.php to DirectoryIndex drupal.php
RewriteRule ^(.*)$ index.php?q=$1 [L,QSA] to RewriteRule ^(.*)$ drupal.php?q=$1 [L,QSA]

You will probably need to modify your unit tests and shell scripts as well.


How should a custom module install a reference data dictionary?

In D7 I would make a Taxonomy out of such data. Just create a new taxonomy called Chemical Dictionary. Taxonomies already have:

a title
a description field

You just need to add a custom field for the image(s) using the Field UI. You could easily import these things from CSV or a remote database table using the Migrate module if your comfortable with code.

Taxonomy terms are stored in a database table by default in drupal, they are already entities.

While typically used for tagging things, you dont have to use it that way.


Where does drupal determine which theme file to use for an entity field?

Everything can be overridden by one hook in any module so bear that in mind.

The theme registry is where everything is stored in terms of theming for pages/entities. It all depends on the order here in determining the theme it will use.

You can use the devel module and dpm out the theme registry:

https://api.drupal.org/api/drupal/includes%21theme.inc/function/theme_get_registry/7

It usually is built in this order:

module where entity is created
module where function was called to get the entity
your theme directory

but at any point that could have been overridden


How can I modify the code in taxonomy feature to include terms

Features can't export (and import) terms without "extension".
You could use UUID Features:

  The UUID Features Integration module provides a mechanism for
  exporting content (nodes, taxonomy, fields) into a features module.


Git flow feature in branch on stage server

If you switch from the feature branch back to develop, it won't wipe them out because the changes are stored in the database, and you should see an overridden status on the feature. Once you switch back to develop, you can perform a feature-revert again to change the settings back.

Either way, I would backup the database, either using Backup & Migrate, or directly on the server, just in case anything goes wrong.


This error usually causes due to Jquery version incompatibility, try installing jquery_update module and navigate to

example.com/admin/config/development/jquery_update

and choose jQuery version for administrative pages as 1.5 or 1.7


Why my stylesheet won´t load into my node/add forms? (D6)

I´ve found the solution:

<?php
      if ((arg(0) == 'node') && (arg(1) == 'add') || (arg(2) == 'edit')){
    $node = node_load(array('nid' => arg(1)));
    print $title;
    }
?>

Thanks to nevets, who gave me the hint that I needed! :)


How do I print custom html in nodes of a certain type using template.php?

If you want to provide a new variable to your node template file you should implement hook_preprocess_node() in your theme and pass it from there:

function MYTHEME_preprocess_node(&$vars) {
  if ($vars['node']->type == 'node_type') {
    $vars['extra_html'] = my_function_to_build_html_string();
  }
}

Then in your node.tpl.php file you can output that HTML wherever you want like so:

<?php if (isset($extra_html)): print $extra_html; endif; ?>

If you just want to add some HTML into the normal content of the node, you would do it like this:

function MYTHEME_preprocess_node(&$vars) {
  if ($vars['node']->type == 'node_type') {
    $vars['content']['extra_html'] = array(
      '#markup' => my_function_to_build_html_string(),
      '#weight' => -10 // Control the display order of this element
    );
  }
}

In either case you'll need to clear Drupal's caches once you've implemented this hook so the theme registry picks it up.


How to duplicate a display (which is not the master) as a different display type?

Drupal 7 solution
There is no out-of-the-Views-box solution for this in Drupal 7 ... Except if you get really creative (or via "ugly ways" as @MPD wrote in a comment below the question) with exporting / editing / reimporting such view. But that's not out-of-the-Views-box of course, and  to my knowledge not included somewhere within the Views UI. Comment #1 in the issue about "Clone a Page view into a block view" seems to confirm this.
Drupal 8 solution
In Drupal 8, for an existing display of a view, assuming it's a page display, you can say "duplicate this display as another display type". This will copy all of that view definition to the new display.
As an example, in a standard (core only) Drupal 8 site,  you can now duplicate a page display as:

another page.
a block.
an attachment.
an embed (1).
an entity reference (2).
a feed.

This appears to be one of the most exciting new features of Views in Drupal 8 ... Apart from Views in Drupal Core (= VDC) ... of course.
Notes:

(1): In the Views settings, if you select “Allow embedded displays”, then they can be used in code via views_embed_view().
(2): In the Entity Reference field settings, select “Filter by an entity reference view” and use a view with this display type to define what can be referenced.

Credits: "Babou", who made me discover it while listening to "Talking Drupal (episode 111)".


To answer the original question (how do I get a module path), and not taking into account the javascript attachment part here is OO friendly solution (without showing the dependency injection itself):

$module_handler = \Drupal::service('module_handler');
$module_path = $module_handler->getModule('my_module')->getPath();

This will give you back the following (of course also depends on how your directory structure looks like)

"modules/custom/my_module"

drupal_get_path is indeed faster to write. However, it calls the same service above statically which makes your code unable to unit test (also not to mention the dependencies of your class are not visible).
Long story short: if you choose to make things Quick&Dirty go for drupal_get_path any other cases use the right service yourself with a proper dependency injection.


Remove 'alias' => 'b', from your getIds() call, that parameter is only needed if you need to remove any ambiguity from the source query.


it was so stupidly simple... Just don't add any term and add a filter to the view

having Brand one of .... OR having Brand empty(NULL)

I should definitely stop looking for a complex solutions for a simple questions. Thanks anyway


drupal multilingual frontpages different templates

Create a custom template file for the English landing page first (for example: page-customfront.tpl.php) then add the following code into your theme template.php file:

function mytheme_preprocess_page(&$variables) {
  global $language;
  if (drupal_is_front_page() && $language->language == 'en') {
    $variables['template_file'] = 'page-customfront';
  }
}

This should do the trick (assuming English will remain the default language with no prefix). Don't forget to switch out mytheme in the function name with your actual theme name.

As for the language links you could use the following code:

<?php
$langs = language_list();
foreach ($langs as $lang) {
  if ($lang->enabled) {
    if ($lang->language == 'en') continue;
    print l($lang->native, '<front>', array('language' => $lang));
  }
}
?>

This should go into page-customfront.tpl.php in the place where you want the links to appear. If you are familiar with creating custom modules or don't mind learning it would probably be preferable to turn this code into a function, add it your module file, enable the module and then just call the function from page-customfront.tpl.php.


It depends on the module.

You can create a module which has a simple info file and a blank module file, compare that to views which has loads of file and implement lots of hooks and create it's own as well. Obviously this requires more memory than a blank module.

Performance depends on a lot of factors. A module can use a lot of memory but not slow the side down much while the reversed can be true as well. Usually the bottleneck is r/w to the database. A single bad query can take seconds to perform, most tasks in code is not that slow. Iterating over a lot of objects and munching data can, however, take a lot of time.

So it's hard to say how a module will effect performance, but it's always a good idea to limit the amount of modules used when possible. I haven't heard of a thumb rule though and to be able to make one, you would need to know the hosting environment.


Upgrading Drupal 8 to a newer version from the command line using Drush?

To do it via the command line you can simply run the command drush up drupal

To do it manually, it's a bit more tedious as you need to be really careful about what you want to keep, templates.. modules... themes. Basically you need to replace all core files at the root level and note that the files that reside at the root level e.g. .htaccess.. robots.txt need to be compared and merged with the latest.

I hope this helps.


twig to print paragraph field in controller

You have to get the paragraph entity with .entity

{{ teacher.field_classrooms.entity.field_in_paragraph.value }}

where you can get the fields inside of the paragraph.


How to use Drupal.displace inside Drupal.behaviors

Your thought to use drupalViewportOffsetChange is the way to go. The actual event is drupalViewportOffsetChange.toolbar. Here is an example:

  Drupal.behaviors.myTheme = {
    attach: function attach(context) {
      if (context === document) {
        $(context).on("drupalViewportOffsetChange.toolbar", function (event, offsets) {
          var selectors = [".class-of-thing-i-want-to-offset"];
          selectors.forEach(function (selector) {
            if ($(selector).length > 0 && offsets.top > 0) {
              $(selector).css("top", offsets.top);
            }
          });
        });
      }
    }
  };


Second index after 'und' is used for delta of values. You can make it 1 , 2, 3 etc to add multiple values... Something like below...

$node->field_my_custom_field['und'][0]['value'] = 'my value one';
$node->field_my_custom_field['und'][1]['value'] = 'my value two';
$node->field_my_custom_field['und'][2]['value'] = 'my value three';
$node->field_my_custom_field['und'][3]['value'] = 'my value four';


How to display taxonomy term image in a view

For that you can add a relationship in advanced.
Search for your term reference field in it and add the relation.

Then go to fields and search for your image field which is inside of the taxonomy. That way you will be able to add the image.


Display entity reference field in a views block

Just coming from memory I would recommend something like this:

Create a view of what you want to show. (In your case, a view of content-type="contributors")
Create a relationship in that view to the content that contains the reference field. (Just click on add a relationship, and search for the name of your reference field)
Create a contextual filter to filter by ID. This filter will also be the reference field name. (choose "Provide default value" then "Content ID from URL") This contextual filter will use your relationship.
Restrict that Views block to only show on that content type (in block settings of course).

What you're doing is adding a relationship to that reference field. Then it is available as a contextual filter, where you can then provide a default value to filter by content ID.

Note: keep in mind if ever your reference field is not available as a relationship in your view, you may need to first add a content or node based relationship.


Redirect to the front page with a different language

You can try this code

 <?php

 use Drupal\Core\Url;
 use Symfony\Component\HttpFoundation\RedirectResponse;

 $language = Drupal::languageManager()->getLanguage('vi');
 $url = Url::fromRoute('<front>', [], ['language' => $language]);
 $response = new RedirectResponse($url->toString());
 $response->send();


Default user image in user account menu!

You can check if a user picture exists this way:

if (!$user->user_picture->isEmpty()) {
  $picture = file_create_url($file->getFileUri());
  $picture = $user->user_picture->view('large');
} else {
  $picture_field = \Drupal\field\Entity\FieldConfig::loadByName('user', 'user', 'user_picture');
  $default_image = $picture_field->getSetting('default_image');
  $file = \Drupal::entityManager()->loadEntityByUuid('file', $default_image['uuid']);
  $picture = $file->getFileUri();
}