For doing this, i won't use a hook but the drupal eventSubscriber :

First your need to make a custom module with the file for declare to drupal your new service :

  myModule.services.yml

services:
  myModule.services:
    class: Drupal\myModule\EventSubscriber\MyServiceSubscriber
    arguments: []
    tags:
      - { name: event_subscriber }

Then in the file :

  myModule/src/EventSubscriber/MyServiceSubscriber.php

<?php

namespace Drupal\myModule\EventSubscriber;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;

    /**
     * Class myServiceSubscriber.
     *
     * @package Drupal\myModule
     */
    class MyServiceSubscriber implements EventSubscriberInterface {

        public function onRequest(GetResponseEvent $event) {
           // here your code, this method ll be call on every call request
           // so you can code your logic here
        }

      /**
       * {@inheritdoc}
       */
      static function getSubscribedEvents() {

          $events[KernelEvents::REQUEST][] = ['onRequest', 900];

          return $events;
      }

    }


How can i export single content node (or) selected content nodes using drush command

Drush command node-export-export accepts arguments ... You can see documentation of any drush command using below syntax..

drush help command-name

In your case

drush help node-export-export

Arguments:
 nids                                      A list of space-separated node IDs
                                           to export.

For Example

drush node-export-export 45 46 47

export nodes with node IDs 45, 46, 47


Have a look if the class error has been added to your <input>. It has on my side, it's the CSS that does not highlight the elements properly.

You can either adjust your stylesheet for .form-item input.error or you can use a piece of jQuery to make the parent of the radios styleable, such as

$('.form-radios:not(.error):has(.form-item input.error)').addClass('error');

Another option would be to add the appropriate class via the Drupal's theming system (theme_optionwidgets_buttons()).


How to make content private and only for certain roles to see

