How to disable context from URL in Views

Found the solution. Actually this doesn't disable a context from URL. But it worked for my demand.

Click 'add' under Filter criteria.
->Select 'User: Current'.
->Select 'Is the logged in user' as 'Yes'.

That's all.


I've added both node created and node changed fields to my views before, this is how I output them:

Date Created: {{ fields.created.content }}
Date Modified: {{ fields.changed.content }}

I assume user would work the same way. It will render in whatever way the view field is configured.

For example: {{ fields.uid.content }}


Views block: Displaying a content block on profile page (/user) with user's chosen tags as contextual filter

I have found a solution to this. Using a user view instead of a content view was the way to go for me. Then adding appropriate relationships on the teaxonomy term.

I used the these directions:

Create a user view.
Add a contextual filter on user: uid. If no filter value is present, build a default value using the currently logged in user. (This will give you exactly one user object in your view -- the logged in user.)
Add a relationship, using the relevant taxonomy reference field on the user accounts. This will bring you information about the "interest" term for the logged in user.
Add another relationship, called "term: nodes marked with term" (or something like that). This will bring you information about all nodes marked with the interest term for the logged in user.

From this article:
https://drupal.org/node/1111722

Hope it helps!


Make insert module add uploaded images to media library automatically

Instead of using the Insert module, use the Media module's WYSIWYG integration. This adds a button to the WYSIWYG toolbar which allows you to choose an item from the Media library. You can also upload a new media item which adds it to the library and selects it to be inserted into the WYSIWYG editor. The link above explains how to set it up. Make sure you follow all the steps. You have to enabled this functionality in both the WYSIWYG profile and the text format to get it working properly.

Also, check out this great video on Media for some more information.


Well that was a nasty one. I downloaded and unpacked the latest Drupal version as instructed. But then made a copy using Finder. Unfortunately this leaves out the all files starting with a ..

After copying the files on the comannd line everything works as ecpected. Thanks to @leymannx for pushing me into the right direction.


Is it possible/ feasible to convert ordinary nodes to Ubercart nodes?

I'm not sure how the ubercart theme you're interested in works, but you can declare any content type as an ubercart 'product' type. This would eliminate the need to convert exsiting/imported nodes, but I'm not sure if the theme you're looking at is only set up for the default Product type that ubercart creates for itself.


Hiding referenced term name from node display

In the content type or paragraph type go to Manage Display and configure the format of the term field as "Rendered entity".

Copy taxonomy-term.html.twig to the template folder of your theme and remove the linked title:
{{ name }}

taxonomy-term.html.twig

  {{ title_prefix }}
  {% if not page %}

{{ name }}

  {% endif %}
  {{ title_suffix }}
  {{ content }}


Creating testing local site from online production site

First, try to do the move the project to your server again but DO NOT go through the installation process. Simple add all the files to the proper directory then move in all the data. After that, just try going to the home page.

If that wasn't it I feel like you probably skipped giving 'admin'@'localhost' permission to access your db.

Try checking admin's priviledges in the MySQL console:

mysql> SHOW GRANTS FOR 'admin'@'localhost';

If admin doesn't have privileges, go into MySQL console and:

Create a user(if you don't have one made): mysql>CREATE USER 'admin'@'localhost' IDENTIFIED BY 'apassword';
Now, give admin priviledges: mysql>GRANT ALL PRIVILEGES ON *.* TO 'admin'@'localhost'
Lastly, flush! mysql>FLUSH PRIVILEGES;

Hope this fixes it!


Get the highest Matched output in result

It's something like this ... Since I dont have your exact table in my database it could be slightly wrong. But this is 80% or 99% what you're asking.

$query = db_select('my_table', 't')
    ->fields('t', array('UserID'))
    ->condition('contentID', 31)
    ->groupBy('UserID')
    ->orderBy(2, 'DESC');
$query->addExpression('COUNT(t.UserID) AS num_items');
$results = $query->execute();

// dpm() is in the Devel module.
foreach ($results as $record) { dpm($record); }

EDIT:

The final query that worked was:

$query = db_select('flag_content','fcnt')
->fields('fcnt', array('uid'))
->condition('fcnt.content_id', array(178,225), 'IN')
->groupBy('fcnt.uid')
->orderBy('num_items', 'DESC');
$query->addExpression('COUNT(*)' , 'num_items');


Features along with configuration synchronization

Can I just use features to create new article module through features
  ui and use it?

Except for some very trivial use cases: No.
But Features still is a good starting point and a big time saver.

Don't expect Features to produce ready-to-use modules of complex Features. It is a great code/stub generator, but be prepared for finetuning both before in Features UI and afterwards on file level.
Plan your fields carefully: While single-use fields make it easier to create Feature modules, but reusing fields (or more exactly: reusing field storage) across different node types saved me a lot of work later in Views and themeing.
I always use "Mark all config as required" and "Allow conflicts", and afterwards move the generated config from config/install to config/optional. I guess this is not the standard Features workflow, but I do this for 2 reasons:

It prevents clashes between Features and existing core config/sync. If an optional config setting already exists, it will silently be ignored instead of stopping with errors.
I found it way easier to manage larger but meaningful modules with some duplicated config, than to split everything into super-small modules with a dependency nightmare.

I'm not quite certain if my experiences are useful to you though, because we are a small company with me being the sole developer. We are trying to reuse Features across different projects, not to avoid collisions on the same project.


How to create a log in and register link in the secondary menu

Create a new entry in the secondary menu and point it to /user or /?q=user.


Preprocess custom CCK fields and print image URL in TPL file

Try the below:

$vars['image'] = $node->field_uppdrag_logo[0]['value'];


Nightly truncating all cache_* tables? Good or bad?

Cron job to truncate the tables might cause some metadata locks due to the TRUNCATE command being a DDL statement; depends on how busy your server is. What APDQC does is a table rename swap and then truncate; if you did something similar then you should be ok. APDQC will also use gzip to make the table sizes smaller; something that would be a benefit in your case. Without compression our DB cache tables would take about 50GB, they now take about 12gb.


Views HTML List displays empty random regions

Not able to access your URL. May be it is because of width of the item. Adjust the width of the items, it will display properly for you.


How to update record programmatically with ECK?

After thousands of research, according to the page Creating and Modifying Entities this is the way to update an entity :

$entity = entity_load_single('entity_name', $entity_id);
$entity->title = 'new name';
$entity->save();

This will load the entity 'entity_name' with the id 'entity_id', then the title will be replace by 'new name'.

I hope its help.


Print CCK field "A" if CCK field "B" has a value of "Z"

THIMK! Test the value of Field B before printing Field A.

<?php
if(isset($node->field_field_b['und'][0]['value']) && ($node->field_field_b['und'][0]['value'] == 'blue')) {
    if(isset($node->field_field_a['und'][0]['value'])) {
          print $node->field_field_a['und'][0]['value'];
    }
  }
 ?>


could i overwrite the array value by the preprocess function?

You could only overwrite them if they are accessible within template_preprocess_node(). For example, if the module adds $links to the $vars (or $variables) array, or to the $node object, in its own implementation of preprocess_node(), you could simply do:
$vars['links'][0]['text'] = "i have changed this text";
If the module does not add $links to the $vars/$variables array or to the node object, you would not be able to change it from mytheme_preprocess_node().


I haven't used it before but the Register with Picture module sounds like it would do the trick:

  This module exposes the 'upload picture' element to the registration form. It also gives you the ability to set a picture as required in the module settings.

There are stable versions for both Drupal 6 and Drupal 7. It also has 1600+ installs, is actively maintained and has very few issues in the queue, so I'm assuming it should work great.


How to concatenate all token values of a list in a single field within a Rules loop?

If what you're looking for is not available, then just make it available, which is "a different way to concatenate all of the URLs of each file" (as in your question). Read on for more details ...

Have a look at this example of a Rule (in Rules export format), which is a variation of what you're asking for:

{ "rules_show_list_of_fields" : {
    "LABEL" : "Show list of fields",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_insert" : [], "node_update" : [] },
    "IF" : [
      { "node_is_of_type" : { "node" : [ "node" ], "type" : { "value" : { "article" : "article" } } } }
    ],
    "DO" : [
      { "variable_add" : {
          "USING" : { "type" : "text", "value" : "StartOfList-" },
          "PROVIDE" : { "variable_added" : { "email_list" : "List of eMail IDs" } }
        }
      },
      { "LOOP" : {
          "USING" : { "list" : [ "node:field-email-addresses" ] },
          "ITEM" : { "current_email" : "Current eMail" },
          "DO" : [
            { "data_set" : {
                "data" : [ "email-list" ],
                "value" : "[email-list:value][current-email:value]-"
              }
            }
          ]
        }
      },
      { "data_set" : { "data" : [ "email-list" ], "value" : "[email-list:value]EndOfList" } },
      { "drupal_message" : { "message" : "The value of the email_list variable is: [email-list:value]." } }
    ]
  }
}

Here is a summary of what this rule does:

Add a new variable email_list.
Init the email_list value with some prefix.
For each item within the loop, append the value of that item, followed by a separator character.
Add a suffix to the email_list value.

In my case I'm using a multi value text field with machine name field_email_addresses, which contains eMail Ids, and just want to dispay a Status message with a concatenation of those eMail IDs, separated by a "-", and with a prefix (=StartOfList) / suffix (=EndOfList). And I also use Rules Events "Update existing node".

Replace the machine name of my list field to your list field, and replace all 'eMail' by 'file' and you should be able to import this rule in your own site (if you have the Rules UI enabled).

Not sure if you want the prefix or suffix, and/or the separator character (="-"). Adapt or remove any of these to fit your needs.

Voilà ...

Demo

Here is how the Status message looks like after you create a new node, or update an existing node (of type Article):

  The value of the email_list variable is: StartOfList-user2@example.com-user4@example.com-EndOfList.


Blocks are rendered in hook_preprocess_page. At that time, all implementations of hook_preprocess_node have already been executed, so you cannot influence how the node is displayed (apart from messing with the HTML in $vars['content']).

If you use Drupal's Form API to implement the select list and the submit button, Drupal will redirect you after submitting the form, so you do not need to reload the page manually. See Post/Redirect/Get for why it is generally a good idea to redirect after a HTTP Post.


How can I limit the taxonomy terms of certain nodes?

Write a module that implements hook_node_validate. The implementation of that hook can check the integrity of the term associations by calling taxonomy_select_nodes and report any inconsistencies by calling form_set_error.

Beware of the limitations of taxonomy_select_nodes:

  This function requires taxonomy module to be maintaining its own tables, and will return an empty array if it is not. If using other field storage methods alternatives methods for listing terms will need to be used.


"CSRF validation failed" when try to send POST request in custom module

You need to get a CSRF token before making your POST call.

function getCsrfToken(callback) {
  jQuery
    .get(Drupal.url('rest/session/token'))
    .done(function (data) {
      var csrfToken = data;
      callback(csrfToken);
    });
}

and use this in your ajax call as a new header:

  jQuery.ajax({
    url: 'http://example.com/entity/node?_format=hal_json',
    method: 'POST',
    headers: {
      'Content-Type': 'application/hal+json',
      'X-CSRF-Token': csrfToken
    },
    data: JSON.stringify(node),
    success: function (node) {
      console.log(node);
    }
  });

https://www.drupal.org/docs/8/core/modules/rest/3-post-for-creating-content-entities


Recursive multilevel taxonomy feeds Drupal 7

You can solve this by double running an import with only one master CSV and using the Skip hash check & Update existing terms settings within your importer.

Feeds tracks each imported item in the feeds_item table. As entries are imported, it adds the imported guid to the table and stores hashed value of the imported row within hash. This hash value is checked upon reprocessing so Feeds can skip any unnecessary updating (if the source data hasn't changed it doesn't need reprocessing).

If Skip hash check is enabled with Update existing terms set to Update existing terms, this forces Feeds to update regardless. For your purposes, the first import run will ensure that each feed item is in the feeds_item table. On the second import run, the hierarchy integrity will be restored as each pguid will have a valid guid reference in the feeds_item table.


Proper way to get the base path when including an image from a module?

Drupal core uses file_create_url() for internal images like this (eg, the default favicon.ico handling in includes/theme.inc).

This ensures that hook_file_url_alter() gets called (the CDN module does this), that the basepath gets set, and that everything is escaped properly.

So, I would use

$path = drupal_get_path('module', 'mymodle');
$url = file_create_url($path . '/images/some.jpg');


How to add "Add to Cart" button using Ubercart?

According to this answer:

  ... The content type has to be an Ubercart product content type, then the
  add-to-cart button will automatically show up on that content type
  along with all the other fields that are necessary for an Ubercart
  product like price, sku, etc.

  To make a content type an Ubercart product content type, edit the
  content type at /admin/structure/types/manage/{name of content type},
  choose the "Ubercart product settings" tab in the lower left of the
  page, select "Content type is a product", then save the content type.


If you're using Views 3:

While I don't know how to exactly do what you want purely with Views (or even if it's possible), I can suggest you a module called Display Suite which can work with Views. You can define different display modes for nodes first, and then go to Views and choose "Node Display" type of output, and define in the settings which article should be displayed with which display, for example First 3 nodes in the list should use "Teaser with Image" display, next 3 would use "Teaser without Image" display, and then the next 6 would use a normal "Teaser" display. Then you can use CSS to define the columns for the last 6. Doing it this way you eliminate having the need to use Attachments, so all your results come from 1 display. Pagers then should work normally. I cannot guarantee you this will work 100% as I haven't used this module by myself, but I've seen a colleague implement something like this before, and he also had problems with using Pagers. I'm not sure if this functionality is compatible with Views 2 as it's been a long time since I used Views 2. Good luck.