There are a couple options (and more, I'm sure):

http://drupal.org/project/nodeaccess (easier to set up, but more manually intensive for the end user)

or

http://drupal.org/project/taxonomy_access (a little bit more to set up, but easier on ur end users)


Change default date format in input mask: Is it possible?

Assuming the machine name of your content type is "test".
Please navigate to:
admin/structure/types/manage/test/form-display
You should see the following form (with different fields, of course).
In my example, the name of the field is simply "date" .
You can change the widget to Select list and then you will see the cog wheel on the right side of the row.
After clicking on it, you shall be able to choose your preferred Date Format.

Hopefully that helps.
Update 1: Regarding Update
In my default Drupal installation when I try to add date-based fields, I do have the following 2 options:

Date
Timestamp

Option Date
I have suboptions, "Date only" or "Date and time"

If I choose "Date and time" -> I am able to see the select widget as
option.
If I choose "Date only" -> I am able to see the select widget
as option.

Timestamp
I am able to see only Datetime timestamp

As a last thing:
Screenshot, showing the different type of fields in Manage form Display:

Update 2:
It seems the following article has it explained how to do the exact thing you are looking for:
https://www.previousnext.com.au/blog/making-drupal-8-datetime-widgets-use-human-formats


Not sure but this might help: https://drupal.org/node/1980360 - Importing KML file data into GeoField field instance


Change Taxonomy Page to display first node in full

The way to do this is to enable the "Taxonomy term" view in Views:

Add and offset of 1 to the page view:

And then add and Attachment display that has a pager with an Offset of 0 and an Items per page as 1. On the attachment you can switch the Format to show full nodes instead of teasers.

This will work "automatically" for all Taxonomy terms. The reason this works is that the view takes an argument of the taxonomy term in the URL.

It overrides Drupal core's url for Taxonomy terms and uses the view as a replacement.


As Kevin already mentioned: it can be done using 'composer-patches' in a similar way to patching a Drupal module.

The mentioned patch contained more than I wanted to patch, so I downloaded the patch and added it to a local 'patches' directory. Also, the patch uses a path that starts at 'libraries', while the patch configuration starts one level deeper.

So the patch configuration becomes:

....
patches {
    "mehrpadin/superfish": {
        "Fixed nested UL accordion functionality": "./patches/smallscreen_patch.diff"
    }
}
...

And the patch itself is changed from:

diff --git a/libraries/superfish/sfsmallscreen.js b/libraries/superfish/sfsmallscreen.js
index 9765fed..f5722a9 100644
--- a/libraries/superfish/sfsmallscreen.js
+++ b/libraries/superfish/sfsmallscreen.js

to

diff --git a/superfish/sfsmallscreen.js b/superfish/sfsmallscreen.js
index 9765fed..f5722a9 100644
--- a/superfish/sfsmallscreen.js
+++ b/superfish/sfsmallscreen.js


Switch site language after IP to locale redirect

You have tried Language Switcher module but you are not getting any result. Once try to use Language Switcher Dropdown module.

  Language Switcher Dropdown is a very simple module that exposes a new
  block, similar to the default Language Switcher block provided by
  Locale module. The new block allows site visitors to switch languages
  using a drop-down select list instead of using hyperlinks.


Just deactivate the predefined menu link and add a new one - use

<front>

as path.

In Drupal 7 and 8 go to

Home > Administration > Structure > Menus > Main menu > Add link

Your German version will say something like

Startseite > Verwaltung > Struktur > Menüs > Hauptmenü > Hinzufügen

Drupal 7

See tooltip for details (using Rubik Theme)

Drupal 8 (German version)


Views template- how can I still use "hide if empty" behavior with my custom template?

Quick and dirty, how about turning the label for this field off in Views and add something like:

<?php if (!empty($row->field_field_location_taxonomize_terms)): ?>

Label:

<?php endif; ?>

at the top of this template?  (Changing up the HTML around Label: to match your system and t()'ing it, etc)


CKEditor "Source" button does not brings back the full html

I know D8's CKEditor doesn't allow you to use the style attribute to prevent click jacking attacks, example.

Can't remember if D7 CKeditor did or not, but either way, it's bad security practice to allow people to use style attribute.

The better approach is to use a class.

...something goes here...

Your Drupal theme's style.css

.bg-red {
  background-color:red;
}


Drupal 7 Form AJAX button to return javascript script

The AJAX callback is only used to tell Drupal's AJAX engine what part of form to update. All actual work of building the form elements is supposed to happen in form's hook, in code wrapped in a control statement like the following.

if (!empty($form_state['values'])) {
  // ...
}


Is it a good idea to mix node api and entity api?

As long as you are sure everything you get will always be a node, there is no problem with mixing. Nodes are entities, after all, and node hooks and functions never got "obsolete" mark. It may be even beneficial, because you are making sure other node-related modules will continue to work with your module in a way you expect them to.

On the other hand, if you are getting something from that other module, and you can't guarantee it will always return a node, you should assume it might be any other entity, and either switch to entity approach totally, or filter what you got to make sure you only use node functions on nodes.


admin/content/comment/approval -> 410 Gone error (linked from content -> comments -> unapproved comments)

You could try installing the module

admin_views

As well as converting core administration pages (admin/content/node, admin/people etc.. ) to use VBO, it will add a view to admin/content/comment/approval

Recommended.


Facet API - Rewrite facet items via callback function

Make sure this filter is selected for your facet(s): "Rewrite facet items via callback function"
admin/config/search/apachesolr/settings > Facets > YOUR FACET > configure filters > [x] Rewrite facet items via callback function
You can verify your hook is implemented using drush and devel module:

drush hook facet_items_alter
Enter the number of the hook implementation you wish to view.
[0]  :  Cancel
[1]  :  my_module_name

If you see something similar to above, then your hook is implemented. To see the implementation code, enter a number (1 in this example).


Search API Database Search score calculation

When you use debugQuery=true in a query, you can see all debug informations and how solr calculate scores for the result documents.


Show 2 content types in a view that share same field value

Since field_id and field_org_id are two separate fields, you'll need some way to tie them together. A custom entity could do that, but you could also cheat a little and use a taxonomy vocabulary that contains these two fields.

You could then build a view that displays all content and add a relation to the vocabulary and restrict the results to only the content that possesses this relationship.

Cheaty, but I think it might be the easiest solution.

Edit:

I wouldn't modify the content or content types, but rather, add the field_id and field_org_id fields to the taxonomy vocabulary, then iterate through your Agent and Organization nodes and generate taxonomy terms that associate one field's value to another by populating each term's field_id and field_org_id fields from their respective Agent and Organization nodes.

So, some code...

Create the vocabulary

$vocab = new stdClass();
$vocab->name = 'Organization to Agents';
$vocab->machine_name = 'org_to_agents';
taxonomy_vocabulary_save($vocab);

Add the fields

$fields = array(
    'field_id',
    'field_org_id',
);

foreach($fields as $field) {
  // Replace my)taxonomy_vocabulary with your chosen vocabulary name.
  if (is_null(field_info_instance('taxonomy_term', $field, 'my_taxonomy_vocabulary'))) {
    field_create_instance(array(
      'label' => $t($field),  // <-- This doesn't need to be pretty.
      'widget' => array(
        'type' => 'textfield',
      ),
      'field_name' => $field,
      'entity_type' => 'taxonomy_term',
      'bundle' => 'my_taxonomy_vocabulary',
    ));
  }
}

Get the list of IDs

// Credits to https://www.drupal.org/node/1079616#comment-10864932 for example.
$agents = db_query("SELECT nid FROM {node} WHERE type = :type", array(':type' => 'agent'))
  ->fetchCol();
$orgs = db_query("SELECT nid FROM {node} WHERE type = :type", array(':type' => 'organization'))
  ->fetchCol();

// Should result in a list of unique Node IDs that exist in
// at least one node for both content types.
$nids = array_intersect($agents, $orgs);

Create your taxonomy terms

$vocab = taxonomy_vocabulary_machine_name_load('my_taxonomy_vocabulary');
foreach($nids as $key => $nid) {
  $term = (object)array(
    'name' => $key, // Use any unique value that makes sense here.
    'vid' => $vocab->vid,
  );
  $term->field_id[LANGUAGE_NONE][0]['value'] = $nid;
  $term->field_org_id[LANGUAGE_NONE][0]['value'] = $nid;
  taxonomy_term_save($term);
}

Again, this is a bit "cheaty", and a custom entity would probably be considered more proper, but I think this should help.

Hope it helps!


If you want to get any node data (it loads all fields image or text), you can use node_load function

function node_load

Load a node object from the database

try from devel/php by loading any node by calling print_r( node_load(1) );

now you able to fetch your uploaded image data from node object.

or

if you want to fetch any node related data while creating node, use form alters & do custom submitting handler
please refer this link


You could probably handle it with the following code:

function mytheme_preprocess_node(&$variables) {
  if (isset($variables['node']->field_myfield[$variables['node']->language][0]['tid'])) {
    $tid = $variables['node']->field_myfield[$variables['node']->language][0]['tid'];
    $variables['theme_hook_suggestions'][] = 'node__term_'. $tid;
  }
}

Now if a term with the id 6 would be referenced from a node's 'field_myfield' Drupal would look for a template named 'node--term_6.tpl.php' and use that if available.


Drupal 7 Ckeditor cannot edit profiles (picture added)

Broken unclickable fieldsets are almost always a symptom of JS not being run to build the links & click events to trigger expansion.

If the JS console is reporting errors, try to disable JS caching/aggregation, if possible, and look for offending JS errors that would stop execution. That should give you a good idea where it's coming from.

Most likely, the 3 affected sites have a similar configuration that is injecting JS which breaks further JS execution. Look for similar modules across the 3 sites. Good places to look are any custom modules, JQuery update (is it overriding the default jQuery from Drupal core?), custom blocks with JS, or any modules designed to inject ad-hoc JS snippets (I've come across sites using JS snippets despite its alpha status).


Adding the current node title as the value of the comment form title?

You're right, you most likely have the $form_id wrong.  To check this you can use drupal_set_message($form_id); and refresh the page to see all form ids on the current page.

Once you have the form id correct, then you can use print_r($form);

For example, I got this working on the comment form on my node type "Announcement":

function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'comment_node_announcement_form') {
    $form['subject']['#default_value'] = $form['#node']->title;
    //print_r($form);
  }
  //drupal_set_message($form_id); // Use to get $form_id
}


Aggregating but not taking the first result

You can use the Views Field View module, like so:

Create a view "user profile" master (not page)

use contextual filter user UID
In the pager: Display a specified number of items : 1 item and set offset to 1

Create the main view

add global field view
use user uid as a contextual filter

The problem with this is that if user have only one profile then you may encounter a problem but maybe you can change it
for more detail on how to create view inside view check Drupal Views Inside Other Views.


Why would taxonomy_term_save be slow when called from hook_install_tasks?

In this case, the problem resulted from having the Pathauto module enabled during installation.  When a new taxonomy term is saved, Drupal calls pathauto_taxonomy_term_insert(), which calls pathauto_taxonomy_term_update_alias(), which in turn calls pathauto_create_alias().  This last function calls an internal function, _pathauto_path_is_callback(), to determine whether an alias can be created for a given path, and this in turn calls the core function menu_get_item(), which contains the following lines:

if (variable_get('menu_rebuild_needed', FALSE) || !variable_get('menu_masks', array())) {
  menu_rebuild();
}

menu_rebuild contains the following lines:

if (defined('MAINTENANCE_MODE')) {
  variable_set('menu_rebuild_needed', TRUE);
}
else {
  variable_del('menu_rebuild_needed');
}

The cumulative effect seems to be that the menu_rebuild_needed variable is continually reset to TRUE, meaning that a complete menu rebuild is triggered each time a new taxonomy term is saved, slowing things down immensely (from ~100 terms saved per second to ~1 per second).

This seems like a bug, though it's not clear which component, if any, is at fault.  For now, I am working around the problem by disabling pathauto, creating the terms, and then re-enabling pathauto:

module_disable(array('pathauto'));
…
module_enable(array('pathauto'));


translate custom fields in the registration form

You need the i18n_field module from http://drupal.org/project/i18n. This allows to translate field labels, descriptions and so on.


After moving Drupal 7 site, adding /user or /?q=user to base URL simply reloads maintenance page

Update your settings.php to this:

$conf['site_offline'] = 0;

From https://www.drupal.org/node/276457#comment-901392


Get multiple results from entity reference relationship in views

Verify Distinct Checkbox in View Query Settings. You should disable it.
Verify number of items to display is more than one.
Make sure no filters or contextual filters added that will effect the view results.

I just added a entity reference field to Article Content Type. And then added a relationship to the entity in view using Relationships. It does show multiple values.

I am not sure what other configurations are enabled in your view. See below query generated using views for above scenario.

SELECT node.title AS node_title, node.nid AS nid, users_field_data_field_user.name AS users_field_data_field_user_name, users_field_data_field_user.uid AS users_field_data_field_user_uid, node.created AS node_created, 'node' AS field_data_body_node_entity_type
FROM
{node} node
LEFT JOIN {field_data_field_user} field_data_field_user ON node.nid = field_data_field_user.entity_id AND (field_data_field_user.entity_type = 'node' AND field_data_field_user.deleted = '0')
LEFT JOIN {users} users_field_data_field_user ON field_data_field_user.field_user_target_id = users_field_data_field_user.uid
WHERE (( (node.status = '1') ))
ORDER BY node_created DESC
LIMIT 5 OFFSET 0


You can use the base_path() function which should always work.

To be honest though it just returns $GLOBALS['base_path'] so your global $base_path statement should work fine.


How to get the URL addresses of all the photos on form

I implemented it this way. Hopefully this will save someone's time. The code works well if you upload files, delete if it works after the removal of the second file in this list and removes only the first remote URL.

function testmodule_form_page_node_form_alter(&$form, &$form_state, $form_id) {
    $form['field_photo']['#element_validate'][] = 'my_function';
}

function my_function($element, &$form, &$form_state){

        $lang = $element['#language'];
        foreach (element_children($element[$lang]) as $key) {
                $fid = $element[$lang][$key]['#value']['fid'];
                $file = file_load($fid);
                $url = file_create_url($file->uri);
                dpm($url);
        }
}


The problem began after I uncommented and defined a wrong $cookie_domain, in settings.php. (I needed this set up for FCKeditor/CKFinder.) Once I have corrected this, I've managed to log in again.


Cannot Logon to Drupal ("The website encountered an error while retrieving...")

Check your setup.php, probably you should set the baseurl variable there, since your drupal root is not the default /var/www


Are you actually having a problem with user_access or just asking before you're trying it? I'm not really following what exactly is your problem.

Taxonomy Access Control should influence what user_access returns. Or you could just set permissions for "Use contextual links" and let Drupal take care of it with contextual links instead of writing a custom module.


Quicktabs and views to create tabbed views

Is this not just a matter of editing the view block to show four items rather than one? Under "Pager" in the view, select "Display a specified number of items" and then the quantity you prefer.


There is the Expose items per page option under Pager options, so this might help a bit. This allows users to change how many results they want to see per page.

Why do you want to show different pagers for the same set of results? Pagers can add to the performance strain.

There are some contributed modules that add to the Views pager, try searching for them and see if they come close to what you need. For example Pagerer or Views Extra Pagers.


Hide CCK fields for users without references with node

Have you checked the Field Permission module which allows site administrators to set field-level permissions to edit, view and create fields on any entity.


Would disabling these following functions in PHP.INI affect Drupal 7?

Yes, that may cause odd debug issues down the track.

Some of those are required by drush:

i.e:

escapeshellarg
escapeshellcmd

symlink is used in system.tar.inc

Modules such as devel and advanced_help use parse_ini_file

Other contrib may use others, e.g print_pdf uses proc_open


So In the end I had to use hook_form_alter, here's a quick trimmed down example of how I achieved my particular problem:

function hook_form_alter(&$form, FormStateInterface $form_state, $form_id) {

if ($form_state->getFormObject() instanceof YamlFormUiElementEditForm and hashandler) {

$form['newsection'] = [
  '#type' => 'fieldset',
  '#title' => t('New Section'),
];
$form['newsection']['newfield'] = [
  '#type' => 'textfield',
  '#title' => t('New field'),
];


Print taxonomy term name in node.tpl.php

$term = current($node->taxonomy);
echo '
' . $term->name . '
';


You can use Drupal console commands to delete the existings configs. New install will only be possible when the existing configs are deleted.
use Drupal config:delete active profile.type.main

If you dont have drupal console installed then deleting the configs from db is other work around for this issue.

Go to the config db table and delete the configs which are existing.

Thank you


Is there an easy way to adjust the block layout?

The page.tpl.php file within /themes/bartik/templates/ folder is the main layout for the theme.

So in your copied version of that you can edit that file. If you look for:
print render($page['sidebar_second']);

That is the rendered content of sidebar second region. There's also 1 for sidebar_first. So you can move these to a different location within this file if you want it to be displayed heigher/lower in the content


Can you please try adding this to your buildForm() method:

$form['#parents'] = array();

According to documentation: FormStateInterface::setValueForElement
You need to pass an array() and set the parents array for the form element.
Hope this helps.

UPDATE
After revisiting the documentation, can you try this code:

$form_state->setValueForElement($form_state->getValue('test'),"0");


After batch_set(). Use

$batch =& batch_get();

This contains the information you need.

But I'm not sure you will be able to resume.


Sounds like exposed filters are what you're looking for. Just check for the "Expose" control when you're edited any filter item in your view.


Form in custom module using Controller: The HTML tag form isn't present in Twig

This is not working, you can't use a form template in a controller. You have to assign the template to $form['#theme'] when building the form or in a form alter hook. Then it gets used by formBuilder()->getForm() automatically.
See for example seven_form_node_form_alter():
$form['#theme'] = ['node_edit_form'];

and the corresponding twig file for a two column layout:
core/themes/seven/templates/node-edit-form.html.twig
{#
/**
 * @file
 * Theme override for a node edit form.
 *
 * Two column template for the node add/edit form.
 *
 * This template will be used when a node edit form specifies 'node_edit_form'
 * as its #theme callback.  Otherwise, by default, node add/edit forms will be
 * themed by form.html.twig.
 *
 * Available variables:
 * - form: The node add/edit form.
 *
 * @see seven_form_node_form_alter()
 */
#}

    {{ form|without('advanced', 'footer', 'actions') }}

    {{ form.advanced }}

      {{ form.footer }}
      {{ form.actions }}

Form modes
A different approach would be to configure a form mode in UI containing only the field you want and then use it in your controller:
    $formObject = \Drupal::entityTypeManager()
        ->getFormObject('user', 'custom_form_mode')
        ->setEntity($user);

See How do I load a form with a specific form display (form mode)?


I think MYTHEME_preprocess_page() function doesn't need for it.

The node--[node-type].tpl.php is only enough for it.


Where to insert .js code using the webform module for google tracking a submit button?

you have 2 option:
1- using #attached to the $form element. use hook_form_alter

function YourMODULE_form_webform_client_form_1_alter(&$form, &$form_state) {
  $form['#attached']['js'] = array(
    drupal_get_path('module', 'YourMODULE') . '/js/your_script.js',
  );
}

2- add it in your custom module with drupal_add_js() function, Also it will be much better if you just load the js on only that page (web form page) so you will avoid loading it on every page.


I highly recommend looking into Feeds. It has a CSV importer where you can map the fields and headers to anything you want.


create views for a field submitted more than once in one row

1)Change your views format into grid set its maximum column

3)Allow Group By Authored into Grids

4)Add css

   float: left;
   width: 80%;


How can I prevent user pages being created for users with a specific role?

I suppose you could use the Rules module to create a redirect (possibly to 404) when someone tries to view the user page of a user with a specified role.


How to get custom field labels translated

Last days, I got the same issue to translate labels and descriptions of custom. here is what i did to solve it.

Enable i18n's i18_field "Field translation" submodule
Go to admin/config/regional/translate/i18n_string
Checked 'fields' (properly check all) and Click on "Refresh strings".
Go to admin/config/regional/translate/translate
Search desired string and translated it to other lang.


If you're writing code:

search_api_track_item_change('entity_type', array($entity_id));

That will mark an entity as 'dirty', and it'll be (re-)indexed on the next run.

If you're not writing code, install the rules module, add a rule with an event of "A flag type has been flagged...", and an action of type "Index an entity", with the relevant parameters.


How do I display the date but not the author?

It's enough to edit the node.html.twig template used from the theme. For example, the Bartik theme uses a node.html.twig template containing the following code. (I omitted the documentation comment at the beginning of the file.)

{%
  set classes = [
    'node',
    'node--type-' ~ node.bundle|clean_class,
    node.isPromoted() ? 'node--promoted',
    node.isSticky() ? 'node--sticky',
    not node.isPublished() ? 'node--unpublished',
    view_mode ? 'node--view-mode-' ~ view_mode|clean_class,
    'clearfix',
  ]
%}
{{ attach_library('bartik/classy.node') }}

    {{ title_prefix }}
      {% if label and not page %}

        {{ label }}

    {% endif %}
    {{ title_suffix }}
    {% if display_submitted %}

        {{ author_picture }}

          {% trans %}Submitted by {{ author_name }} on {{ date }}{% endtrans %}

        {{ metadata }}

    {% endif %}

    {{ content }}

The line printing the name of the user who created the node and when it was posted is the following one.

{% trans %}Submitted by {{ author_name }} on {{ date }}{% endtrans %}

It's enough to change it and remove the part printing the username. In the case of the Bartik theme, the node.html.twig content will become the following one.

{%
  set classes = [
    'node',
    'node--type-' ~ node.bundle|clean_class,
    node.isPromoted() ? 'node--promoted',
    node.isSticky() ? 'node--sticky',
    not node.isPublished() ? 'node--unpublished',
    view_mode ? 'node--view-mode-' ~ view_mode|clean_class,
    'clearfix',
  ]
%}
{{ attach_library('bartik/classy.node') }}

    {{ title_prefix }}
      {% if label and not page %}

        {{ label }}

    {% endif %}
    {{ title_suffix }}
    {% if display_submitted %}

        {{ author_picture }}

          {% trans %}Submitted on {{ date }}{% endtrans %}

        {{ metadata }}

    {% endif %}

    {{ content }}

For a different theme, it's enough searching the line of the node.html.twig template containing {{ author_name }} and remove it. Clearly, also the sentence containing {{ author_name }} needs to be changed to make it grammatical. (Submitted by on {{ date }} would not be grammatically correct.)

As general suggestion, never change a template file used from a Drupal core theme or a third-party theme. Rather, create a sub-theme using that theme as parent theme, and add the template files you need to change.


Load external libraries in a custom block

Libraries don't work like that. You need a yourmodule.libraries.yml and define it there.

There's detailed documentation on https://www.drupal.org/developing/api/8/assets#external. The following is an example of how a library is defined.

angular.angularjs:
  remote: https://github.com/angular/angular.js
  version: 1.4.4
  license:
    name: MIT
    url: https://github.com/angular/angular.js/blob/master/LICENSE
    gpl-compatible: true
  js:
    https://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular.min.js: { type: external, minified: true }

Then, the library that you specify is yourmodule/nameofthelibrary, see https://www.drupal.org/developing/api/8/assets#render-array or any of the other examples on that page.


Drupal 7 Views Chart Statistics Over Time

Within the Charts module, there is an interesting issue about this, i.e. Graph node input over time (support date formatting on a continuous axis). In Comment #3 of that issue is stated: 'The trouble here is that neither Views nor Date modules provide aggregation options for date-based fields.'. The patch(es) included in this issue are expected to soon be applied.


You need to assign a node to be 'front'. Otherwise the meta won't show.


Programmatically create a node with alias and menu item using Entity API

I would suggest that you use the node_save() and have a $node->path set to create the desired path alias, rather than using $entity->save() because if inspect (via dpm()) the output of an entity_load() of a node, you would see nothing there related to the node's path alias.

Of course you could use $entity->save() > then fetch the node/entity id > and then use [path_save()][1] too.


How to add page restrictions for blocks in drupal?

In Drupal 7 you can use PHP code in the block's "Visibility settings."

Steps

Go to admin/modules and enable the PHP filter module

Go to admin/structure/block and click on "Configure"

Enter the following PHP code (including <?php and ?>) in the Page settings.


You can set your content type to not use comment title by unchecking "Allow comment title" under the settings for your content type.

Then I would copy comment.tpl.php to your theme and customize the output there instead of just unsetting the title value in theme_preprocess_comment().


There is no such method as \Drupal::entityLoad(). Use the static method on the entity type. Assuming "File", you should use:

$file = \Drupal\file\Entity\File::load(reset($entity_ids));

Berdir pointed out in a comment that QueryInterface::execute() returns an array keyed by entity ID or revision ID so reset() is the thing to use to get the first element.


How can I change the way list appears when I click a tag?

There are a few ways to achieve that.

First and the easiest way is to go to the display settings of the content type and hide all fields in teaser view mode.

Second way is to use Views module, which ships with a taxonomy term view. You need to go to the views administration, structure/views, and enable this view. Or better, clone this view and enable the cloned one. This way you have more options then only to show the titles. However, it can be an overkill if you only need to show titles.


Putting any fields of referenced entity in lightbox frame

This doens't necessarily have to be done using lightbox. It ended up being a lot easier using a jQuery plugin like Simple Modal

I made extra fields in views and gave them a class the jQuery could latch on to using

$('hideMe').hide;

and using jQuery's click(); method to go and say (this).modal

A different question here at Drupal Answers went into the same issue but it was more about how to write the jQuery code so definitely more of a jQuery question. Anyway the question with the exact code can be found here.


Content for textgroup views is not allowed for translation because of its text format

I had the same problem, then found a solution. I'll show you the details with screenshots.

First enable Internationalization Views (i18nviews).
Create your custom view. For example, I'll simply list the nodes related to Article content type.
Add a header:

Click on "add" next to Header section

Add "Global: Text area"

Type your header text, and select your input format. Please note that I selected "Filtered HTML" here!

Click Apply

After saving the view, you'll see notice, telling that this header text can not be translated, so in my case:
"The string views:list_articles:default:header:views:area:content for textgroup views is not allowed for translation because of its text format."

Go to admin/config/regional/i18n/strings (Home » Administration » Configuration » Regional and language » Multilingual settings » Strings)
Check the appropriate text format you used above, when adding a header text, it must be the same - so in my case, it's "Filtered HTML" -, and then click Save configuration.

Now go back to your custom view, and on the right dropdown menu, click "translate view":

Now you'll see this:

Click on one of the "translate" links. After that, you'll see the following screen, and a message that the appropriate string for the header text translation has been created - which means from now on, you can translate it!

Scroll down to the appropriate header text, and translate it:

After translating, click on "Save translation".
On the following screen, you can see that some translations have been saved.
Now when switching to the other language, you'll see that the header text is translated! You are READY!


Multisite domain not working without symlink

I have the answer now.

The symlink is necessary so two separate domains can share the one IP along with your server's records. Obviously the subdomains share the same name and so are fine just listed in sites directory. The symlink links the other domain or any number of domains to the same html folder where the root installation of drupal resides.

The clean urls for the symlink multi-site domain on my Centos 6.4 linux system running httpd require the default httpd.conf file in etc/httpd/conf to change AllowOverride NONE to All for directories. Then the service must be restarted for changes to take effect service httpd restart


How do I get the list of nodes of a specific content type and their titles?

PLease try this-
This will load all published nodes of type event.

$query = new EntityFieldQuery();

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

$result = $query->execute();

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

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


get same result from db_query() as views query

Your view most likely has tags getting attached to it, like node_access. Or if you're using grouping on the View that may make a difference in the result property.

Like Nikhil suggested to add that hook somewhere in a custom module just to see what $query has in it. And if you have the Devel module installed you can pass that query like so:

dpq($query);

If it ends up being the case that you have tags being added to the views query and need to mimic that, I'd recommend switching over to the dynamic queries and doing an $query->addTag(...);


How to convert User points to vote ballots?

Use the integration between the User Points module and the Rules module to "roll your own cookies", by writing some custom rules to transfer user points from one account to another.

As a sample, have a look at this rule, which is used in combination with voting of a node, whereas the author looses "-2" points, and the voter looses "-1" points:

{ "rules_votedown_question" : {
    "LABEL" : "votedown_question",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "TAGS" : [ "answers" ],
    "REQUIRES" : [ "rules", "voting_rules", "userpoints_rules" ],
    "ON" : { "voting_rules_insert_node" : [] },
    "IF" : [
      { "node_is_of_type" : {
          "node" : [ "node" ],
          "type" : { "value" : { "answers_question" : "answers_question" } }
        }
      },
      { "voting_rules_condition_check_vote_value" : { "vote" : [ "vote" ], "value" : "-1" } }
    ],
    "DO" : [
      { "userpoints_action_grant_points" : {
          "user" : [ "node:author" ],
          "points" : "-2",
          "tid" : "0",
          "entity" : [ "" ],
          "description" : "Receive downvote to [node:type-name] \u0022[node:title]\u0022",
          "operation" : "QuestionDownvoteReceived",
          "reference" : "By uid=[vote:uid], for [node:type-name] to q=\u003Ca href=\u0022\/node\/[node:nid]\u0022\u003E[node:title]\u003C\/a\u003E",
          "display" : "1",
          "moderate" : "default"
        }
      },
      { "userpoints_action_grant_points" : {
          "user" : [ "vote:user" ],
          "points" : "-1",
          "tid" : "0",
          "entity" : [ "" ],
          "description" : "Issue downvote to [node:type-name] \u0022[node:title]\u0022",
          "operation" : "QuestionDownvoteIssued",
          "reference" : "From uid=[node:author:uid], for [node:type-name] to q=\u003Ca href=\u0022\/node\/[node:nid]\u0022\u003E[node:title]\u003C\/a\u003E",
          "display" : "1",
          "moderate" : "default"
        }
      }
    ]
  }
}

If you simply adapt the amount of points (-2 and -1) to something like (eg) +300 and -300, you've a prototype to transfer (300) user points from one user to another (eg Candidate A). Just repeat for Candidate B and C.

If you replace the Rules event by an event like "something is flagged" (created with the Flag module), a simple click could be used to indicate "I want to transfer some predefined (hardcoded) amount of user points of mine to this user). You could take this even a step further: since flags are fieldable, you could add a field to indicate the amount of points to be "moved", so that the user could enter "300" for Candidate A (instead of some hardcoded, fixed amount).

However, the above Rules example may need further refinements, e.g. if you want to ensure that after moving points from User A to User B, the remaining points for User A is not negative. Refer to "How to check whether one's current User Points are negative with the Rules module?" for details about how you can implement such refinement also.

PS: I'm assuming this question is about D7.


You can try like

 $media_query = db_select('node','n')
         ->distinct()->innerJoin('field_data_field_media_room_type','mtype','mtype.entity_id = n.nid');
        ->fields('n',array('nid'));
        ->fields('mtype',array('field_media_room_type_tid'));
        ->condition('n.type','media_room_page','=');
        ->condition('mtype.field_media_room_type_tid',$media_id,'=');
        $media_res = $media_query->execute();
        while($media_fetch = $media_res->fetchObject()){
         $media_year = '';
            if(isset($media_node->field_year['und'][0]) && $media_node->field_year['und'][0] !=''){
                $media_year = $media_node->field_year['und'][0]['value'];
            }
          echo'<pre>';print_r($media_year);
        }

or

you can use Group By for that particular column.


Is drush.wrapper used anymore for Drush 8? How to use for Windows?

No, don't use drush.wrapper. There is a new tool in town - Drush Launcher. It works on Windows too since it's PHP based - just follow step 4 in the installation instructions. (Step 2 and 3 aren't relevant on Windows, and step 1 is just a normal file download on Windows.)

Added: You should remove/rename the global Drush if you have any. If you need it, check out the fallback option for Drush Launcher.

PS! Also the Linux/Mac people should use Drush Launcher.


You need to pass a fragment to drupal_goto() as an option like so:

$options = array('fragment' => 'nl/admin/overlay');
drupal_goto('some-url', $options);

Reference for this can be found on the url() docs page (the docs page for drupal_goto() actually refers you to there as well).


How to render the field from custom block in node.twig

A node should not have access to a block unless you've done something to add the block to the node. A block can have access to node fields, though (the reverse).

To do what you're talking about I would recommend adding that block to the node in some way. For example:

if you want to add a block as a field in a node:
https://www.drupal.org/project/fieldblock
I would normally use Display suite to then output this block as I want, where I want. But you can also access it via twig template at this point just as you would any other field.

if you're building with paragraphs:
https://www.drupal.org/project/paragraph_blocks


What should be the path to the file while using #attached in a custom_module_block_view()?

You should use drupal_get_path() function to construct the path of your asset file (in your case the JS file).

To include the YOUR_MODULE.js file which sits in a subfolder js, part of your custom module

$block = array
(
    'subject' => t('My block title'),
    'content' => array(
        '#markup' => '<p>' . t('This is some text that will go in the block.') . '</p>',
        '#attached' => array(
            'js' => array(drupal_get_path('module', 'YOUR_MODULE_NAME') . '/js/YOUR_MODULE.js'),
        ),
    ),
);


Find the parent node type of the commerce product being added to the cart

Generally speaking, the line item for each product in the cart has a data array with a context sub-array that includes information identifying the context from which the product was added to the cart. In the case of a product added from a node's Add to Cart form, this array would point to the specific node ID and even name the reference field responsible for generating the form.

If I were you, I'd use the Devel module's dpm() function to inspect the contents of the line item's data array. Drilling down through the context array you should discover how to get the information you're needing. Just make sure to use a !empty() check before assuming a particular key in the array exists!


Taxes not updated after manually adding a product to an order. Drupal Commerce

We ran into the same issue which we worked around by using the Drupal Commerce Point of Sale module to manage manual orders.

As of now, the button "apply pricing rules" is working for us in the order editing form to apply the taxes but we found it easier to use Commerce POS. Your mileage may vary...

Hope this helps!


Allow comments only for the author of the node

although the Drupal 8 version still is on dev but you can try comment_perm module.

The Comment Permissions module enables control of commenting by user
role and by node type. Additional user permissions for selected node
types are added to the user access system so you can configure
commenting with more control than Drupal core provides.

Update
another solution that I could suggest is using hook_form_alter.
in your custom module
function YOURMODULENAME_form_alter(&$form, FormStateInterface $form_state, $form_id) {

  if($form_id == "YOUR_COMMENT_TYPE_ID"){
    $node = \Drupal::request()->attributes->get('node');
    if(!is_null($node) && $node->getOwnerId() != \Drupal::currentUser()->id()) {
      $form['#access'] = false;
    }
  }

}


Theme suggestions for blocks in a region which has a dash in the name

Per the Theme suggestion docs you linked to the format for region-specific block templates go like this:

  An example of a region-specific template would be "block--sidebar_first.tpl.php"

It looks like Drupal flips _ and - in theme suggestions so

  block__header-top

becomes

  block--header_top.tpl.php

(I knew it replaced _ with - but I didn't know it was the other way round too; there may be more to it than that).


Commerce 2 | Quantity Dropdown with Default Values -> Error

I found the solution to my issue:

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

 if (strpos($form_id, "commerce_order_item_add_to_cart_form") !== false) {
$form['quantity']['widget'][0]['value']['#default_value'] = 1;
 $form['quantity']['widget'][0]['value']['#step'] = 0.5;
   $form['quantity']['widget'][0]['value']['#min'] = 1;
    $form['quantity']['widget'][0]['value']['#max'] = 3;
    $form['quantity']['widget'][0]['value']['#type'] = 'select';
 $form['quantity']['widget'][0]['value']['#options'] = array(
 '1' => t('1 hour'),
'1.5' => t('1,5 hour'),
  '2' => t('2 hours'),
   '2.5' => t('2,5 hours'),
   '3' => t('3 hours') );
    }}


Giving a user the choice to appear offline in a view showing online users

Assuming Drupal 7, you can go to /admin/config/people/accounts/fields, attach a Boolean field to user accounts to allow the user to select their preference, then filter on that user field in your view to exclude those who opt out.


Programmatically set updated time on node

I think you can change the value by accessing the variable and saving it then

$clone->changed->value = time();
$clone->save();


Date Display: How to hide part of repeat rule?

The recurrence description is defined in date_repeat_rrule_description() in date_repeat.module.

At this time, there is no way for themes to change it. See this issue: http://drupal.org/node/342665

EDIT

Actually, you may override theme_date_repeat_field(), which calls date_repeat_rrule_description(). You could call your own version of that function to customize the display.

This would leave the contrib modules untouched, but you would be duplicating some effort and have more code to maintain.


There's 2 good options I know of currently: iframe (in colorbox for example) and CTools. Which option to use depends of the circumstances. I guess this information I found in the CTools modal.html file brings out the main difference:

  CTools provides a simple modal that can be used as a popup to place forms. It differs from the normal modal frameworks in that it does not do its work via an iframe. This is both an advantage and a disadvantage. The iframe simply renders normal pages in a sub-browser and they can do their thing. That makes it much easier to put arbitrary pages and forms in a modal. However, the iframe is not very good at actually communicating changes to the main page, so you cannot open the modal, have it do some work, and then modify the page.

I have no personal experienced with CTools on this subject so I can't add anything else to that, but I've implemented the iframe method in a couple of projects. In the most recent one I used the Colorbox plugin to show a few forms created with the Webform module in a popup.
I'll add some example code here in case there's some interest.

Link to the form:

'.t('Send message').'

Javascript code to open the linked address in a popup:

if ($('a.colorbox_form').length > 0) {
  var link = $("a.colorbox_form").attr('href');
  link = link.concat('?colorbox=true');
  // colorbox=true is attached for later use (read below).
  $("a.colorbox_form").attr('href', link);
  $("a.colorbox_form").colorbox({iframe:true, width:500, height:450});
}

In the theme template file:

function mytheme_preprocess_page(&$variables) {
  // Different template and additional stylsheet for colorbox content.
  if (isset($_GET['colorbox']) && $_GET['colorbox'] == TRUE) {
    $variables['theme_hook_suggestions'] = array('page__iframe'); // page--iframe.tpl.php
    drupal_add_css(path_to_theme() .'/iframe.css');
    $variables['styles'] = drupal_get_css();
  }
}

I attached 'colorbox=true' to the links using javascript so that users with javascript turned off would see the form with the normal template. The iframe template only has messages, title and content printed.

This already works, but I ran into a issue with Webforms: 'colorbox=true' wasn't preserved when the form got submitted. My attempt to fix it:

function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if (isset($_GET['colorbox']) && $_GET['colorbox'] == TRUE) {
    // The id-s of the forms that are possibly shown within a popup.
    $form_ids = array('webform_client_form_2', 'webform_client_form_4');
    if (in_array($form_id, $form_ids)) {
      $form['#submit'][] = 'mymodule_webform_submit';
    }
  }
}

function mymodule_webform_submit(&$form, &$form_state) {
  //drupal_set_message('
'.var_export($form_state['redirect'], TRUE).'
');
  if (!isset($form_state['redirect'])) {
    $form_state['redirect'] = array($_GET['q'], array('query' => array('colorbox' => 'true')));
  }
  else {
    $form_state['redirect'][1]['query'] = array('colorbox' => 'true');
  }
}


Custom create account form included in a create content form

All of this is possible, but you will need to write a bit more code for it to work.

First, I suggest you use LoginToboggan.  LT provides a workflow for validating a user's email address which you can hook into either by code or perhaps with the Rules module.  LT already has the framework for tracking if a user is verified or not.  It will be up to you to write the code to create the user (not too hard) and to create the node as published or unpublished depending on the status of the user.

Second, you will have to decide what to do for verification (what if they enter the right email but wrong password?).


Change user roles based on profile field

I think you could write a little module.

db_select() all users with that role_type entry
user_load() them and user_save() them with updated $user->roles[]

Maybe this thread HOWTO assign a user to a role programatically on drupal.org can give you a deeper insight.


You cannot do that because when Drupal invokes hook_menu() and hook_menu_alter() the value contained in $_GET['q'], which is used to find the menu callback to use, has been already changed from the path alias to the normal path.
drupal_path_initialize(), which is called by drupal_bootstrap() contains the following code:

  if (!empty($_GET['q'])) {
    $_GET['q'] = drupal_get_normal_path($_GET['q']);
  }
  else {
    $_GET['q'] = drupal_get_normal_path(variable_get('site_frontpage', 'node'));
  }

What you are trying to achieve can be accomplished in another way: implementing hook_node_access(). Differently from the equivalent hook in Drupal 6, it can be implemented also from modules that don't define a new content type.

function mymodule_node_access($node, $op, $account) {
  if ($op == 'view') {
    $path_alias = request_path();
    // ...
  }
}

$account contains the user object to which is being given access to the node. If the hook returns NODE_ACCESS_ALLOW, then the user has access to the node for the operation passed in $op; if the hook returns NODE_ACCESS_DENY, the user doesn't have access to the node; when it returns NODE_ACCESS_IGNORE, it leaves to other modules the decision.

request_path() returns the path alias if one was used. This means that if the user is using a URL like example.com/node/60, it returns "node/60"; if the user is using
example.com/mynodes/about-us, which is an alias for example.com/node/60, it returns "mynodes/about-us." In the case the user is using example.com/index.php, the function returns an empty string.


What is the difference between Pantheon DROPS and vanilla Drupal?

Pantheon's variant of Drupal is openly hosted on GitHub:

https://github.com/pantheon-systems/drops-7

The main variation that matters is in drupal_settings_initialize():

https://github.com/pantheon-systems/drops-7/blob/master/includes/bootstrap.inc#L720

This is how Pantheon runs sites without making users handle DB or Redis credentials. This change is now in Pressflow as well.

The other material addition is an apachesolr integration package and a way for the site to query the Pantheon API. Those are in modules/pantheon.

The good news is none of this will prevent a site from working anywhere else. The changes are all designed to revert to normal when not on Pantheon.


How to use galleria to create slideshow of Images in a Node

Quick solutions eva module , with this you can set up a view of images with contextual filter (nid) , then attach it to the content type , then it will be available under manage display


How to find hooks being called by a Drupal page?

Use hook_module_implements_alter and do the drupal set message in here. You'll need to use a FAKE cache for the cache_bootstrap bin.

In your settings.php

if (!class_exists('DrupalFakeCache')) {
  $conf['cache_backends'][] = 'includes/cache-install.inc';
}
$conf['cache_class_cache_bootstrap'] = 'DrupalFakeCache';

I will say that hacking core in this case is the preferred way to do this. The person who wrote that linked article is a core maintainer; so they know what there talking about. Using hook_module_implements_alter with a fake cache backend will only make this fire on the first run of that hook. Additional calls to the hook will not be caught due to the static cache. Not using the static cache would require hacking core in this case.


How do I prevent a user from re-using the same password within a certain period of time?

You are looking to alter Password policy module:

A password policy can be defined with a set of constraints which must be met before a user password change will be accepted. Each constraint has a parameter allowing for the minimum number of valid conditions which must be met before the constraint is satisfied.
Current constraints include:

History constraint (checks hashed password against a collection of users previous hashed passwords looking for recent duplicates)

Now, all you need is to take this constrain and make a copy based on time, not number. Should be pretty easy, real difference is in one WHERE condition.
If module provides hooks, make it in your custom module. If it does not, provide a patch with your constrain.


'"media_edit_action" plugin does not exist' error when performing update

I believe that action at some point became deprecated and was removed from the media_entity module.  However, the configuration lingered and is blocking Drupal update from completing successfully.

What worked for me was to go the the Admin > Configuration > Development > Configuration Synchronization > Updates Report (menu tab).

If you view the Full Report, then you can see that the config for the media_edit_action is still present.

Use the pulldown menu on the right to delete that config.

When you run update again, then it should complete successfully.

Hope this helps!


simple numeric token string 2 max 3 digits

$length = 3; // character length
$token = substr(drupal_hmac_base64($node->nid, drupal_get_private_key() . drupal_get_hash_salt()), 0, $length);


How to get url alias of a link, when rewriting field output in Views

The Global Redirects module (drupal.org/project/globalredirect) would be one potential solution! It will automatically redirect all links on your site that are like that globally.


Unsupported serialization format on REST/Delete request

In delete method you can not return ResourceResponse. Try return ModifiedResourceResponse.

return new ModifiedResourceResponse(NULL, 204);

Notice: First argument of ModifiedResourceResponse need are NULL, if your specific data for this parameter  throw same error.


No you cannot save it on the server. One way would be to create your own code to grab the pdf with a tool like cURL and save it to the server. You could trigger your code to run every time a webform is submitted throught Rules and Webform Rules. You could issue a feature request to the module developer in case he wants add this fuctionality.

There is also this module: Fill PDF that does what you require. It is quite harder to get it to work with Webforms since you need to build your own pdf form template.


Calling a Method from another Module's Class

If you want to instantiate a class implementing ContainerInjectionInterface you have to use the Drupal class resolver:
$example = \Drupal::classResolver(Example::class);
$x = $example->request();

The preferred way though is to use a service class instead and inject other services directly as container arguments, as @Kevin commented.


hook_preprocess_field() $variables crashing while printing

Use Devel with vardumper and dump only the $element instead of the whole $variables something like:

function myfi_preprocess_field(&$variables) {
  $element = $variables['element'];
  if ($element['#field_name'] == 'field_download') {
    // Dump only the element.
    dpm($element);
  }
}


What else apart do I need enabled, apart from "block to region" in Display Suite Extras for the "block regions" vertical tab to appear?

You can't use the Default display view mode. You have to enable the Full Content view mode, which will then give you things like Block Regions and custom Page Title options.


How can a user select a different language to the site default language?

Have you tried using the Administration Language module?

  This module lets the administrator see all administration pages in her preferred language.

  You can use this to display the frontend of the site in one language and still keep most of the backend in English (or another language of your choice).


Customize HTML for field in field collection

If your template is being recognized you can access the fields and field content through the $content array. Below is the normal field collection item template file that comes with the field_collection module.

<?php

/**
 * @file
 * Default theme implementation for field collection items.
 *
 * Available variables:
 * - $content: An array of comment items. Use render($content) to print them all, or
 *   print a subset such as render($content['field_example']). Use
 *   hide($content['field_example']) to temporarily suppress the printing of a
 *   given element.
 * - $title: The (sanitized) field collection item label.
 * - $url: Direct url of the current entity if specified.
 * - $page: Flag for the full page state.
 * - $classes: String of classes that can be used to style contextually through
 *   CSS. It can be manipulated through the variable $classes_array from
 *   preprocess functions. By default the following classes are available, where
 *   the parts enclosed by {} are replaced by the appropriate values:
 *   - entity-field-collection-item
 *   - field-collection-item-{field_name}
 *
 * Other variables:
 * - $classes_array: Array of html class attribute values. It is flattened
 *   into a string within the variable $classes.
 *
 * @see template_preprocess()
 * @see template_preprocess_entity()
 * @see template_process()
 */
?>
<div class="<?php print $classes; ?> clearfix"<?php print $attributes; ?>>
  <div class="content"<?php print $content_attributes; ?>>
    <?php
      print render($content);
    ?>

Using devel you can use dpm($content); and you will see the below setup.

So as you see in field collection item you could use $content['field_field_1'][0]['#markup'] if your field has extra markup (like for instance if it was set to display as a link to from entity_reference). You could use $content['field_field_1']['#items'][0]['safe_value'] to get the safe value of the field (sanitized). If you want to customize the markup around a certain field you can hide the field and the render it somewhere else. See the below code for an example.

<?php

/**
 * @file
 * Default theme implementation for field collection items.
 *
 * Available variables:
 * - $content: An array of comment items. Use render($content) to print them all, or
 *   print a subset such as render($content['field_example']). Use
 *   hide($content['field_example']) to temporarily suppress the printing of a
 *   given element.
 * - $title: The (sanitized) field collection item label.
 * - $url: Direct url of the current entity if specified.
 * - $page: Flag for the full page state.
 * - $classes: String of classes that can be used to style contextually through
 *   CSS. It can be manipulated through the variable $classes_array from
 *   preprocess functions. By default the following classes are available, where
 *   the parts enclosed by {} are replaced by the appropriate values:
 *   - entity-field-collection-item
 *   - field-collection-item-{field_name}
 *
 * Other variables:
 * - $classes_array: Array of html class attribute values. It is flattened
 *   into a string within the variable $classes.
 *
 * @see template_preprocess()
 * @see template_preprocess_entity()
 * @see template_process()
 */
?>
<div class="<?php print $classes; ?> clearfix"<?php print $attributes; ?>>
  <div class="content"<?php print $content_attributes; ?>>
    <?php
      // Hide field collection field.
      hide($content['field_image']);
      print render($content);
    ?>

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

Hopefully all of this helps, if not let me know and I can adjust to what exactly you are needing or explain more :)