You can use https://www.drupal.org/project/viewfield to reference views and even pass arguments.


You need to add a Contextual Filter field w/c would be the Content: Nid
In contextual filter Content: Nid configuration, under WHEN THE FILTER VALUE IS NOT IN THE URL, use Content ID from URL for the Type.
In contextual filter Content: Nid configuration, scroll down and toggle open the More fieldset and check Exclude


You can make your own login form (or alter default login form, i think) with two submit buttons calling different callback functions:

function xxx_login_form($form, &$state) {

  // .. usename and password fields here

  $form['submit_update'] = array(
    '#type' => 'submit',
    '#value' => t('Update'),
    '#submit' => array('xxx_login_submit_update'),
  );

  $form['submit_no'] = array(
    '#type' => 'submit',
    '#value' => t('No'),
    '#submit' => array('xxx_login_submit_no'),
  );

  return $form;

}

function xxx_login_submit_update($form, &$state) {

      if(user_authenticate($state['values']['username'], $state['values']['password'])) {
        // log in user
        $user_obj = user_load_by_name($username);
        $form_state = array();
        $form_state['uid'] = $user_obj->uid;
        user_login_submit(array(), $form_state);

        // .. do some updates

        return true;
      } else {
        return false;
      }

}

function xxx_login_submit_no($form, &$state) {

   // do what you need but do not log user in.

}

You can of course add custom validate functions, messages or what you need. If you want redirect to another page after button is pressed, you can use

'#action' => 'some/page/1'

for the buttons.


How to check in a rules condition if an image field has value?

Make sure the field you are trying to "test" (for its value), is available at the time Rules tries to do so.

That's why I always add a entity_has_field condition (and put it as the first condition) which looks something as in this example (part of a rules export of some rule):

"IF" : [
  { "entity_has_field" : { "entity" : [ "account" ], "field" : "field_next_appointement" } }
],

In my sample here, it is related to entity account, and my field's machine name is field_next_appointement.

So retry your rule with the Data Value is Empty condition, but put such entity_has_field condition in front of it. So that in the end your rule has 2 conditions (no PHP coding at all involved), something like so:

entity has field ...
NOT Data Value is Empty ...

Below is a (simple) rule from my training class examples. It'll display a message like "Watch, this is ONLY 100 EUR !!!!" for a node which has a field_article_price field, whereas that price is exactly 100 EUR.

{ "rules_this_article_is_for_sale" : {
    "LABEL" : "This article is for sale",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_view" : [] },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_article_price" } },
      { "data_is" : { "data" : [ "node:field-article-price" ], "value" : "100" } }
    ],
    "DO" : [
      { "drupal_message" : { "message" : "Watch, this is ONLY 100 EUR !!!!", "type" : "warning" } }
    ]
  }
}

Looking at your (updated) question (now including your current rule), I think you should try to work step-by-step to investigate which part of your rule "doesn't" work. If I was in your shoes, I'd experiment with these variations (only for debugging):

Replace the ACTION with just a drupal_message:

if you get a message then, your problem is within ACTION. Todo: fix the Action.
if not your problem is in the EVENT of CONDITION(s). Todo: go to item 2.

Remove all CONDITION(s):

if you get a message then, your problem is within CONDITION(s). Todo: fix the CONDITION(s).
if not your problem is in the EVENT. Todo: go to item 3.

Review the EVENT: if the event you're trying to use to make the Rule work does not actually happen, or if you're "too late", then of course that needs to be fixed/reviewed. In my experience, there are quite a few Rules scenarios where you should use "When Drupal is initializing". My (personal favorite) sample of that is about "before content is going to be viewed" ...

I realize the above 3 steps do not actually "answer" your question, but they may help to debug what's actually the problem.


How to build a simple data comparison rule?

OK, I would then recommend Business Rules to build that kind of data comparison rule.

1- Create a first Variable "Value from Entity field" to store the original value of your field.

2- Create a second Variable "Value from Entity field" to store the current value of your field (i.e. the saved value after updating node)

3- Create an Action "Send an email"

4- Create a Condition "Variable data comparison" to compare the two variables you built in 1 and 2. Available variables are listed, use {{your_variable_name}}. Use the right operator, here I needed != (different from).

5- Inside your Condition, add the Action "Send an email" (in section "Items to execute if condition succeed")

6- Create a Rule based on an event "After updating Entity", define the context (entity type and bundle, here content and content type) and insert the Condition you built in 4. You should see a nice flowchart with your Rule label (white), then your Condition label (blue) and if YES, your Action label (green).

That's a start.

Hope this helps.


Apache Solr 4.6.0 installation and compatibility with Drupal7

You aren't alone I had to scour the internet and read several articles before I truly understand all of this. I tried about three different methods until I finally got it right!

If you are using Debian/Ubuntu (with Tomcat7) it's even easier then most outline. I preferred this over Lullabot since when you install it through Ubuntu it's actually a service and less fiddling :)

Install Java

apt-get install java7-jdk

Install Tomcat

apt-get install tomcat7 tomcat7-admin

Once this is done you can get to http://localhost:8080 and see that's it is all running properly.

Note: It's recommended to push the port to another one since 8080 is pretty common. If you want to do that use this code for that!

sudo sed -i s/8080/8983/g /var/lib/tomcat7/conf/server.xml

Configure Tomcat

You will want to actually create a users account for Tomcat so that other people have to log into the admin (it keeps it safer).

nano /var/lib/tomcat7/conf/tomcat-users.xml
Then add these xml arguments between the <tomcat-users> tags

<role rolename="manager-gui"/>
 <role rolename="admin-gui"/>
 <user username="!!somename!!" password="!!somepassword!!" roles="manager-gui,admin-gui"/>
Now you can restart tomcat again and view the admin page at  http://localhost:8983/manager/html

service tomcat7 restart

Install Solr

Download the latest ApacheSolr here (When I wrote this I got it working with 4.7)
Extract the files into a directory

Copy Solr library files

Next we want to add the library files to Tomcat library directory. Note: You can also use symlinks if you prefer, but for the purpose of understand where everything goes I chose to place it directly in the directories

cp ~/solr-4.x.x/example/lib/ext/* /usr/share/tomcat7/lib/

It may be a good idea to also copy the java libraries from solr/dist/solrrj-lib/*

cp ~/solr-4.x.x/dist/solrj-lib/* /usr/local/tomcat7/lib/

Copy Solr WAR app file

cp ~/solr-4.x.x/dist/solr-4.x.x.war /var/lib/tomcat7/webapps/solr.war

Setup Drupal ApacheSolr core

We first need to copy over the sample configuration files from ApacheSolr.

mkdir -p /var/lib/tomcat7/solr
cp -r ~/solr-4.x.x/example/solr/collection1/conf /var/lib/tomcat7/solr/
Next grab the latest version of the apachesolr module https://drupal.org/project/apachesolr and unzip it

tar xvf apachesolr-*.tar.gz
Syncronize the apachesolr configuration files (for Drupal) with your solr configuration

rsync -av apachesolr/solr-conf/solr-4.x/ /var/lib/tomcat7/solr/conf/

Note: I found an error in which ApacheSolr refused to start due to duplicate errors. I reported that here so you might want to look at the solution here as at the time of writing this I could not get it running without that!

Create a core definition file to tell Apache Solr which cores are available.

nano /var/lib/tomcat7/solr/solr.xml
Paste the following code inside that file

<?xml version="1.0" encoding="UTF-8" ?>
 <solr persistent="false">
   <cores adminPath="/admin/cores">
     <core name="!!yourcorename!!" instanceDir="!!yourcoredir!!" />
    </cores>
  </solr>

Create Drupal core directory

This will create a new core in your system with that name. If you wish to add more you simply can repeat this step as well as the one above.

mkdir /var/lib/tomcat7/solr/!!yourcoredir!!
cp -r /var/lib/tomcat7/solr/conf /var/lib/tomcat7/solr/!!yourcoredir!!/

Let's Make It Live

Your at the last stretch!! Let's put tomcat7 to sleep

service tomcat7 stop
Now change the permissions on the tomcat directory

chown -R tomcat7:tomcat7 /var/lib/tomcat7
Start it back up

service tomcat7 start

It's Live

You should be able to go to http://localhost:8983/solr and see a new core instance available! Now you can go ahead and configure drupal to point to that.

Note: Your new core is located at http://localhost:8983/solr/!!yourcorename!! to be used in the Drupal ApacheSolr module.

Credit and props goes out to Pacoup


Replace last item in a Views grid of images

But is there no way to actually get it into the grid in html from the
  Views UI?

As I can see thare is no way for that in views UI.

But here are possible custom solutions:

Solution1

Add "more link" in PAGER section. Than specify link in 'Link
display' section under ADVANCED.
Style your link with css

Solution2
Add new views row in [hook_views_pre_render][1]

Solution3
Add new views row in custon views template


Which is the better module for shopping cart?

From the sounds of it, you actually want a whole e-commerce system, not just a shopping cart.

Ubercart will do this for you, but the general trend now is to go with Drupal Commerce (project page | Commerce homepage).

Both modules will allow for shopping carts, as well as integration with a variety of payment service providers.  I'd personally go with Drupal Commerce.  It seems a little more difficult than Ubecart at first glance, but once you get over that you'll realise it is much more flexible/powerful.

Try using the Commerce Quickstart installation profile to get yourself familiar/started with it.

There are a lot of good videos for Commerce as well such as Selling Content with Drupal Commerce using Content Access and Roles from the Commerce Guys.

Lastly, there is a blog post here that weighs up the pros and cons of each system (although it is from 2011)

Edit:

You might find the getting started guide useful also.


How to get a list of all displays of every view?

Please find the following drush one-liner to list all the views including all display names:

drush eval 'foreach (views_get_all_views() as $view) { foreach ($view->display as $display => $data) { print "$view->name: $display\n"; }; }'

Modify the code as required.


Is Drupal Commerce ready for the real world?

The payment gateway is the key. If your chosen payment gateway is available for Drupal Commerce, I would say yes, go ahead and use it.

Even if not, there are compelling reasons to develop or help to develop the payment gateway.

Drupal 7 is much more advanced, and will continue to be relevant for much longer. Drupal 6 will not be supported when Drupal 8 is released. Suppose Drupal 8 is released in 2 years (nobody knows at this stage but it's a reasonable estimate) and your site takes 6 months to launch. A Drupal 6 site would only have a viable life of 18 months. It's something worth considering!

We're building a reasonably complicated Drupal Commerce site right now and the elements like the order system, cart, checkout and things like entity types are all fairly concrete. It's also slick to use, and offers numerous advantages over Ubercart (products do not HAVE to be nodes, opening up new ways of selling things).


What is the best practice to exchange variables between page calls

You should never read the value of the $_GET param in a template file directly, that logic should be separated out into a process/preprocess function.

Other than that, no...there isn't really anywhere 'better' for page parameters to go. The alternatives are to use something session based, or to set something up to POST variables to the second page. Or use temporary database storage which seems like overkill for this.

Your use case sounds like the archetypal situation where URL parameters would be acceptable. For example, it's the same way Drupal core handles paging (the page parameter is added to URLs).

If you're worried about separating these pages up for SEO benefit, that's a different matter, and you should look at creating unique paths for each piece of content (provided of course that the page changes enough to not be seen as a duplicate with the URL parameter available).


How to iterate thru a webform checkbox results

I'm not sure this require a technical answer. We would need more informations about the template you're in.

Usually, when you experience this kind of difficulty to access or decorate data, it means you're at the wrong template level. Manually iterating on elements in a template is not the "Drupal Way".

The rendering engine will do it for you and provide a template name (suggestion, that you could see in the source code with the debug activated)

Check carefully the provided theme suggestions to choose the template in which the actual checkbox is rendered.

Override the template by using a more specific suggestion. Copy the code from the previously used template, you will have to the name and attributes of the checkbox element and it will be much easier to manage the display you want.


There is need to work with Rules module make such action, "send email", "change role".

The workbench module is very popular, but is for Drupal 7 only. can be achieved good results using the revisioning module, which has a release for Drupal 6.


Why won't my custom content field update on save/edit?

I figured out what my issue was. In order to force users to use the UI I set the input field as being disabled from my JS file.

 document.getElementById('edit-brand-header-config-und-0-value').disabled = true;

Apparently setting it to disabled prevents it from being stored even though I could add a value to it programmatically through JS.

Removing "disabled = true"


In the pager settings of your view select the wanted amount of items and then specify an offset by 1, so the first item won't be displayed.


Can I create a text field which is both a autocomplete taxonomy, and a freetagging field

That is how the autocomplete taxonomy widget works by default?

It provides autocompletion, but users can also add their own new tags.

Simply add a taxonomy field to your profile, select the Autocomplete Widget and you're good to go.


The taxonomy fact was just an example. I also need this for webforms, so it would be better to have a general solution for that then just for a single module since this problem will occure for every configuration that is stored below "Structure".

It got this fixed using: Admin Links Access Filter


Which table stores info about hook_update_N?

The schema version for the update hook is stored in the key_value table.

You can set it with the global function drupal_set_installed_schema_version($module, $version).

For example:

drupal_set_installed_schema_version('my_module', 8005);

If you want the check the schema version number:

$schema_version = drupal_get_installed_schema_version('my_module');


Is there any way to add the css class to tinymce inside wysiwyg editor

As you are using wysiwyg module with tinymce library. You should implement the alter function provided by wysiwyg module to add the editor settings.

For tinymce 4.x:

function MYMODULE_wysiwyg_editor_settings_alter(&$settings, $context) {
  if ($context['profile']->editor == 'tinymce') {
    $settings['link_class_list'] = array(
      "Class Example" => "class-example",
    );
  }
}

For tinymce 3.x:

function MYMODULE_wysiwyg_editor_settings_alter(&$settings, $context) {
  if ($context['profile']->editor == 'tinymce') {
    $settings['theme_advanced_styles'] = array(
      "Class Example" => "class-example",
    );
  }
}

References

documentation of tinymce 4.x
documentation of tinymce 3.x
API of wysiwyg


What happens when you delete a field from an existing Content Type?

When you delete any of the field of the content type then all the log of that field from the database is deleted.

eg. Suppose we create a field named test in the content type A then it creates 2 tables in the database ie field_data_test and field_revision_test.

So when you delete the field test then both the tables are also deleted from the database.


I think this is what the domain access module is for.


How do I properly add css to my feature?

You add the css file to the module.
Use drupal_add_css to include the css file in the .module, this could be done in hook_init and would look something like this:

module_name_init() {
  if (arg(0) == 'views_path') {
    drupal_add_css(drupal_get_path('module', 'module_name') . '/path_to.css');
  }
}


You need to add a field to the media entity, that acts as the base for a media provider module (such as images, files, remote videos, google docs, etc.). The various media provider modules dictate the field, that is needed to store and retrieve the essential information (and optionally some meta data)

E.g. for creating image media entity, you select "image" as media source (provider). Then add the image field to the entity, and select this field as base for media provider. Optionally the media provider can extract additional meta data (width, height, EXIF,...) from that field and map it to other fields of your media entity.

For a Youtube video (Video embed field), the base field is an URL field. For a File media entity, the base field is a file field. And so on.


You can create a block-view display with no content and then attach those attachment-view to the block-view display. This may be a possible hack if i understand you correctly.


How do I configure Apache and Varnish with both HTTP and HTTPS access and prevent mixed content error?

Drupal 8

Apply the following settings in site's settings.php file:

$settings['reverse_proxy'] = TRUE;
$settings['reverse_proxy_addresses'] = [@$_SERVER['REMOTE_ADDR']]

It should work for CDN where IP addresses are dynamic.

This is explained in the following comment:

 * In order for this setting to be used you must specify every possible
 * reverse proxy IP address in $settings['reverse_proxy_addresses'].
 * If a complete list of reverse proxies is not available in your
 * environment (for example, if you use a CDN) you may set the
 * $_SERVER['REMOTE_ADDR'] variable directly in settings.php.
 * Be aware, however, that it is likely that this would allow IP
 * address spoofing unless more advanced precautions are taken

Drupal 7

$conf['reverse_proxy'] = TRUE;
$conf['reverse_proxy_addresses'] = [@$_SERVER['REMOTE_ADDR']];

See also:

Setting reverse_proxy and reverse_proxy_addresses behind AWS ELBs.
Using a load balancer or reverse proxy


How to process an http request with a controller?

Ok, my problem was the serialization. To recover my node object in my function of POST, I should deserialize the json with the function:

 $data = \GuzzleHttp\json_decode( $request->getContent(), TRUE);
 $serializer = \Drupal::service('serializer');
 $node = $serializer->deserialize($data, \Drupal\node\Entity\Node::class, 'json');

 $new_node = Node::create(array(
   'type' => $node->bundle(),
   'title' => $node->title,
   'langcode' => $node->language()->getId(),
   'uid' => '1',
   'status' => 1,
   'body' => $node->get('body'),
 ));

 $new_node->save();

Now, I can manipulate my node like I want in my other website.


PDOException when saving node with AudioRecorderField

Looks like the problem was with the PHP upload limit. Seemed to be a computer problem because I always used short recording files when testing, while my client tested with a full recording.


Currently this is not possible. You can always build a view that contain only fields you need. Or select fields when configuring view's display.

Developers needed to choose between GUI on export and unattended processing. They choose automation capabilities, and for good reasons - large exports can take a long time, so it makes sense to trigger them at night using drush.

If you believe there should be such option, then you can fork project - it's opensource, GPL v2, so you have full right to do so. You can also file a feature request in module's issue queue, but personally I don't think it would be implemented by maintainers. If you will provide ready to use patches, then maybe.


Flexible addons for Solr to achieve sorting and filtering

Search API includes Views integration out of the box. Definitely you will need Facets Api. this combination is the best for Solr integration with Drupal. Here is a great screen-cast that might help.


How to remove Storage API without data loss

You'll probably need to manually update the files_managed database table and change the uri to use the public:// schema.


No need for $options['alias'] = TRUE, that will prevent alias lookup.

  If you provide an internal path and $options['alias'] is set to TRUE,
  the path is assumed already to be the correct path alias, and the
  alias is not looked up.

Use the node/$nid path and let Drupal find the correct alias.

If that doesn't work, you could try manually passing the $options['language'] parameter

  'language': An optional language object. If the path being linked to
  is internal to the site, $options['language'] is used to look up the
  alias for the URL. If $options['language'] is omitted, the global
  $language_url will be used.

https://api.drupal.org/api/drupal/includes%21common.inc/function/url/7


Should anyone be interested, updating to the latest core (7.69) seems to have restored the CKEditor functionality.


How do I pass the UID in URL to embedded View?

In an embedded view you typically use the "When the filter value is not available" option for the contextual filter to achieve this.

Select "provide default value" then choose "raw value from URL" and set the path component to be 1.

You should also set validation criteria and select what should happen when the value is missing or incorrect.


How to display additional fileds I've added to a page - the way I want them?

Hiding additional fields is easy, just notice Display Fields tab at the Manage Fields page for the specified content type (page in this case). There you can easily exclude additional fields from being automatically appended to the $content.

In order to show fields the way you want them use themename_preprocess_page hook and check $vars['node'] object for the particular fields.


How do I trigger an event when a button is clicked on a user profile?

Wow, this is a question with many solutions. Some stuff I can quickly think of:

Developers way:

create a custom module: https://www.drupal.org/developing/modules/7
implement hook_menu to create callbacks for your links
implement your logic in the callback functions defined for your entries in hook_menu.
"presentation layer". Depending on the structure of your website and your profiles:

a) Create a block with your links in it, references: block_example, link function

b) Implement a "pseudo field" on fieldable entities (e.g. user, profile2)

c) Use link function in your profile template file e.g. user-profile.tpl.php

extra points might be awarded if you use the link function and your hook menu implementation together with the ajax framework. example.

Site builders way (one way.. there are many):

create a flag
create a rule for flagging items
in that rule implement your logic
optional: undo the flagging (so the user can do this action again)

All of the mentioned solutions will probably require some logic for handling the access and display of that button as well.

(one) developer way, if this button appears on user/id:

<?php
global $user;
if (arg(0) == 'user' && arg(1) == $user->uid && null === arg(2) {
  print l('do something', 'yourcallballback/' . arg(1));
}

site builders way (for the example from above):

usually there's no additional access check required here, you can setup that flag to be global and only clickable once if you want to make sure that it's only available once. for the display part you probably really have to use code to only show that flag if the current user visits his own profile.


Drupal 7 - FAPI - Multistep form - with add another option

When you want to add a new set of values, you have to build the form in a different way - the fields that should be "multiplicated" have to be in an array.

so, your

$form['Name'] = array(
        '#title' => t('Name'),
        '#type' => 'textfield',

should instead look like this :

$form['step2'][$i]['Name'] = array( ...

where $i is set to zero in the begining and increased by the callback for your "add another" button. The "step2" fieldset is there just to help you distinguish the parts that are repeated from the others - its not necessary i guess.
The aformentioned examples module has nice examples how to acheive that even with ajax, so you dont have to reload the whole thing. Dont forget to set

$form['#tree'] = TRUE;

so that you can process the several sets of results.


htaccess 301 redirect everything except /admin

It depends on RewriteBase /.
I checked your code with this online tool and it was working fine.
Toggling comment for rewritebase line will help but other rules might get affected. Instead, modify your condition and remove the slash. It should work.

RewriteCond %{HTTP_HOST} ^www\.example\.com$ [NC]
RewriteCond %{REQUEST_URI} !^admin [NC]
RewriteRule ^(.*)$ http://newsite.com/$1 [R=301,L]


You can use token_replace() for that. As you're using a global token (no context required) it's very simple:

$markup = token_replace('
This is my test

[current-page:title]
');
$node->content['field_mytest']['#markup'] = $markup;


Template files do not work when in "Templates" directory

It turns out there were more .tpl.php files in a different directory that was not obvious, thus overriding the templates I intended to use.


How do I override the "This image has been removed" message?

First, you need to know which input text filter you have enabled where the images are not showing. For the sake of this answer, let's say it's the "Basic HTML" input filter.

Go to the configuration for this input filter, such as /admin/config/content/formats/manage/basic_html

Scroll down to "Enabled Filters" and look for:

"Restrict images to this site"
Disallows usage of  tag sources that are not hosted on this site by replacing them with a placeholder image.

If you can not view externally-hosted images, it is likely this filter is enabled. Simply disable this filter.


I cant see what is in your "...which basically add HREFLANG attribute like this" and "But I want to add language as well as region like this."

I bet you want to replace, let's say, "en" to "en-GB" right? If so, you need to alter Drupal language ISO. Current is ISO 639, language+region is ISO 3166-1 alpha 2.

BTW for your question, you need something like this to locate the hreflang:

function YOUR_THEME_OR_MODULE_NAME_html_head_alter(&$head_elements) {
  drupal_set_message('<pre>' . print_r($head_elements,1) . '</pre>');
}

Clear cache and reload the page.

UPDATE

An easier way is by adding a custom language. E.g. visit admin/config/regional/language/add

Expand Custom language fieldset.
Enter your desired ISO 3166-1 alpha 2 language code to language code & path prefix language code.
Fill the rest (language name in English, native language name & Direction) as usual.


How to get parent paragraph from a child block preprocess

The linked answer was using this inside a node hook.
In case of hook_preprocess_block(&$variables) you can try $variables['elements']['content']['#block_content'] instead. This should return the content entity, similar to the linked answer.
Notice: $whateverEntity->_referringItem is not cache-safe, so if you are referencing the same block on multiple paragraphs, this will not work reliably.


Not able to log in to Drupal site as other user

Once I was able to get in touch with my other site admin and she was able to log in with the same credentials I knew the problem was local.  I had tried different browsers.  I flushed my DNS and rebooted my computer and was able to log in.


How to use default taxonomy with a mixture of terms and content?

You probably want to replace the taxonomy/term/## page with a page view of content in that term and "attach" another view to the header that lists the child "taxonomy terms".

That way you them alongside your content as a browsable tree or as a list of "folders" above the content in that folder.


Show profile2 fields on users page through panels

It looks like you are doing it ok, but there is an issue related that you can check at https://www.drupal.org/node/1011370#comment-9332247.

If you update to the latest dev version of profile2, it should work, and you could select the profile context and the profile type.


As i understood you almost cant use common tables on multi-site installation - i`ve been checking them one by one. First i configured all of sites - only the main site (from which tables were shared) could switch languages and translate nodes. On the others there were no switcher showing and translated nodes were not linking.

Maybe you can some, but still you got to have everything identical (starting from content types and endind with nodes)

Maybe i am wrong.


How to set a different theme for editing one's account

If you go to admin/settings/admin you can select your admin theme as well as using it for content editing.


Issues importing nodes containing taxonomy terms with &/& using feeds

I am using Feeds XPath Parser to import an XML file that contains a couple of fields that I then map to terms in two different vocabularies. It looks like the parser removes ampersands before Feeds Tamper kicks in. This leaves the terms with three spaces where previously there was a space, an ampersand and another space.

My solution - was to create a Find Replace tamper plugin that looks for three spaces in the imported text and replaces the three spaces with a space, an ampersand and another space.

Not pretty, but it works. Of course, this solution won't work if there are other special characters in the feed that would also be removed. In that case, I'd create multiple Find Replace plugins that look for the specific text strings, such as "Canada   Alaska" and replacing them with the corrected string, i.e. "Canada & Alaska". Even less pretty but ...


taxonomy-term--vocabulary.tpl.php still shows tagged content

As I now think I know what you want, here's what I'd do: use Page Manager to override the default display, then add the rendered Entity display for Taxonomy. That should then pull in your custom template,


Features workflow issue with deleting a field

The correct way to remove Features-created content is via hook_update_N (which should be implemented in the file your_module.install).

The main idea with Features is to manage configuration with code. Using hook_update_N is consistent with that, since the field deletion is in code (which can be managed with version control) — whereas the equivalent command drush field-delete field is not being called from managed code; it's a separate command-line step you need to perform (and to remember to perform).


How can I insert Javascript right before the body in my custom theme?

Not sure this helps but I had a similar problem before. I solved it by using the jQuery syntax instead of the $, like so:

jQuery(window).load(function() {
    jQuery('#a a').css({'background-position','-20px 55px'});
    // and so on
});

You could load your js file by calling the drupal_add_js() in the THEME_preprocess_page() hook in your template.php file.


so for what it's worth using the default/settings.php as the master and then having each of the sites do a PHP include (as @Alan mentions) does work well!  (I know this is an old question but I am working through multisite issues with Drupal 8 (8.6.13) and have come across this very thing...)

a couple of caveats:

1) I am managing the multisite installation and config manually so am creating my own settings.php files, not using drush site-install which will auto-generate the settings.php

2) you must do the include at the top of the site's settings.php and ensure that you are overriding only what you need to. (...or the inverse, that you are okay using the config in the default settings file)

I have this at the top of the settings.php for each site:

$default_path = "sites/default";
include $app_root . '/' . $default_path . '/settings.php';

and then override the database settings - setting the prefix etc:

$databases['default']['default'] = array (
  'database' => 'this_is_the_database',
  'username' => 'username',
  'password' => 'password',
  'prefix' => array(
    'default'         => 'site1_prefix_',
  ... etc

and the site name:

$config['system.site']['name'] = 'Site 1 Name will override default site name';

of course YMMV

tl;dr - yes you can, but be aware of the order in which your PHP will execute and apply the settings


Drupal 7: Article with Multiple Image Thumbnails Embedded in it

With Colorbox and Insert, it should be a breeze.


Display menu Shopping cart (# items) and total amount

You can use https://www.drupal.org/project/menu_badges to accomplish that.

  Once enabled, go to Administration > Structure > Menus, and click
  "list links" next to the menu containing the target item. Click "edit"
  next to the item and select the badge to display with the Display Menu
  Badge select box.

Or you can set the parent menu item of the Shopping cart (# items) link provided by the cart module to your menu. This menu item is provided by commerce and by default can be found in the navigation menu at admin/structure/menu/manage/navigation


How to add a css file to the admin theme from a front subtheme?

There are a few options to accomplish this.

If your admin theme has a html.tpl.php you could manually add it in the head using <link type="text/css" rel="stylesheet" href="linktoyourcssfile">

Although, know that, when you update your admin theme, the html.tpl.php file probably will be overwritten so you will need to add it every time again.

Another solution is to install the Add To Head module and add the above line to the head without having the trouble it will be overwritten the next time you update the theme.

It's up to you to see which solution fits you best.


How Do I get specific fields value in Twig?

In a block twig you can access a field value like this:

{{ content['#block_content'].field_myfield.value }}

This is the database value of the field.

Most times you want to render a field:

{{ content.field_myfield }}

This will display the field as it is configured in the view mode.


So, I will create my own module to do that. The module will offer a new field can be created on any type of content, and will accept search criterias, the number to display, and so a search result will appear in the node.


How can we retain dropdown list value, when we select the option?

You can set the default values as follows,

$form['choice'] = array(
    '#type' => 'select',
    '#options' => $options,
    '#title' => t('Select your layout'),
    '#default_value' => variable_get('choice', $form_state['choice']['type']
)
);

provided you get the submitted values in the variable $form_state['choice']['type'] post submit action.
And the variable name should match the form field name "choice"

Hope this works for you!


"Drupal calls should be avoided in classes, use dependency injection instead"

Take the BlockLibraryController class as example; it extends the same class as your controller.

You define:

A static and public create() method that gets the values from the dependency container, and creates a new object of your class
A class constructor that saves the values passed from the previous method in object properties
A set of object properties to save the values passed in the class constructor

In your case, the code would be similar to the following one.

class MyModuleController extends ControllerBase {
  /**
   * The path alias manager.
   *
   * @var \Drupal\Core\Path\AliasManagerInterface
   */
  protected aliasManager;

  /**
   * Constructs a MyModuleController object.
   *
   * @param \Drupal\Core\Path\AliasManagerInterface $alias_manager
   *   The path alias manager.
   */
  public function __construct(AliasManagerInterface $alias_manager) {
    $this->aliasManager = $alias_manager;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('path.alias_manager')
    );
  }

  /**
   * {@inheritdoc}
   */
  public function getUserContent() {
    $alias = $this->aliasManager->getPathByAlias($_POST['url']);
    // Omissis.
  }

}