How to override certain function in a module to disable the return value

The value returned from the implementations of hook_footer() is used from theme('closure').

function theme_closure($main = 0) {
  $footer = module_invoke_all('footer', $main);
  return implode("\n", $footer) . drupal_get_js('footer');
}

That function is called from template_preprocess_page(), which uses the following code:

  // Closure should be filled last.
  $variables['closure']           = theme('closure');

  if ($node = menu_get_object()) {
    $variables['node'] = $node;
  }

If you want not to print the value returned by hook_footer(), you have the following options. As you are talking of articles, I get you mean nodes whose content type is "article"; if you used the word articles to mean nodes, then remove the part that checks the value of the type property.

Empty $variables['closure'] inside a preprocess function, which can be implemented in a module, or a theme (inside template.php). The following code is the code I would write for a theme.

function mytheme_preprocess_page(&$variables) {
  if (!empty($variables['node']) && $variables['node']->type == 'article' && !$variables['node']->status) {
    $variables['closure'] = '';
  }
}

If you are not interested in the content type of the node, then the code becomes the following one:

function mytheme_preprocess_page(&$variables) {
  if (!empty($variables['node']) && !$variables['node']->status) {
    $variables['closure'] = '';
  }
}

In the page.tpl.php file you normally find the following code to print the value returned from hook_footer():