Don't forget to put use \Drupal\Core\Path\AliasManagerInterface; on the top of the file containing the code you are showing.

As side note, the code you use to render the view is wrong: You don't need to use drupal_render() because views_embed_view() already returns a renderable array.
Then, the render array you are returning is probably not giving the output you expect. #name is probably not going to be used from Drupal, and #markup filters the markup you are passing to it, as described on Render API overview.

  #markup: Specifies that the array provides HTML markup directly. Unless the markup is very simple, such as an explanation in a paragraph tag, it is normally preferable to use #theme or #type instead, so that the theme can customize the markup. Note that the value is passed through \Drupal\Component\Utility\Xss::filterAdmin(), which strips known XSS vectors while allowing a permissive list of HTML tags that are not XSS vectors. (I.e, <script> and <style> are not allowed.) See \Drupal\Component\Utility\Xss::$adminTags for the list of tags that will be allowed. If your markup needs any of the tags that are not in this whitelist, then you can implement a theme hook and template file and/or an asset library. Alternatively, you can use the render array key #allowed_tags to alter which tags are filtered.
  #allowed_tags: If #markup is supplied this can be used to change which tags are using to filter the markup. The value should be an array of tags that Xss::filter() would accept. If #plain_text is set this value is ignored.


Need "carat" for currently active Superfish menu item

Your best bet would be to just use CSS.  You can create that effect using absolutely positioned pseudo elements with some border tricks.  For example:

.sf-menu li {
  position: relative;
}

.sf-hover:after,
.active-trail:after {
  content: "";
  display: block;
  position: absolute;
  width: 100%;
  height: 20px;
  border-left: 20px solid transparent;
  border-right: 20px solid transparent;
  border-top: 20px solid #369;
}


Link tags in template file auto closing.

The problem here was that there where links in the content being outputted.  Once I changed that the links stopped auto closing.


How to alter standard.front_page in module links YML file?

I usually use this the hook_menu_links_discovered_alter() in this way:

/**
 * Implements hook_menu_links_discovered_alter().
 */
function YOUR-MODULE-NAME_menu_links_discovered_alter(&$links) {
   // Changing the title.
   $links['standard.front_page']['title'] = 'Hi';
   // Changing the route.
   $links['standard.front_page']['route_name'] = 'block.admin_display';
}

But it seems that there are another ways in How to update a menu link created with MenuLinkContent::create()? and How do I programmatically update or delete menu items?


This is very common problem. What's your module weight? You can find the value in the table system. Try to change it to something more "heavier".

update DATABASE_NAME.system set weight = '99' WHERE name = "MODULE_NAME";

Standard approach hot to set a modude weight is to declare it in MODULE_NAME.install file:

/**
 * Implements hook_enable()
 */
function MODULE_NAME_enable() {
    db_update('system')
    ->fields(array('weight' => 99))
    ->condition('type', 'module')
    ->condition('name', 'MODULE_NAME')
    ->execute();
}


It could sound a stupid question, but have you enabled your module?
Have you launched the uninstall procedure?


Normally the SMS gateway will ping a URL on your site with the relevant details from the SMS, e.g appended as a GET querystring.

I've done this before with hook_menu and a custom callback to listen for the SMS details.

/**
 * Implements hook_menu
 */
function MYMODULE_menu(){
  $items = array();
  $items['api/sms'] = array(
    'title' => 'SMS listener',
    'page callback' => 'mymodule_sms_incoming_process',
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  );

  return $items;

}

/**
 * SMS listener
 * Processing incoming SMS messages
 */
function mymodule_sms_incoming_process(){
  /* Do stuff with SMS parameters
   * Make sure to sanitize any $_GET vars with filter_xss etc..
   */
  if (!isset($_GET['code']) { return FALSE }
}


Where do I set anonymous checkout without users hit the login page?

You aren't just using Drupal Commerce, are you? It sounds like you're using Commerce Kickstart or Drupal Commerce with the Commerce Checkout Redirect module enabled. That's what's responsible for the behavior you're describing. Just disable it and enable the "Access checkout" permission that David Thomas pointed to.


How to handle ajax wrapper id for list of similar ajax forms?

You can use drupal_html_id() which:

  Prepares a string for use as a valid HTML ID and guarantees uniqueness.

e.g.

function my_form($form, &$form_state) {
  $id_string = 'my-element-id';
  $unique_id = drupal_html_id($id_string);

  $form['element'] = array(
    '#type' => 'select',
    '#options' => $options,
    '#ajax' => array(
      'wrapper' => $unique_id,
      // ...
    )
  );

  $form['output'] = array(
    '#prefix' => '
',
    '#suffix' => '
',
    '#markup' => 'Some markup'
  );
}

That should guarantee that the AJAX will work no matter how many different instances of the same form you create.


Views table aggregation with counts per value of a field

Views_merge_rows module will save your day! Assuming that the States field is a list field.

1) In your aggregation enabled views with table display add a User:Name (Group results together), a States field (COUNT, Excluded from display) and again a States field (Group results together, Rewrite Results > Rewrite the output of this field: [field_states]  ([field_states_1])).

So you will get a list of users with states but with one row per node. Here is a screenshot:

2) Then, enable the views_merge_rows module. In you Merge rows settings do this:

So you get what you want!


How to view content from admin theme (Seven), when logged in as admin

Drupal doesn't treat Content/Node view page as admin pages even after enabling "Use the administration theme when editing or creating content" setting on "Admin => Appearance" Page. This is just a setting allowed by Drupal Core. Node module uses this setting and alter Content/Note edit, delete, revision, etc. page URLs so Drupal can treat these path as Admin path.

You'll have to alter route defined by Core's Node module. You can do this by implementing alterRoutes() and tell Drupal to treat Content View page as admin URLs. Check example below:

namespace Drupal\example\Routing;

use Drupal\Core\Routing\RouteSubscriberBase;
use Symfony\Component\Routing\RouteCollection;

/**
 * Listens to the dynamic route events.
 */
class RouteSubscriber extends RouteSubscriberBase {

  /**
   * {@inheritdoc}
   */
  public function alterRoutes(RouteCollection $collection) {
    if ($route = $collection->get('entity.node.canonical')) {
      // Node module has option to define all path as admin path,
      // where path has "_node_operation_route" option set to TRUE.
      $route->setOption('_node_operation_route', TRUE);
      // Below line define path as admin path.
      // $route->setOption('_admin_route', TRUE);
    }
  }

}

If Use the administration theme when editing or creating content setting is enabled then, the Node module checks if any path has _node_operation_route option set to TRUE. If yes, it alters the path and set _admin_route option to TRUE so the path will be treated as an admin path (and then you will see it as in an admin theme, which is in this case, Seven).

If this doesn't work you can specifically set _admin_route option to TRUE for Content/Node View (entity.node.canonical) page programatically (check commented code).


I just tried such a Views configuration:

Nodes with a Date field, with multiple dates
Some nodes have dates only in the past, some only in the future, some in both.
Configured a Views page with a simple date filter, when value is greater than now

Views filters:

And Views filters with end-date also works:

End result:

It seems to work out of the box, with the simplest setting for me.
Regarding the delta, this is simply an index number for the value in a multiple value field, its position in the list.


How do I use rules scheduler to disable and enable a commerce product entity based on certain date fields?