<?php print $closure; ?>

Replace that line with the following one:

<?php if (!empty($node) && $node->type != 'article' && $node->status): ?>
  <?php print $closure; ?>
<?php endif; ?>

If you just need not to print the value of $closure when a node is not published, independently from the content type of the node, then the code simply becomes:

<?php if (!empty($node) && $node->status): ?>
  <?php print $closure; ?>
<?php endif; ?>

In this way, you can remove the value added to $closure from all the implementations of hook_footer(). You can also remove the part added from a specific module, if the module always adds the same string.

If you want to change the value returned from your implementation of hook_footer(), you can use menu_get_object() to get the node object associated to the page, if there is one.

function mymodule_footer() {
  $node = menu_get_object();

  if (!empty($node) && $node->type == 'article' && !$node->status) {
    return '';
  }

  // Return the value you would return when the node is published.
}


There are three ways to go about.

1) Use views. In views the Field to add is Content : Title. (Even if you change the name of the title field it is still title. It is just changing the label on the form.)

2) You can install Display Suite Module. Once you install this module you would get additional fields once you select a layout in the layouts section.

  Display Suite allows you to take full control over how your content is
  displayed using a drag and drop interface. Arrange your nodes, views,
  comments, user data etc. the way you want without having to work your
  way through dozens of template files.