First create a Rules component for setting the status of a product.

Go to Configuration -> Workflow -> Rules -> Components -> Add new component.
Create an Action set.
Give the component a suitable name, such as Set product status.
Create a parameter of type Commerce Product, label Product, machine name product; and another of type Truth value, label Status, machine name status.
Add action: Set a data value
For Data, use the Data selector to select the product parameter's status (product:status).
For Value, use the Data selector to to select the status parameter (status).
Save

You now have a component that can be scheduled. Next you need to trigger the creation of the scheduled action. I'm going to describe the process for enabling the product; you should be able to create another rule for disabling easily enough following the same method.

Go to Configuration -> Workflow -> Rules -> Add new rule
Choose the triggers After saving a new commerce product and After updating an existing commerce product.
Add the condition Entity has field.
For Entity, use the Data selector to choose commerce-product as the entity.
For Field, use the dropdown to select your start date field.
Add condition Data value is empty.
For Data to check, use the Data selector to choose the start date field.
Check the Negate checkbox (we only want to proceed if the field is not empty)
Add another condition Data comparison and select the start date field is greater than site:current-date
Add an action Schedule component evaluation.
For Component, choose the component you created earlier.
For Scheduled evaluation date, use the Data selector to get the start date.
For Identifier, choose something like Enable product [commerce-product:product-id]
For Status check the box.
For Product use the Data selector to choose commerce-product.

Then in order to remove a scheduled action if the date's removed from the field:

Follow steps 1-7 (but not 8!) immediately above to create a new rule.
Add an action Delete scheduled tasks.
For Component, choose the component you created earlier.
For Identifer, use the same string you used before.

And another rule to delete the scheduled action when the product's deleted would be good too.

I quickly gave that a go and it seems to work for me. Let me know if you have any problems.


Views php field or filter to a file or module

Found the answer here

Custom Views Field Handler
https://kalamuna.atlassian.net/wiki/display/KALA/Custom+Views+Field+Handler


The core issue you linked to has a patch that is apparently working, so it may be easier to patch with Composer instead of adding code to a custom module.
But, if you want to use the $form['#disable_inline_form_errors'] = TRUE;, this is what you can do:
First, create a custom module.  You need to follow the instructions on the first four pages:

Getting Started - Background & Prerequisites
Prepare a Module skeleton
Naming and placing your Drupal module
Let Drupal know about your module with an .info.yml file

Then, in the MYMODULE.module file, add this code:
/**
 * Customize the user login form.
 */
function MYMODULE_form_user_login_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  $form['#disable_inline_form_errors'] = TRUE;
}

What this code does is use hook_form_alter to target the user login form.  Lots of Drupal's form behaviors can be customized in this way.
You then need to go to the module administration page and enable your custom module.


If I understand the question right, the answer should be as simple as changing the block region :
go to:
https://www.example.com/admin/structure/block

and change the specified block region to footer or a region below "main content region".

You may check regions positioning by clicking on "Demonstrate block regions (Your-Theme-name)"


How can I get path aliases arguments from a URL in a template?

You can use function drupal_get_path_alias() to get the path alias, then strstr() to get the first component of the path, like so.

echo strstr(drupal_get_path_alias(), '/', TRUE);


An .htaccess can cause Internal Server Errors that are unrelated to PHP.  Bad directives in the file (eg, syntax errors) and using restricted directives (eg, doing an Option + that has been denied by the main Apache configuration) are two likely culprits.  I see the later very frequently with shared hosting.

The only way to really debug this is to find the Apache error log.  This varies from system to system.  On my CentOS machines, they are at

/var/logs/httpd/error_log

If this isn't your location, do a find error_log to track it down.  You may need to be root to read this file.


It is indeed a bad idea to have both modules altering the page title. A better approach I have found is to create a custom token, (which is really trivial with the provided example) and use it inside a metatag configuration for the desired node type. This way page_title could be uninstalled since it's no longer needed.


Fivestar and maybe Rate seem like the modules for your problem.

But you can also use a list field like you mention. You seem to have the need to restrict the voting to the author of the Review node, while creating it (on Node Edit, not to all visitors on Node View).

But there aren't any ETA for Drupal 8 versions of those modules. Maybe you can help with that while working on your project? Although Fivestar has much more features than you seem to need, it's a more flexible solution and may be more future-proof.

It all depends on when you need it working, and how much you can invest in getting the D8 versions up and running.

If you're a developer or can sponsor one you can work on the D8 versions to get the superb usability for your users.

If not you can use the List field and some Views magic to build the basic vote and stats structure.


Yes. Configure an apache virtual host for each site. They look something like this:

<VirtualHost *:80>
    DocumentRoot "/path/to/drupal/install"
    ServerName mysite.example.com
</VirtualHost>

<VirtualHost *:80>
    DocumentRoot "/path/to/drupal/install"
    ServerName myothersite.example.com
</VirtualHost>

Every virtual host in the multisite must be configured with the same DocumentRoot. The ServerName directive should match what you have used as the respective site's key in sites.php. Note that in this case *:80 signifies this virtual host listens on every IP of this server.


Programatically create field collection into Profile2 on new user creation

Fatal error: Call to a member function setHostEntity() on a non-object

The error means that you are trying to call setHostEntity() method on a non-object, in other words the $field_collection is not an object (NULL probably).

So please check one line before, which is:

$field_collection = entity_create('field_collection_item', array('field_name' => 'field_activities'));

So basically you are trying to load field_activities field collection, but it is not there, therefore your $field_collection is FALSE as per entity_create  API:

  Return value: A new instance of the entity type or FALSE if there is no information for the given entity type.

Therefore please make sure your field_activities exists as field collection (e.g. at /admin/structure/field-collections), or add additional failing scenario to your code, so when $field_collection is FALSE, do not execute further code.

For valid examples using field collections, check: Entity metadata wrappers page.


The simplest way is a cron job that calls drush @alias cr set for 24 hours. You can do that at the server level.


How to re-create a notifications 'inbox' similar to the one here at stackexchange?

You could use the Menu Badges module for such notifications, which you can add to any menu item and/or menu tab of your choice. In your case something like "New comments" seems like one, out of a few, appropriate menu item (or menu tab).

Here are some details about it (from its project page):

  Provides a method for adding iOS-style badges to menu items. (see screenshot)

  Adding Badges to Menus

  Once enabled, go to Administration > Structure > Menus, and click "list links" next to the menu containing the target item. Click "edit" next to the item and select the badge to display with the Display Menu Badge select box.

  Adding Badges to Tabs

  For adding badges to menu tabs, there is a tab under Administration > Structure > Menus called "Tab Menu Badges". Search for the menu router path of the tab you want to alter, then select a badge from the corresponding select box.

  Badge Types

  The module includes five example badges, and new badges can be created easily with Views. Modules can also supply their own badges with a hook implementation. See the README.txt file for details.

Because of how it integrates with the Views module, by using this integration you basically reduce the solution for any type of notification to something like "Just create an appropriate view of it".

However, there is a small caveat: if you really want the actual number (shown in the red circle) to be accurate, make sure you have some field in your view that will actually correspond to the "new" part of your question. To better explain this: have a look at the "tracker" view (disabled by default), which has the field "Content:Has new content" (or variation: "Content:Has new comments"). This is a perfect field to use if you want to use Menu Badges to get notified whenever there is new content (or variation: new comments).

If you don't have such "new" indicator, then you basically have 2 variations to get around that:

You give the user the option to selectively mark those entries so that they are no longer included in the counter. It takes a little effort to implement such option, but the tutorial about "How to allow users to manage their own Message Stack messages?" explains how to use the Flag, Rules and VBO modules to get it to work.
When the user visits the menu link (or menu tab), you "mark" all of the entries included in the Menu Badges counter as "no longer new". That should make the counter disappear entirely. The anser to "How to make menu badges count disappear after the page is viewed?" details the steps how this can be implemented.

Video tutorials:

Defining Menu Badges with Views in Drupal, from the module maintainer, which shows how to use it for a custom view with a menu tab "unpublished content" within admin/content.
Drupal 7 Menu Badges Module.


How to set a yml sequence config value via drush cset

Uh, I love riddles like this! And finally found a way!

You first have to delete the error_handlers config key.

$ drush -y cdel devel.settings error_handlers

And then set it again.

$ drush -y cset devel.settings error_handlers.4 4

Let's check.

$ drush cget devel.settings error_handlers
'devel.settings:error_handlers':
  4: 4

Yeah!

Just drush -y cset devel.settings error_handlers.4 4 without deleting it first would just append it and you'd end up with 1: 1 and 4: 4 both.


Development with git branches/ gitflow and new modules

I always have a somewhat up-to-date DB dump from live/master available. When switching between feature branches I can drush sql-drop the DB, drush sql-cli < live.sql and drush cim the branch config. If needed. When switching back into the develop or master branch I do the same steps again.

This means you routinely have to commit your feature's configs into its branch. Or to write really cool install.yml in a custom module and enable that after you switched back into the feature branch.

I guess we will have something automating this in half a year. But for now, it's perfectly fine. At least for me.


Views global text area replacement patterns for multiple values

You need to either display as a table, or change the settings to force fields to be included in the View.

When you add a field to Views, you can alter how it is represented, including Rewrite, Style and if it contains multiples, how to display those values.

Adjust the field settings for the field you want and then that should be represented in the replacement pattern further down the chain


Any control version tools: GIT, Mercury, SVN and etc for controlling team source.
Also drupal have prepared version of drupal installation for team working for tracking timelines, bugs, etc:
Drupal used as a project management tool
More version controlling tools reviewd here: http://www.smashingmagazine.com/2008/09/18/the-top-7-open-source-version-control-systems/

And there's many ready services (free or usually payment) for working with team in internet, try this search: http://www.google.ru/search?q=project+management, there I see basecamphq.com for example.

More hard thing is DB synchronizing, because it's depend on your tasks, for example, sometime merging portion of content and users are needed, sometime aren't. Some of system variables should be synchronized, some of these not. Some content type or fields are required, some just for test.

Hard solution is writing script (manual) in any language that have access to DBs and track changes.
Other solution is using Features module with some contributed, like Strongarm and etc. This module create module that have changes, where developers export their changes, so it can be controlled via Version control tools as usual plain file. You will just enable it, and their changes will applied to central site. Also with this (and not only) cool tool used: Drush, for me this is the best solution.
Also there's tools of synching depend on DB engine, Best tool for synchronizing MySQL databases for example.


See my custom entity as a normal page in drupal 8

Then you have probably defined an admin path to view the entity:

/src/Entity/MyEntity.php

 *   links = {
 *     "canonical" = "/admin/structure/my_entity/{my_entity}",

Change this to a non admin path:

 *   links = {
 *     "canonical" = "/my_entity/{my_entity}",


There is no block_user module so far as I can see or find.

You can delete the row from the key value table, yes. It should get rid of the error. You can do it with drush if you want.

Back up your database
drush sql-query "DELETE FROM key_value WHERE collection='system.schema' AND name='block_user';"

This assumes a Drupal 8 site.


How do I add a header to the contact form?

Just like Rylyn said you can use the #prefix attribute. You could change your form with the hook_form_alter:

 function YOURTHEME_form_alter(&$form, &$form_state, $form_id) {
    // replace the 'FORM-ID' with the actual id of the contact form
    if ($form_id == 'FORM-ID') {
       $form['name'] = array (
          '#type' => 'textfield',
          '#title' => 'your_title',
          '#prefix' => 'your_text_header'
       );
    }
 }


How to fix AJAX HTTP request which was terminated abnormally?

This issue sounds like yours: Drupal alerts "An AJAX HTTP request terminated abnormally" during normal site operation, confusing site visitors/editors


acquia/solr/D7: indexing additional files outside of a node

Decided just to work within the Drupal framework rather than trying to hard-code something special. After I split the PDF, for each page I used file_save_data() to register the file in the file_managed table, then added the resulting file to the node in a separate file field:

$thisSplitURI = "{$splitURI}/{$finalFilename}_{$i}.pdf";
$thisSplitPath = drupal_realpath($thisSplitURI);
$file = file_save_data($contents, $thisSplitURI); // $contents is the value where the raw PDF contents are stored
$file->display = 1;
$node->field_split_pdf_pages[LANGUAGE_NONE][] = (array) $file;

Probably not ideal, especially when there's an 800-page document in there, but it gets the job done.


It's not documented nicely anywhere I can find, but it seems that you can't use the password reset option via email for a user who's an Administrator of the site. Instead you have to use some alternate method to change the database directly, like this.


Is there a way to "hard-reset" a module?

This answer reflects my understanding of how Drupal is working.  Anyone with more or different understanding, please speak up, I'd love to know more.

Removing all remnants of a module by uninstalling it works only as well as the code included by the module for cleaning up after itself.  For instance, if it has made a change such as adding tables or otherwise changing the database and does not properly delete the tables, they will remain  there.  Removing the module, should remove much of its potential to cause a problem provided that Drupal core knows it is gone and does not hang up looking for hooks that the module provided.  Have you run 'update.php' in the URL?  This will cause Drupal to update all the connections to the module.  If the module is gone, then it won't make calls to it that cannot be responded to.

The only way to really reset Drupal is to maintain backups.  Make backups before installing any module and at least every day or so during site development. The module Backup and Migrate is a simple way to simplify  site database backups. In addition, it is also a good idea to look into using Git to keep track of your code when developing a site.  Git is basically a unix tool, but there are windows UI versions such as GitGui that are not difficult to learn and put to work keeping track opf your code.


How to debug Batch API more efficiently?

Here are some workarounds which I've found so far which makes life easier.

Using curl

You need: drush and curl.

Add var_export($name); exit; into the batch code place of interest, so batch won't be set to finish state.
In the web browser open Network console (e.g. DevTools in Chrome).
Start batch process as usual (in Feeds it's at: /import).
Stop the batch processing just before the redirect by pressing Escape. Then note the URI.

Alternative way is to fetch id directly from the batch table:

$ drush sqlq "SELECT bid FROM batch"

Click on the previous 302 request and take a note of your session cookie from Request Headers, you need only SESS0X=Y cookie, e.g.

Cookie: SESS0F00=B4R

Run curl as below (you need to replace id, session cookie and your host):

$ curl -X POST -d "id=124&op=do" --cookie "SESS0F00=B4R" "http://myhost.local/batch"
your_debug_data_here

Previous step is repeatable after each code change which makes it easy to debug variables in no time.

For ever more efficiently, you can map it (e.g. in vim), so the output can be executed each time when you need it.

Using repeatable XHR requests

Add var_export($name); exit; into the batch code place of interest, so batch won't be set to finish state.
In the web browser open Network console (e.g. DevTools in Chrome).
Start batch process as usual (in Feeds it's at: /import) and it should fail, because of exit; added in step 1.
Note the batch?id=x&op=do request and do Replay XHR (at least in Chrome).
Now on each code change you should be able to repeat the last step over and over again.

There are probably more ways of doing similar thing (including use of some plugins such as Postman, etc).


exposed filter autocomplete suggestions sort

The filter handler class views_handler_filter_term_node_tid uses the autocomplete path admin/views/ajax/autocomplete/taxonomy and is driven by the callback views_ajax_autocomplete_taxonomy().

This autocomplete callback explicitly excludes the term typed in and doesn't do any explicit sorting (thus defaults to whatever your RDBMS does):

$query = db_select('taxonomy_term_data', 't');
$query->addTag('translatable');
$query->addTag('term_access');

// Do not select already entered terms.
if (!empty($tags_typed)) {
  $query->condition('t.name', $tags_typed, 'NOT IN');
}
// Select rows that match by term name.
$tags_return = $query
->fields('t', array('tid', 'name'))
  ->condition('t.vid', $vid)
  ->condition('t.name', '%' . db_like($tag_last) . '%', 'LIKE')
  ->range(0, 10)
  ->execute()
  ->fetchAllKeyed();

If you'd like to alter the results or how it's sorted, the query is using tagging, thus available for altering via hook_query_alter().


Auto delete temporary files after 15 seconds of creation

The value stored in this config
\Drupal::config('system.file')->set('temporary_maximum_age', '15');

You can update that with the value you wants.
If you want to change the form as well which is recommended use hook_form_FORM_ID_alter to adjust the system file settings from system_file_system_settings
The current implementation looks like this
$intervals = [0, 21600, 43200, 86400, 604800, 2419200, 7776000];
$period = array_combine($intervals, array_map([$this->dateFormatter, 'formatInterval'], $intervals));
$period[0] = $this->t('Never');
$form['temporary_maximum_age'] = [
  '#type' => 'select',
  '#title' => $this->t('Delete temporary files after'),
  '#default_value' => $config->get('temporary_maximum_age'),
  '#options' => $period,
  '#description' => $this->t('Temporary files are not referenced, but are in the file system and therefore may show up in administrative lists. Warning: If enabled, temporary files will be permanently deleted and may not be recoverable.'),
];

You can alter the form and adjust it to what you want.
Keep in mind, to see this happen your corn must run at least every 15 sec.


How can I programmatically change the view mode?

You can select VIew Mode as:

function YOUR_MODULE_entity_view_mode_alter(&$view_mode, Drupal\Core\Entity\EntityInterface $entity, $context) {
  if ($entity->getEntityTypeId() == 'taxonomy_term' && $entity->bundle() == 'tag' && $view_mode == 'full') {
    $view_mode = 'CUSTOM VIEW MODE';
  }
}


Drupal Common's 3 How To Edit The Commons Browsing Widget Tabs?

If you specifically need to remove the Wiki's Tab instead of turning off Commons Wiki module, none of the functions to override has been set up as a hook, as far as I can understand.

So even if the following method is not the best approach, you could make a very quick patch to commons_bw.module :

Into function commons_bw_get_tab_definitions($widget_type = 'group')

add unset($tabs['commons_wikis']); before return $tabs;

Of course you'll have to remember this whenever you update your Commons distrib...

See also this great post on how to add your own content type to the Commons browsing widget. This will give you a complete overview of what you can do


$query = Index::load('my_index')->query();
$query->addCondition('search_api_language', $language);
$query->keys($search_string);
$query->range(0, 25);
$data = $query->execute();

Also I have a custom parsing function for the results:

function parse_results(array $results) {
$list = [];
  foreach ($results AS $item) {
    // The pattern is "entity:[entity_type]:[entity_id]:[language_code]".
    // For example "entity:node/1:en".
    $data = explode(':', $item->getId());
    $data = explode('/', $data[1]);
    $list[] = $data[1];
  }
  return $list;
}


What options do I have for changing CSS depending upon context?

We have been using the theme key module to switch between different styles and (sub-) themes for different situations.


user-profile.tpl.php and render($user_profile) not working

In order to have the $user_profile renderable array available within your tpl, you can use the same logic used by Drupal user core module.

Build the content for a user object, loop through each field and assign it to the $user_profile variable.

In your case, it would something like this:

function mytheme_preprocess_user_profile_form(&$vars)
{
    // load user
    $account = user_load(arg(1));

    if (!$account) {
        // user not found
        return;
    }

    // retrieve all profile fields and attach to $account->content.
    user_build_content($account);

    // loop through each field attached to the user object
    $vars['user_profile'] = array();
    foreach (element_children($account->content) as $key) {
        // add it to the $user_profile variable, which will be available in tpl
        $vars['user_profile'][$key] = $account->content[$key];
    }

    $args = func_get_args();
    array_shift($args);
    $form_state['build_info']['args'] = $args;
    $vars['form'] = drupal_build_form('user_profile_form', $form_state['build_info']['args']);
}


Add a field to multiple content types at once?

Broad lines using the Features module could be:

Add the field to two (to see the pattern) content types by hand
Create a Feature including field bases and field instances for the newly created fields
Edit the created module multiplying the field bases and instances to all content types needed
Enable the edited module


If you are using the Migrate UI, at the bottom of the page there is an Options slideout with the Update checkbox. If you are kicking off your migration programmatically then call prepareUpdate() before calling processImport().

migrate_static_registration(array($machine_name));
$migration = Migration::getInstance($machine_name);
$migration->prepareUpdate();
$result = $migration->processImport();


How can I invalidate cached field access grants for anonymous users?

I was able to use hook_entity_field_access and return an AccessResult $result->addCacheContexts(['session', 'user.roles.anonymous'])


Content API - parameter to find link url of a Link field

The Content API is a tricky thing to get the hang of, but try to do the following:

As long as your Rest Server endpoint path is "api" and the resource is "content" what you have above should technically work.  Make sure you also enabled the Link content type in the Content API configuration.

When you do query with /api/content?field_link=http://www.google.com you will only get the base fields returned, even if you filtered by http://www.google.com it won't show in the response you get.  You then have to send another request to /api/content/ and that will return every field for that given node.

Hopefully this helps a little bit, if anyone can fill in my holes I would appreciate it, I'm by no means an expert, just played around with the Content API and got it to work a little.

I did respond to your email with some private links to prove that it is possible.


On the other answer, the page cache is bypassed on the first hit. Subsequent hits do hit the page cache because the cookie will be set then.

To answer your question, have some client side javascript that sets a cookie called gallery_list_mode. If no selection is made, set it to 0 or delete it. If user selected thumbs, have the javascript set the gallery_list_mode cookie to thumbs. Then inside of your settings.php drop this in

<?php
// Check if cookie is set and user is on a gallery page.
if (!empty($_COOKIE['gallery_list_mode']) && $_SERVER['REQUEST_URI'] == '/gallery') {
  $ok_list = array(
    'thumbs',
  );
  if (in_array($_COOKIE['gallery_list_mode', $ok_list)) {
    // Add cookie value to page cache id.
    $_SERVER['REQUEST_URI'] .= '?list_mode=' . $_COOKIE['gallery_list_mode'];

    // This line might be needed.
    //$_GET['q'] .= '?list_mode=' . $_COOKIE['gallery_list_mode'];
  }
}
?>

This will make http://domain.com/gallery point to the cache entry for http://domain.com/gallery?list_mode=thumbs if the gallery_list_mode cookie is set to thumbs.

As a security feature you should make sure to only accept values for gallery_list_mode that you want. That is what the $ok_list array is for.


An year and a half later ...
Looks like it's xdebug: https://bugs.xdebug.org/bug_view_page.php?bug_id=00001401
If you turn debugging on (so something is listening on port 9000), the error goes away.
(Found this while searching for the same problem, so I thought I'd share)


How do I remove extra space in table field?

I checked this in my site and this is indeed default behaviour of Views. The easiest way to fix this is by changing your code to:

$.trim($(this).find('td.views-field-title a').text());


Drupal caches the system table with all the module locations, so you'll need to run:

    drush registry-rebuild

or use the Registry Rebuild module in order to flush that cache after manually updating the module paths in the system table. Alternatively, you could also just manually delete the system list from the cache bootstrap table:

    DELETE FROM cache_bootstrap WHERE cid='system_list';

Sources:

Overriding and Removing Overridden Modules included in a Distribution - https://drupal.org/node/1974964

Disabling or Enabling modules manually in the database - https://drupal.org/node/157632


What was killed after the installation and enabling of Devel with Drush 7?

In my case, increasing the value of memory_limit in php.ini solved the problem.

I had 128M and I just changed to 512M, for testing purposes, and the "Killed" message just disappeared.

Of course, don't forget restart your web server after that change.


File is saved to /tmp directory, despite setting it permanent

Just use a managed file element, it's much easier:

$form['fid'] = array(
  "#title" => "Document file",
  '#type' => 'managed_file',
  '#size' => 22,
  '#upload_location' => 'public://',
  '#upload_validators' => array(
    'file_validate_extensions' => array('pdf doc docx'),
  ),
);

Then remove the validation handler and change you submit handler to:

$file = file_load($form_state['values']['fid']);
$file->status = FILE_STATUS_PERMANENT;
file_save($file);

And you're done; Drupal handles moving the temp file into the right place for you, as well as adding relevant records to the file_managed/file_usage tables.


The best way to implement custom rendering of a form would be to use a custom theme hook for the form:

/**
 * Builder function for the ticket form.
 */
function MODULE_ticket_form($form, $form_state) {
  // Build the $form array here...

  // Let the theme API knows that this form use it own theme hook.
  $form['#theme'] = 'ticket_form';
  return $form;
}

/**
 * Implements hook_theme().
 */
function MODULE_theme() {
  return array(
    // Custom theme hook for the ticket form.
    'ticket_form' => array(
      'render element' => 'form',
    ),
  );
}

/**
 * Default implementation for the ticket_form theme hook.
 */
function theme_ticket_form($variables) {
  $form =& $variables['form'];

  //Custom rendering of forms elements goes here...
  $output = ...;

  // Render every other elements (incl. hidden system ones).
  $output .= drupal_render_children($form);
  return $output;
}

Instead of using only a theme function, you can also use a template file. The theme function can also return a render array instead of a string.


Get authenticated user details from a remote database

I recommend separating these questions.

1) Drupal Single Sign on module: https://drupal.org/project/sso

2) Again, I recommend posting this as a separate question, but could you be more specific? which table(s)?


The module used for translating fields (title, help text, description, allowed values) is i18n_field.

Internationalization 1.8 shipped with a broken i18n_field module, so in many cases nothing would get translated.

The first issue that fixed most of the failures was
[7.x-1.8 regression] Field translation fails in numerous situations
It has now been committed and is a part of the latest -dev release.

Contrib field types such as commerce_price might need the following patch:
Extend support for contrib field types

With those patches applied I had no problem with translating any part of a field.
For translating allowed values (radio or select fields), my process was this:
1) Go to manage fields, click edit next to my list(text) field.
2) Click the Translate tab on the next page.
3) In the table, find my language and click "translate".
4) I can translate the values under the "Field settings" vertical tab.