3) The third method is to work with the node.tpl.php you have a node object. Since you are using teaser the title would be available in a field. All the other fields can be accessed from the node object.


Drupal Elysia Cron Max execution time error, in select.inc

Please note that Drush can use different PHP configuration file for CLI than your Apache, so you need to increase your time in there (max_execution_time).

To find where is your PHP config file, run: drush status, e.g.

$ drush status
...
 PHP configuration               :  /etc/php/7.0/cli/php.ini
...

then edit the file and increase your max_execution_time to higher value.

Alternatively add the following line in your PHP function which expect to be run by cron for longer time:

ini_set('max_execution_time', 0);


Auto node redirct depending on a cck field's content

There is multiple way of doing this. Probably the best one is create a custom module and

Using hook_menu_alter(), alter the page callback for node/%node. In your page callback, check the type of the node to invoke node_page_view on the node or redirect to the referenced node.

MODULE_menu_alter(&$items) {
  $items['node/%node']['page callback'] = 'MODULE_node_page_view';
}

MODULE_node_page_view($node) {
  if ($node->type == MODULE_NODE_TYPE) {
    //if fixed_x is a node nid
    $reference = $node->field_x;
    drupal_goto('node/'. $referenced_node->nid);
    //if fixed_x is a path
    drupal_goto($node->field_x);
    //etc
  }
  else {
    return node_page_view($node);
  }
}