Also keep in mind that when showing one of those values on a rendered entity, you need to use the "Default translated" formatter (set under "Manage Display").


Visibilities permissions of children links in the Toolbar

This is not a problem with the Admin Toolbar module, I think that you're not given the correct permissions.

In Drupal >= 8.5 you need to give the following permissions:

Use the administration pages and help
Use the administration toolbar
Tags: Create terms
Tags: Delete terms
Tags: Edit terms
Access the taxonomy vocabulary overview page

In Drupal < 8.5 as the Access the taxonomy vocabulary overview page not exists you need to assign the following permissions:

Use the administration pages and help
Use the administration toolbar
Tags: Create terms
Tags: Delete terms
Tags: Edit terms
Administer vocabularies and terms

The problem here is that the user will have the permission to create new vocabularies.

You can read about this in New term overview and create permissions and in Add a dedicated permission to access the term overview page (without 'administer taxonomy' permission)


The Webform module for Drupal 8 does not fully support display modes.  To alter a submission's HTML or text you will need to use hook_preprocess_webform_submission_html() and hook_preprocess_webform_submission_text().

I created a ticket on D.O. to look into this issue.


The quickest way might be/would be to copy...

/**
 * Theme function for unified login page.
 *
 * @ingroup themable
 */
function theme_lt_unified_login_page($variables) {

  $login_form = $variables['login_form'];
  $register_form = $variables['register_form'];
  $active_form = $variables['active_form'];
  $output = '';

  $output .= '
';

  // Create the initial message and links that people can click on.
  $output .= '
' . t('You are not logged in.') . '
';
  $output .= '
';
  $output .= l(t('I have an account'), 'user/login', array('attributes' => array('class' => array('login-link'), 'id' => 'login-link')));
  $output .= ' ';
  $output .= l(t('I want to create an account'), 'user/register', array('attributes' => array('class' => array('login-link'), 'id' => 'register-link')));

  $output .= '
';

  // Add the login and registration forms in.
  $output .= '
' . $login_form . '
';
  $output .= '
' . $register_form . '
';

  $output .= '
';

  return $output;
}

to your theme's template.php file and rename it...

/**
 * Theme function for unified login page.
 *
 * @ingroup themable
 */
function YOURTHEME_lt_unified_login_page($variables) {

  $login_form = $variables['login_form'];
  $register_form = $variables['register_form'];
  $active_form = $variables['active_form'];
  $output = '';

  $output .= '
';

  // Create the initial message and links that people can click on.
  $output .= '
' . t('PLACE YOUR CUSTOM MESSAGE HERE.') . '
';
  $output .= '
';
  $output .= l(t('I have an account'), 'user/login', array('attributes' => array('class' => array('login-link'), 'id' => 'login-link')));
  $output .= ' ';
  $output .= l(t('I want to create an account'), 'user/register', array('attributes' => array('class' => array('login-link'), 'id' => 'register-link')));

  $output .= '
';

  // Add the login and registration forms in.
  $output .= '
' . $login_form . '
';
  $output .= '
' . $register_form . '
';

  $output .= '
';

  return $output;
}

...along with whatever you wanted that login-message to be.  Clear caches/theme registry and you should be on your way.

ADDITION:

This drupal fu works because, instead of calling theme_lt_unified_login_page() directly, it does it like this:

$output = theme('lt_unified_login_page', $variables);

and it is the theme() function that does the magic in that when you build the theme registry, it will discover that there is a YOURTHEME_lt_unified_login_page() function out there, and will call that as an override to the theme_lt_unified_login_page() one that logintoboggan provides.

(Note that the first argument doesn't start with theme_ or YOURTHEME_, one of these are prepended by the theme system as described above.)


Any way to set Drupal theme settings per page?

For Drupal 7, you can do this by taking advantage of the fact that theme settings are cached by drupal_static(). See theme_get_setting(). I think the same approach would work for Drupal 8 too, but haven't tried it.

// Implement HOOK_init.
// Here we override one of the Bootstrap theme settings.
function MY_MODULE_init() {
  // Only do this if we're actually on the relevant page.
  if ($_GET['q'] == PATH_TO_THE_PAGE) {
    // Override the Bootstrap theme setting 'Smart form descriptions (via Tooltips)'.
    // This because we want to display form input #description as text, not tooltip.
    // This will also affect any other forms on the current page, no easy solution for that.

    // Set the name of the theme we're interested in (the current theme in this case).
    $theme_name = $GLOBALS['theme_key'];
    // Read the setting first to ensure that the drupal_static cache is populated.
    $setting = theme_get_setting('bootstrap_forms_smart_descriptions', $theme_name);
    // Get a reference to the cached settings.
    $cached_settings = &drupal_static('theme_get_setting');
    // Unset the 'bootstrap_forms_smart_descriptions' setting from the cache.
    unset($cached_settings[$theme_name]['bootstrap_forms_smart_descriptions']);
  }
}

I should add, this is arguably a bit of a hack, as it depends on the internals of drupal_static() and theme_get_setting() i.e. not documented API functionality - unless you consider the code to be the documentation :)