Set the message field as not required in a custom contact form

I've solved this issue this way:

function hook_entity_base_field_info_alter(&$fields, EntityTypeInterface $entity_type) {
  if ($entity_type->id() == 'contact_message') {
    if (isset($fields['message']) && $fields['message'] instanceof BaseFieldDefinition) {
      /* @var BaseFieldDefinition $field */
      $field = &$fields['message'];
      $field->setRequired(FALSE);
    }
  }
}


What is the easiest way to install clean Drupal from scratch using drush?

drush qd

Downloads Drupal, runs site install, launches a lightweight webserver, opens a browser and logs you in as 'admin'.

I might have answered drush quick-drupal, but Clive said there might be a contest.  :)


Generate a fancy PDF certificate from form?

You can build a proper fillable PDF form and then use the Fill PDF module to merge it with data from a node or a webform.

Have a look at the demo on the Fill PDF service website.


How can I give option tags of a select tag ids or classes in Drupal 7?

You cannot give class or an id to options directly through form api. you can however, theme select element to add classes to select options.

   // theme_select
function THEME_select($variables) {
  $element = $variables['element'];
  element_set_attributes($element, array('id', 'name', 'size'));
  _form_set_class($element, array('form-select'));
  return '<select' . drupal_attributes($element['#attributes']) . '>' . THEME_form_select_options($element) . '</select>';
}

/**
 *
 * @param type $element
 * @param type $choices
 * @return string
 */
function THEME_form_select_options($element, $choices = NULL) {
  if (!isset($choices)) {
    $choices = $element['#options'];
  }
  // array_key_exists() accommodates the rare event where $element['#value'] is NULL.
  // isset() fails in this situation.
  $value_valid = isset($element['#value']) || array_key_exists('#value', $element);
  $value_is_array = $value_valid && is_array($element['#value']);
  $options = '';
  foreach ($choices as $key => $choice) {
    if (is_array($choice)) {
      $options .= '<optgroup label="' . $key . '">';
      $options .= THEME_form_select_options($element, $choice);
      $options .= '</optgroup>';
    }
    elseif (is_object($choice)) {
      $options .= THEME_form_select_options($element, $choice->option);
    }
    else {
      $key = (string) $key;
      if ($value_valid && (!$value_is_array && (string) $element['#value'] === $key || ($value_is_array && in_array($key, $element['#value'])))) {
        $selected = ' selected="selected"';
      }
      else {
        $selected = '';
      }
      $options .= '<option class="' . drupal_clean_css_identifier($key) . '"  value="' . check_plain($key) . '"' . $selected . '>' . check_plain($choice) . '</option>';
    }
  }
  return $options;
}

Similar question is answered here


Show Field Collection fields together in same field item

The problem was with how the field collection was set up. Originally, the field collection fields had unlimited values, while the field collection in the content type was limited to one value.

I reversed this so that the fields were limited to one value and the field collection has unlimited values.


Complex conditional logic for Webform field in YAML format

Nested states can be tricky. Make it two conditions:
visible:
  - ':input[name="field_a"]':
      filled: true
    ':input[name="field_b"]':
      filled: true
  - or
  - ':input[name="field_a"]':
      filled: true
    ':input[name="field_c"]':
      filled: true


One submit button posting to multiple functions

You can't add submit handlers to form after drupal_get_form() is called, because they will not be processed.

You need to add submit handler in hook_form_alter(). If you want add this handler only in specific cases, you can add cutom parameter to drupal_get_form()

Code in block:

$form = drupal_get_form('test_form_form', 'add_pm');
$output .= drupal_render($form);
return $output;

Code in custom module:

function MODULE_form_alter(&$form, &$form_state, $form_id) {
   if (($form_id == 'test_form_form') && ($form_state['build_info']['args'][0] == 'add_pm')) {
     // add custom submit only if form was called with parameter.
     $form ['#submit'][] = 'pm_form_submit';
   }
}

function pm_form_submit($form, &$form_state) {
  drupal_set_message('pm_form_submit');
}


Odd behaviour on form validation when in block mode

Taking a bit of a stab in the dark here, but I'm suspicious of this comment in your linked code right above hook_block_view():

// used in node--landing-page.tpl.php

That suggests that you're calling this block in directly from a template file, not through the normal block system, which won't work properly.

The problem is that the template files are built too late in the page build, in this case after the system messages have already been taken from the session and cleared out for the next page. So the validation messages do get added to the messages array in the session, but they won't be outputted until the next page is loaded.

I would suggest instead implementing hook_node_view() and adding your block into the content there. That hook is run early enough on in the page build that you won't see the delay with error messages.


Use theme function to change the search form input type

There is no way to change the type of the search box form item with a theme function, but here's a theme friendly answer :-)

By default the Search input type isn't supported in Drupal 7, so you can't use any kind of hook_form_alter to change it out of the box.  You can do the following though to give you the ability to do what you want though:

Download and enable the Elements module from the awesome Dave Reid.
Add the following to your template.php file (you can omit the size - I just put it there to make the box a bit shorter):

function THEMENAME_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'search_block_form') {
    $form['search_block_form'] = array(
      '#type' => 'searchfield',
      '#size' => '20'
    );
  }
}

This could also me done easily in a custom module, but I know you asked about theming specifically.


Calculate the number of days since the creation date of a user account

This depends on what you need to do with it.  If you truly just need the number of days, then this will work

$user = \Drupal::currentUser();
$created = new \DateTime('@' . $user->getAccount()->getCreatedTime());
$interval = $created->diff(new \DateTime());
$days1 = $interval->d
$days2 = intval($interval->format('%d'));

Here $days1 and $days2 should give you the same value.  See the docs for \DateTime and \DateInterval for more information.

If you need a nifty string for output purposes, then check out DateFormatter::formatTimeDiffSince() and friends:

$user = \Drupal::currentUser();
$created = $user->getAccount()->getCreatedTime();
/** @var \Drupal\Core\Datetime\DateFormatterInterface $date_formatter */
$date_formatter = \Drupal::service('date.formatter');
$created_since = $date_formatter->formatTimeDiffSince($created);

and then $created_since will be a string like '7 weeks 2 days'.  You can also use the 'Time ago' formatter directly in the entity rendering configuration.  The default view for the accounts listing does this.


Ajax http request terminated error while installing a Drupal 8 site

The UnmetDependenciesException is something you get when Drupal tries to install a configuration that depends on other modules/configuration which are missing.

You shouldn't see this error installing one of the standard install profiles. My hunch is that the source to your errors is PostgreSQL which is not fully supported by Drupal 8 at this time of writing.

See more in the issue queue: https://www.drupal.org/node/2157455 for running Drupal 8 on postgreSQL.


Use Webform Results in another webform content type

You can programmatically modify the form of Approve Request webform using hook_form_alter() function. In this form you can retrieve the previous webform submission entries and append in the Approve Request form.

You can retrieve previous webform submission using following snippet:

include_once(drupal_get_path('module', 'webform') .'/includes/webform.submissions.inc');
$nid = arg(1); // need to hard-code nid if this is a custom page you can manage dynamically also
$sid = $_GET['sid'];
$submission = webform_get_submission($nid, $sid);


Set weight for JavaScript files loaded via theme.libraries.yml?

You need to try this with in libraries.yml file

js:
    js/foo.js:
    js/bar.js: { weight: N }


How to programmatically add menu for content type?

In hook_menu and set 'access callback' to custom function and then:

$node->type == 'my_node_type'

and/or user type that can access this node...


The second parameter is $mode, which you can provide. e.g.

drupal_mkdir('public://myfolder/', 0755);

By default the 'file_chmod_directory; will be used, which, by default, is 0775.

Exactly what mode you use will obviously depend on your server set up. If you're not sure, ask your sysadmin what it should be.


From the MergeQuery docs

An ANSI SQL:2003 compatible database would run the following query:

MERGE INTO table_name_1 USING table_name_2 ON (condition)
  WHEN MATCHED THEN
  UPDATE SET column1 = value1 [, column2 = value2 ...]
  WHEN NOT MATCHED THEN
  INSERT (column1 [, column2 ...]) VALUES (value1 [, value2 ...

Other databases (most notably MySQL, PostgreSQL and SQLite) will emulate this statement by running a SELECT and then INSERT or UPDATE.

You need to do a SELECT using db_query first, to find out if your data already exists.
Then you can use drupal_write_record, which will do either an UPDATE or an INSERT depending on whether or not you populate the tables primary key(s).


How to set reading permission for each separate page?

The Content Access module allows you to configure permissions by content type or, with some additional configuration, by node (per page).  It works on D6 and D7.


Failure getting nodes from terms via the rest api

The taxonomy_term resource is only for returning taxonomy terms. It won't return any nodes.

There are tons of options but here are two that you can do quickly:

Install the Views Datasource module and create a taxonomy view. Have it output as json.
Create a custom resource that handles this. Check out these instructions on creating a custom resource.


Should dependent libraries list all dependencies?

In general, a library (or any entity/resource in programming that depends on other entities/resources) should only include dependencies for things that it actually uses.

Given your example, bar and baz should depend on jQuery if they use jQuery functions directly. If, however, they only use functions that are provided by foo (which, in turn, uses jQuery), then bar and baz should not depend on jQuery.

Here's another way to look at it: in the future, if foo no longer needs jQuery, and you remove jQuery as a dependency from foo, do bar and baz break as a result? If they break, then they should have had a direct dependency on jQuery. If they don't break (because all of the jQuery dependency is encapsulated in foo), then they don't need a dependency.


implementation of hook_menu() is not working

There are 2 things going on: you've not defined the permissions on the menu & you've not defined the page callback for when the 'instrument' path is accessed. Without this, Drupal doesn't know when or what to display for your 'instrument' menu item.

Doing something like this:

  $items['instrument'] = array(
    'title' => 'Instrument',
    'type' => MENU_NORMAL_ITEM,
    'menu_name' => 'main-menu',
    //@TODO: define a function called mymodule_instrument_page_callback
    // that will render the page for the 'instrument' path.
    'page callback' => 'mymodule_instrument_page_callback',
    // Setting 'access arguments' => array('view content')
    // will allow anyone with the 'view content' permission to view the menu item.
    //'access callback' can be used for dynamically determining access
    'access arguments' => array('view content'),
  );

Will make your menu item available. See the hook_menu() docs for information on page & access callbacks.


Bug created by a module. Which enterd the system a bit to early.


Reading through Placeholder module I come to know this

  Once FAPI uses HTML5 to render elements, this module can be replaced
  by the "placeholder" attribute available as part of the HTML5 spec.
  You can update the FAPI to use the "placeholder" attribute right now
  by using elements module. This means that this module is only useful
  if you are concerned about older browsers that do not support
  "placeholder".

try using elements module so the support for HTML5 attribute can become available in your installation.

Here is the way to add default placeholder attribute.


Configuration override not work from settings.php

You can use the --include-overridden option to show overridden config, for example:

drush cget --include-overridden system.site name


Hide parent term and show only second level

Assuming that when you say "When the parent term is visited" you mean at the taxonomy term page at taxonomy/term/[..], the view settings below will work.

View type : Term
Display : block
Pager : Display all items

Relationships : Taxonomy term: Parent term
> Identifier: Parent

Contextual filter : (Parent) Taxonomy term: Term ID
> Relationship : Parent
  > When the filter value is not available : Provide default value
    > Type: Taxonomy Term ID from URL
    > Load default filter from term page : checked

If you want the parent term to appear instead of the vocabulary name, also do:

  > When the filter value is available or a default is provided : Override title
    > (argument) %1

You can also enter a space instead of "%1" to clear it since the parent term already appears by default as page title (otherwise it will appear twice).

Finally, if you want to sort by term weight, also do:

Sort criteria : Taxonomy term: Weight (asc)

Enable the block to only display on taxonomy term pages, appearing above the main page content block.

You can also do some interesting things when you combine the Taxonomy Menu and Menu Block modules.

Hope that helps!


How to make state/provinces list dynamic on user profiles/registrations? with international addresses?

So, there's a patch for this. The last patch used against the 3.x dev module provided the desired results. Dynamic States list patch


Need to automatically rotate the result of a view once a week (Sunday night)

The problem with that solution is it relies on the view's cache lifetime which might not sync up to Sunday (e.g. a manual cache clear it will reset the lifetime clock on the view cache and expire it 6 days from the manual cache clear).

A better solution would rely on hook_cron() and do the following:

Trigger every Sunday
Set all node fields to false
Randomly select a node and update its field to true.

This could be accomplished with a custom module hook_cron or, I think, the Elysia Cron module.


Userpoints: Require userpoint for being able to create a node?

There is a module in the userpoints_contrib project, which does exactly this.

You can combine it with userpoints_nc or a rule to also deduct points when a node is created, so that creating nodes costs something.


Deploying to multiple hosts using Webistrano

As per this Capistrano Wiki page, you can restrict tasks and single commands to specific :roles and :only attributes:

task :migrate, :roles => :db, :only => { :master => true } do
  # ...
end

task :other do
  run "migrate", :roles => :db, :only => { :master => true }
end

Using this, I was able to run the refresh_configuration task to run on a server with a specific attribute.


How can I customize the message after register?

It might be overkill for a single message but the String Overrides module would work.

It includes a UI for quickly adding string replacements for anything that is passed through the t() function, which includes the message that you're trying to replace.


How to check if library is present in vendor folder?

If you are talking about libraries, which are defined in files like *.libraries.yml, then you can use this:

\Drupal::service('library.discovery')->getLibraryByName('MODULE_NAME', 'LIBRARY_NAME')

You'll receive an array with all data including paths to check that files are exist.


Within Panels, get node ids that contain taxonomy term

Rather than getting the nid from within Panels, I just used taxonomy_select_nodes and passed the result to panels as a second argument in the URL eg panels-view/%tid/%nid.

This solved my problem.

Thanks


Trying to use Replace to change the output of value on a view using custom text

have you try to use Rewrite results in views field settings? In Rewrite results there is an option Override the output of this field with custom text if you click on it it will let you change the output of this field to whatever you want.
plus there will be a Replacement patterns option which will show you a list of replacement tokens. also you can add some HTML if you want/need to.


using hook_query_alter with fieldcondition()

This was solved using the $query->innerJoin()


Changing output format of displayed body text

You can safely make changes to the regular "Full HTML" filter. It has no special significance in the system. It is simply created by the "Standard" install profile because it is convenient for end users. If you install a minimal profile you won't have it at all.

Obviously changing the full html filter will affect other nodes as well that use this filter.


Check for field values to be unique when storing into the DB

When you use fields GUI to add fields to a content type, it is correct that the GUI do not let you set the UNIQUE constraint.

However, the fields created in this way is stored in the SQL database. They're in a table named field_data_ followed by the machine name of the field.  So it is possible to add the UNIQUE constraint to any field after it has been created by means of an SQL ALTER TABLE statement, e.g.:

ALTER TABLE `field_data_field_user` ADD UNIQUE (
  `field_user_value`
)

As long as you only do this to fields that you've created yourself, I do not see any problems.

However, it is also possible to create the content type yourself as an entity, using the Drupal Schema API.  If you've business logic that isn't part of the fields repertoire (such as deletion of an old research assignment before inserting a new one), it is probably better to use the Schema API istead of fields to create the content type.  This is still not plain SQL (the Schema API expects you to declare the database tables in a structured array, and Drupal DB API is using PDO-like objects to interact with the database), but it has the same power and flexibility as plain SQL.

Note that declaring the user and project fields unique will not get the old assignment automatically deleted before the new is inserted.  All this constraint does is to reject operations that does not satisfy the contraint.

To use transactions in Drupal, you just call $txn = db_transaction(); in your own module. The transaction will remain open for as long as the variable $txn remains in scope. When $txn is destroyed, the transaction will be committed.


How to create responsive list items using bootstrap theme

You might need to use the Bootstrap column classes with divs instead of table elements, inside of a "row" element, which must be inside a "container" element:

There is more information about using the Bootstrap grid system in the main Bootstrap page.


Patch drupal.org project (core/module/theme) with issue fork

It has been discussed already in the Opt-in to the Drupal.org Issue Forks and Merge Requests beta thread, see 3152637#comment-13820062.  As of now there is no straight way to integrate commits in composer patch work flow. You need to download the patch file manually by appending .patch to the merge request URL and copy it locally into your project to get it applied in the build process.
"patches": {
    "drupal/foobar": {
        "3200808 - Lorem ipsum": "./patches/3200808-3.patch"
    }
}

You can get additional information on how to generate patch from the commit Id from the guide: Patch files for use with Composer.


*Some* Users Experiencing Login Failures

I would ask one of the people who has had this problem to work through it with you. Do a skype screenshare or look over their shoulder while they experience the problem.

In my experience, these people are not clicking "save" after entering a new password so their password isn't actually getting changed.


How to get the Date, when particular field of a node is equal to some value?

You have to use one of the events described in Entity CRUD, editing, and view hooks.

One example from the documentation:

function hook_ENTITY_TYPE_update(Drupal\Core\Entity\EntityInterface $entity) {
  // Update the entity's entry in a fictional table of this type of entity.
  db_update('example_entity')
    ->fields([
      'updated' => REQUEST_TIME,
    ])
    ->condition('id', $entity->id())
    ->execute();
}

You can get the original field values from $entity->original->status and check if the status has changed.


Can a view "a" appear only in the page of view "b"?

Put him in a block and show that block only on the page of the other view.  Or more precisely, create a block display for view a and have it displayed only on the path defined by the page display in view b.


Best way to enter(insert) the content in drupal, so a non techie can edit the content

Do you have a WYSIWYG editor installed for your end-users?

You can use CKEditor, or a number of other editors, and install as a module. Here is a walkthrough for installing CKEditor: CKEditor Quick Start,
 Or you can install the WYSIWYG module and choose from a handful of WYSIWYG editors to use on your site. By doing so, you would give your content editors a way to create content similarly to how we enter our answers and code examples here on StackExchange and your users will not need to know any html or code to get the job done.


How do I make a Views jump menu to anchor links?

Add another title field for the document, which will have no rewriting at all and hide it from the output (checkbox "Exclude from display"). Then use this second title field when for displaying in jump menu.


Unable to set the data property xxx as the parent data structure is not set

I've found the issue.
In fact insted of set a lat and a lon value, I had to use "Create geofield values from lat/lon".


I'm a bit confused where you're entering the code above? If I want a checkbox to default to checked then in the UI you can specify this. See screen shot where I've added a field with a label "Shippable".


SSH authentication failed, please provide another key- Acquia

I had this problem too with Dev Desktop 2.
It was my first time trying to pull an Acquia cloud site to local.
I generated a key, added my public key to my Acquia profile, but still kept getting Authentication errors.

What fixed it for me was...
SSH into the server (little square next to the SSH path in dev desktop), then just close it.
I was then able to pull the cloud site to my local machine.


Try running drush from inside the VM.

First, use vagrant ssh to get inside.

Then, change directory to the docroot:

cd /vagrant/docroot/

You should be able to run Drush commands from there.

In theory, if you know how to set up Drush aliases, you won't need to do that, but this method is a useful shortcut.

Let me know if it works -- and good luck!


Invalid URL Aliases in Drupal Nested Sites/Subsites - Main 404

Option 1 - base_url
Maybe you want to do some experiments to see if setting the $base_url in your settings.php somehow helps.
Option 2 - RewriteRule
It might be worth trying to further enhance your .htaccess file, by adding a line after the line containing RewriteBase, which looks like so:
RewriteRule . index.php [L]

For more details on the above line, refer to the (accepted) answer in this question on StackOverflow.


Send Notification to users with username and password

You can notify your user by mail using drupal_mail either at the time of updating your password. You arrange your username/password in some template using HTML & send that by help of the above given function drupal_mail.
I hope this help. Let me know if do..


How to export content to XML, CSV or RTF for print

Views Data Source is pretty awesome for XML, the 7 release is in dev but we are using it on our D7 to create feeds for android / iphone apps and a intranet running D6.


Twig_Sandbox_SecurityError: Calling "setOption" method on RC4

Core recently added a default sandbox so that it's not possible to e.g. call the delete method on node objects.

See https://www.drupal.org/node/2513266, you can bring it up there and try to allow it, try to extend it yourself or call that option in preprocess. Not sure what the best option is.


Views: Modify filter/argument when no results occur

You can call the view programatically and if no result are found call it again with new filter arguments.

For example:
    $view_id = 'your view id';
    $display_id = 'your display id';

$view = views_get_view($view_id);
$view->preview($display_id, $views_args);

if (!count($view->result)) {
  // No results, call view again with other filter value.
  $filter_name = 'your filter name';
  $filter_value = 'your filter value';

  $view = views_get_view($view_id);
  $view->preview($display_id, $views_args);
  $view->display['default']->display_options['filters'][$fiter_name]['value'] = $filter_value;
  $view->preview($display_id, $views_args);
}

You will have to adapt it using your current filter name and right values. You can rewrite this example to modify the view all the times you need.

Put this code in a hook_menu callback returning the  view.


Is it possible to find which user created an account?

You have to create a custom module for this.

First you have to add a user field here admin/config/people/accounts/fields. Add a field that will check whether the user has been created by user with role "doctor". A boolean field would suffice. Mark the field as non-mandatory
Create a custom module. This module will provide an interface that only the users with role "doctor" can access. In the interface provide a button, clicking that button will create user with role "patient", also flag the field you created above.
Now in views create a page or block that will display the users, in the filter criteria of the view check whether the boolean field is flagged for that user.


You can use Conditional Fields module to display form fields with certain conditions. No need to use custom ajax calls.

  Conditional Fields allows you to manage sets of dependencies between fields. When a field is “dependent”, it will only be available for editing and displayed if the state of the “dependee” field matches the right condition.


How to get the field settings in drupal 7

You can use a combination of field API and taxonomy API functions to get this info:

$field_name = 'field_FIELD_NAME';

// Get the field info
$info = field_info_field($field_name);

// The link to the vocab is stored as it's machine name
$vocab_machine_name = $info['settings']['allowed_values'][0]['vocabulary'];

// Load the vocab by machine name
$vocab = taxonomy_vocabulary_machine_name_load($vocab_machine_name);

// Finally, get the vid
$vid = $vocab->vid;


Have you tried the Views Calc module? I think you will get what you want from it. Here is an excerpt about it from the module's project page:

... adds simple calculations to a views table. Requires the Views module.
You can SUM, AVERAGE, COUNT, MIN, MAX, or AVG selected columns. A plug in theme makes the view look more spreadsheet-like (right justifies numeric fields, shades calculated columns and rows, and underlines calculated rows).


Adding markup inside first list item of main-menu

I managed to apply the code only to the item in the main-menu by introducing a condition of menu-name and #href:

function mymodule_preprocess_menu_link(&$vars) {
  $element = &$vars['element'];
  $my_view = views_embed_view('view_name', 'display_id');
  if(strpos($element['#href'], 'home') !== false && $element['#original_link']['menu_name'] == 'main-menu')
  {
    $element['#below']['#markup'] = $my_view;
  }
}


How do I reverse the order of submit and preview button?

One solution is to use hook_form_alter() in a custom module to make the submit button heavier than the preview button:

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

  if($form_id == 'MYNODETYPE_node_form') {
    $form['actions']['preview']['#weight'] = $form['actions']['submit']['#weight']-1;
  }
}

Just change the module name and form id accordingly.


How to render views inside page-front.tpl.php?

<?php
print views_embed_view('my_view', 'block_1', $arg1);
?>

replace view_name with your view name
replace block_1 with your machine name
replace $arg1 with an argument (if want to manually pass a value to your contextual filter) This is optional, if you're not going to use it, you can delete it.


Allows users to pass from flat to threaded view for forum comments

Unfortunately, on Drupal 7 that setting is not per user, but per content type. So you need to go to the content type's comment settings and choose either flat or threaded view.


You do not need to create your own Validator. Instead, use setPropertyConstraints instead of addConstraint to attach the Regex validator to the individual property of the field rather than the FieldItemList. For a string field, add the constraint to "value." For a link field, you may want to add it to "URI," etc. Here is an example:
->setPropertyConstraints(
  'value', ['Regex' => [
    'pattern' => '/^[0-9]+$/',
    'message' => t('Please use numbers only in the blah field.'),
  ]]
);


How to create a taxonomy terms dropdrown with Views

There are several approaches:

A. Create a View out of Taxonomy Terms with a Page Display.

For fields add: term id, term name
For filters: Term name (with widgets) and expose the filter

Choose then:

Dropdown,
Vocabulary (of your choice)
Expose this filter to visitors...,
'Is one of' then select all terms from the vocabulary
Remove duplicates

In Views UI, on Advanced Tab

Exposed form in block: Yes
Exposed form style: Basic | Settings
Adjust settings to have autosubmit

B. Create a View out of Content and choose Taxonomy Terms among fields, similar to above.

C. Create a View with Block display from Taxonomy Terms and at Format Tab choose Jump Menu. If you need to overwrite the Jump Menu path you need to add a custom text field and create your desire path out of Replacement Patterns.

Than select the created custom text field from Jump Menu path settings


The field name (on both source and destination sides) for path aliases is 'path'. As Jaypan says, migrate_d2d should be mapping that for you by default.


Sending attachment on webforms with drupal 7

This is a problem of Webform ver. 7.x-4.14. Try to use 7.x-4.x-dev version of webform or apply patch #2 from https://www.drupal.org/node/2675170


This is not a form API level feature, it's field/widget API.

For a custom form, you have to build it yourself with an add more button that uses #ajax to add more elements. A full code example would be too complicated for an answer, but you have to keep track of the count in $form_state, on pressing of the button increaes it, rebuild the form and then return the new elements.

See https://api.drupal.org/api/drupal/core%21core.api.php/group/ajax/8.2.x for more documentation, a quick tutorial that I found: https://www.sitepoint.com/using-ajax-forms-drupal-8/


Drupal authentication for a non-Drupal script

You can wire up your script via a hook_menu, and instead of returning the output to render via Drupal, you can print it directly and exit at the bottom of the function.  The submission handler would do the same thing, but drupal_goto() at the end.

That said, this is a moderately bad idea for the long run.

A better solution would be to use Webforms.  Webforms are really easy to make, get stored in the database, and can be exported to Excel.  I wouldn't be surprised if there is webform hook available so you could do your filesystem thing, too.

Another option is to use the Forms API to make your form w/ your custom validation and submission handlers.


Basically you need recurring meetings like in outlook.

I think you will have to create a rule based on flags. The flag could be something like daily, weekly, bi-weekly, monthly or yearly. Once an organiser selects the flag, rule should create nodes with meeting start time in future according to which flag was set.

Also give user an option to select # of events or end duration and you can put this check in your Rule as well to limit the events it creates.