How to place Drupal_Security_Do_Not_Remove_See_SA_* into httpd.conf instead of .htaccess

.htaccess files are just convienance mechanisms to change Apache configuration without needing to restart Apache (.htaccess are scanned/run any request) -- for performance reasons you may want to place any directives in .htaccess files directly into a vhost entry so the configuration is loaded and stored only one time; on Apache startup.

From the security notice SA-2013-003:

  Warning: Fixing the code execution prevention may require server
  configuration; please read:

  To fix the code execution prevention
  vulnerability on existing Apache installations also requires changes
  to your site's .htaccess files in the files directories. Until you do
  this, your site's status report page at admin/reports/status will
  display error messages about the problem. Please note that if you are
  using a different web server such as Nginx the .htaccess files have no
  effect and you need to configure PHP execution protection yourself in
  the respective server configuration files.

  To fix this issue, you must edit or replace the old .htaccess files
  manually. Copies of the .htaccess files are found in the public files
  directory and temporary files directory, and (for Drupal 7 only) the
  private files directory if your site is configured to use one.

So you take whatever is in the .htaccess file in your websites configured files directories (public, private, etc) and assure those same rules are in the vhost entry for the same set of directories. Typically you do this with a <Directory> directive:

<Directory "/var/www/html">
    Options Indexes FollowSymLinks
    AllowOverride None
    Order allow,deny
    Allow from all
</Directory>
......
<VirtualHost 123.123.123.123:80>
    DocumentRoot /var/www/html/mysite1.de
    ServerName mysite1.de
    ServerAlias mysite1.de *.mysite1.de

    <IfModule mod_rewrite.c>
        <Directory "/var/www/html/mysite1.de">
            RewriteEngine on
            RewriteCond %{REQUEST_FILENAME} !-f
            RewriteCond %{REQUEST_FILENAME} !-d
            RewriteCond %{REQUEST_URI} !=/favicon.ico
            RewriteRule ^ index.php [L]
        </Directory>
    </IfModule>

    # Enforce new security rules from SA-CORE-2013-003.
    # repeat this block as needed per known "files" directories.
    <Directory "/var/www/html/mysite1.de/sites/default/files">
      # Turn off all options we don't need.
      Options None
      Options +FollowSymLinks

      # Set the catch-all handler to prevent scripts from being executed.
      SetHandler Drupal_Security_Do_Not_Remove_See_SA_2006_006
      <Files *>
        # Override the handler again if we're run later in the evaluation list.
        SetHandler Drupal_Security_Do_Not_Remove_See_SA_2013_003
      </Files>

      # If we know how to do it safely, disable the PHP engine entirely.
      <IfModule mod_php5.c>
        php_flag engine off
      </IfModule>
    </Directory>
</VirtualHost>

It doesnt matter if the default web directory has AllowOverride None; typically another conf file included down the apache startup chain, or the virtual host loading setup (such as the following in Ubuntu) can be tweaked to allow any combination of Overrides:

# Ubuntu apache2.conf last line ...
# Include the virtual host configurations:
Include sites-enabled/

This is just saying include *.conf from sites-enabled these dont have to be vhost entries they can be any files with apache directives (but its cleanest to have them be vhost entries) and apache loads the configuration files following a filename pattern/sort.


How can I execute a JavaScript function before the form submission handler is called?

Remove #submit.

$form['submit'] = array(
  '#type' => 'submit',
  '#value' => 'Save',
  '#attributes' => array(
    'id' => 'myid_save',
  ),
);

Your submit function should be myid_user_page_form_submit rather than formsave_action. If your form's function name is myform_form, then you just need to write the submit handler like myform_form_submit. It will consider it automatically.

Now change your js to :

$('#myid_save').on('click', function(e) {
    myid_save_signature();
    myid_save_photo();
    $('#myid_save').submit(); // Add this line
});

It will submit your form using jquery.


Notice: Undefined index: #ajax in ajax_form_callback() (line 391 of /var/www/html/includes/ajax.inc)

Found the solution for this issue in my case was with the max_input_vars which was occurring on Windows machine.

Go to C:\xampp\php (the path where you have installed your WAMP or
XAMPP).
Open the php.ini, the configuration file located there.
Approx on line 475 there would be max_input_vars = 1000 change that as per your need. In my case 1500 worked for me.

Note: I'm not sure increasing max_input_vars is a good practice, I have done that as I was having more than 10K fields in a single form. Still for those who are looking for an alternate solution in their development phase can opt this solution for time being.


You will need to implement hook_views_query_alter to get this going.

Start with the filters in Views.

Make your filters look exactly like this. With that I mean that there should be two groups of filters with AND between the groups. And you need to set Or in the second group. This is important otherwise the code below will not work.

Then replace hook_views_pre_execute with the code below for hook_views_query_alter. I also recommend you rename your module to customsearch instead of customSearch, small letters is standard in function names for Drupal.

/**
* Implements hook_views_query_alter().
*/
function customsearch_views_query_alter(&$view, &$query) {
  if ($view->name == 'search') {
    if (isset($query->where[2]['conditions'][0]['field']) && $query->where[2]['conditions'][0]['field'] == 'field_data_field_price1.field_price1_value') {
      $query->where[2]['conditions'][1]['value'][0] = $query->where[2]['conditions'][0]['value'][0];
      $query->where[2]['conditions'][1]['value'][1] = $query->where[2]['conditions'][0]['value'][1];
    }
    else {
      unset($query->where[2]);
    }
  }
}

In the code I first check to see if something has been entered in the exposed filter. If it is present we populate the second filter's values.

If you enable the module devel and do dsm($query) just before the last } you can debug and look in  the array yourself. For exammple number 2 in $query->where[2] means the second group of filters, which you will see easily if you debug.

Update: I've added an else statement so that the price fields are not in effect at all if nothings been entered in the in betweens.


Anonymous view while developing without quit maintenance mode

This is exactly what the Maintenance Exempt module was built for. From the project description:

  This D7+ module allows specific people to perform the necessary testing on the site with all role combinations without opening the site up to all of your visitors.

  Exemptions can be added by:

  Specifying a list of IP addresses (individually or by CIDR notation)
  Specifying a query string variable


Metatags not showing despite calling render in template

Turned out someone had overridden html.tpl.php and had removed the reference to $head. Adding echo $head between <head> and </head> in html.tpl.php fixed the problem.


First of all it might be that you found a bug in core (a caching issue), so it would be great if you could report it to the Drupal core issue queue as well. There is extensive test coverage for local tasks, but it might be that there is none for adding new entities and that those in core just work due to side effects.

To solve your immediate issue I would try to invalidate just the render cache of the local task blocks.

To find out the cacheability metadata of the local tasks the easiest is to install the renderviz module:

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

and apply the patch from this comment

https://www.drupal.org/node/2640280#comment-11286381

Once you have that installed and you go to the page with your local tasks, you will see a list in the JS console of all cache tags present.

For the bartik theme you will find (e.g. tested with core search pages, which have similar code to yours):

config:block.block.bartik_local_tasks

If you put into the console:

  renderviz('tags', 'config:block.block.bartik_local_tasks');

Then you will see that indeed the primary local tasks will be highlighted.

So in your hook_entity_insert() / hook_entity_update(), you can just do:

 Drupal\Core\Cache\Cache::invalidateTags('config:block.block.bartik_local_tasks');

And that will invalidate just the local tasks block and solve your issue for now.

What should have happened however is that the local tasks block should show both the cache tags for the list [entity-type] and the entities itself. (like a normal listing of entities)

e.g. if you want to change the title of any of your entities, core should based on the deriver update the local tasks block.

And that we don't do that is likely a core bug in regards to cacheability metadata, so please file it. Unless I miss something and there is some special code that makes this work for core's derivers out-of-the box.

Edit:

We correctly add the cache tags of the config entities, however there is no 'list' cache tag, which means that whenever you add or delete a config entity the local tasks don't get invalidated.

As you have a plugin, you can likely just add your own custom cache tag to the plugin definition.

e.g.

$base_plugin_definition['cache_tags'][] = 'local-tasks-my-entity-type-list-cache-tag';

Then just invalidate that list cache tag in your insert / update.

But that definitely is also an issue in Drupal core as I can reproduce it purely with core search pages.

I missed in your question at first that caches fail to get invalidated only when adding or deleting new entities.

That however was the key clue.

Edit 2:

Core should be invalidating list cache tags automatically, so the easiest is to just use the pre-defined list cache tags.

This is the diff that fixes the bug for me in core:

diff --git a/core/modules/search/src/Plugin/Derivative/SearchLocalTask.php b/core/modules/search/src/Plugin/Derivative/SearchLocal
--- a/core/modules/search/src/Plugin/Derivative/SearchLocalTask.php
+++ b/core/modules/search/src/Plugin/Derivative/SearchLocalTask.php
@@ -52,7 +52,9 @@ public function getDerivativeDefinitions($base_plugin_definition) {
           'route_name' => 'search.view_' . $entity_id,
           'base_route' => 'search.plugins:' . $default,
           'weight' => $entity->getWeight(),
 -        );
 +        ) + $base_plugin_definition;
 +
 +        $this->derivatives[$entity_id] += ['cache_tags' => []];
 +        $this->derivatives[$entity_id]['cache_tags'] += $entity->getEntityType()->getListCacheTags();
       }
     }
     return $this->derivatives;

That fixes the bug for me for core search pages.


Views 3 + field collection: relate only the first referenced field collection item

If you create a view with the field collection relationship this is possible.
Besides the field with the image you need to add another field with the image delta.
When you add this field exclude this from display.

In the views filter add a filter on this delta field and set this filter to equals 0.

Now you've got a view with just one (the first) image per node!


The UI for dealing with taxonomy term relationships hasn't changed much in Drupal 7 I think.

However, you might want to look into some contributed projects, for example Taxonomy manager, which exist for both D6 and D7. I don't know if it provides a solution for this, however.


How do I add fields to an existing custom entity?

You just need to add a field_ui_base_route to the entity annotation. The value should be the route ID for the edit form of the config entity type used to provide the bundles.
So if your entity ID is foo and the bundle config entity ID is foo_type, that would be:
@ContentEntityType(
  id = "foo",
  ...
  field_ui_base_route = "entity.foo_type.edit_form"
)

Rebuild the cache, and you should see the relevant menu links and tabs when you manage your bundles in the UI.


Can one feature module make additions to another feature module?

It's definitely possible, I had to do something similar yesterday and I'm happy to say features can handle it perfectly.

The trick is that your 'advanced' feature will not contain the content type at all, but simply a list of the extra fields that are attached to the content type defined by the original rule.

When you install/enable the second feature module, the extra fields will be added to the existing content type as if by magic. I was pleasantly surprised at how well this works.

There is an example of a well established Drupal distribution using this same method (it's where I got the idea if I'm being honest); OpenPublish contains the openpublish_article feature, which defines a content type, and the openpublish_atricle_extra_media feature, whose sole job is to add a couple of extra fields to the article.

Just as a side note, it would probably be a good idea to make your main feature module a dependancy of the second, so the content type is definitely defined by the time the second feature is trying to add the extra fields to it.


Drupal 7.x + Ubercart 3.x + Domain Access

There is no working UC_domain module for Ubercart 3 - Drupal 7, and many issues of configuration - including payment methods per domain user are not availble


How to list and store the value of hidden exposed filter of several views for anonymous user?

The User Alert module may provide a good starting point.  It stores a uniqueid for each visitor in a cookie and keeps track of whether an alert has been closed.  The logic for this would be similar, but you'll need to wire up the code in your own module to push the views-filter to the cookie and back.


What is the command to execute after manually editing the composer.json file?

You are better off calling composer require some/library. This will update the files accordingly and install the library as well.
That said, you can run composer install after manually editing composer.json.


Add a cache tag to the response of /api/v1/get-list:

$build = [
  '#cache' => [
    'contexts' => ['url','url.query_args'],
    'max-age' => 3600,
    'tags' => ['api-v1-list'],
  ],
];

and then invalidate this tag in /api/v1/post-item:

\Drupal\Core\Cache\Cache::invalidateTags(['api-v1-list']);


Programmatically Access custom user field

You can get field values from any entity with field_get_items(); the logged in user is available in the global $user object, and to load fields onto that object you can use user_load().

Put those together and you get something like this:

// Get a fully loaded entity object for the logged in user.
$account = user_load($GLOBALS['user']->uid);

// Extract the field items
$field_items = field_get_items('user', $account, 'field_node');
if ($field_items) {
  // This will be 'target_id' if you're using the Entity Reference module,
  // or 'nid' if you're using References
  $column_name = '?';

  $nid = $field_items[0][$column_name];
}

That's the abstract code if you like.

It's worth bearing in mind that hook_node_access() is passed an $account object already (which will be the logged in user if the access check is happening for them) so you would probably be better off using that to check against. You might still need to run it through user_load(), it'll be easy enough to check that with a bit of debugging.


How to filter entities in View by all of their taxonomy term reference fields?

You can get an argument from url with views.

Use Provide default value in the contextual filter.

Another way (in drupal 7)would be to use this module: https://drupal.org/project/views_url_path_arguments


CSS to define where a image is located on each Node

If you look at the body tag in view source or firebug you should be able to see a list of CSS classes assigned to class attribute; Ex. class="html not-front page-node page-node-1"

So you should be able to style each node different than other nodes based on the node ID

CSS example:

/* node 1 styles */

body.page-node-1 .title {
  color: #333;
  background-color: blue;
}

body.page-node-1 .field-name-field-image {
  position: absolute;
  left: 100px;
  top: 100px;
}

/* node 2 styles */

body.page-node-2 .title {
  color: #000;
  background-color: yellow;
}

body.page-node-2 .field-name-field-image {
  position: absolute;
  left: 200px;
  top: 200px;
}

I hope this will help you.


How can I restrict various roles with limit in creating nodes of a particular content type

you can use node limit module to restrict nodes for various roles.

For each roles you can create a node limit condition with certain limit for nodes for tat particular content type.


Configuration > Development > Logging and errors has some settings on whether to display drupal messages or not. You might check to make sure that it is properly configured for your use case.

Path to config page: /admin/config/development/logging


What happens when a site goes in maintenance mode while a user is editing an node content?

Unless you notify the editors about that, they will lose their work on that node. You can do that either by using some contrib modules or by creating your own custom module. Either way, I think you definitely need some kind of ajax solution so they can be notified even when they are on the node edit page.

You can check Privatemsg and Private Message Growl modules. I'm not quite sure how they work but they look promising.


Best way to build pages, or page equivalent

I would suggest checking out Panels and CSS Injector.

Panels does most of what you are looking for; it presents a user interface for laying out varied content on a page without having to dig into HTML. It's not quite a pure WYSIWYG interface (theme styling might not apply to the Panels UI depending on your set-up), but it is as close as you can get with an out-of-the-box solution in Drupal.

CSS Injector will allow your designers to write CSS specifically for one Panels configuration through the UI, without having to touch the theme files.


Creating a fake JavaScript exposed filter in Drupal 7 Views module

Here is the solution I used:

I created a new module named "My Views' Client Side Filters".

In the module's .module file I added:

<?php

function my_views_client_side_filters_form_views_exposed_form_alter(&$form, &$form_state, $form_id)
{
    $form['#attributes']['onsubmit'] = 'return exposedFilterOnSubmit();';
    drupal_add_js('sites/all/themes/MY_THEME/js/MY_JS_FILE.js');
}

Which resulted in the HTML:

<form onsubmit="return exposedFilterOnSubmit();" action="MY FORM DESTINATION" method="get">

And sites/all/themes/MY_THEME/js/MY_JS_FILE.js:

function isEmpty(str) {
    return (str.length === 0 || !str.trim());
}
var departmentAllShown = true;
var nameAllShown = true;
(function ($) {
    function reloadNames(name) {
        $('.views-row').each(function() {
            if($(this).find('.doctors_view_row_title').text().toLowerCase().indexOf(name.toLowerCase()) >= 0)
                $(this).css('display','block');
            else
                $(this).css('display','none');
        });
        nameAllShown = false;
    }
    jQuery.extend({
        exposedFilterHider: function()
        {
            //Handle url (JavaScript only now enabled)
            if(!isEmpty(window.location.search))
                location = "MY_SITE_LOCATION/FORM_PAGE";

            var department = $('#edit-field-department-value')[0].value;
            var departmentIndex = $('#edit-field-department-value')[0].selectedIndex;
            var name = $('#edit-title')[0].value;

            var nameIsEmpty = isEmpty(name);

            if (departmentIndex != 0)
            {
                $('.item-list').each(function() {
                    if ($(this).children().first().text() === department)
                    {
                        $(this).css('display','block');
                        if (!nameIsEmpty)
                            reloadNames(name);
                        else
                            if (!nameAllShown)
                            {
                                $('.views-row').css('display','block');
                                nameAllShown = true;
                            }
                    }
                    else
                        $(this).css('display','none');
                });
                departmentAllShown = false;
            }
            else
            {
                //Enable all categories if not already
                if (!departmentAllShown)
                {
                    $('.item-list').css('display','block');
                    departmentAllShown = true;
                }

                if (!nameIsEmpty)
                    reloadNames(name);
                else //Enable all names if not already
                    if (!nameAllShown)
                    {
                        $('.views-row').css('display','block');
                        nameAllShown = true;
                    }
            }
        }
    });
})(jQuery);

function exposedFilterOnSubmit()
{
    jQuery.exposedFilterHider();
    return false;
}

Sorry I don't explain any further, I'm kind of stressed in time. If someone asks a specific question I promise to answer.

Hope this helps anyone!

BTW, although the code is a bit long it works spectacularly and runs swiftly.

Remember to change the classes! You might need to change things a bit since my layout may not be the same as yours.

My classes:

.views-row - Entire "person" row (The name container is somewhere inside and there are a few of those in every category)

.doctors_view_row_title - Name container

.item-list - The category container

Good luck guys!


Product price not showing up in views without Disable SQL rewriting

This has been discussed in a lengthy thread on drupal.org. The recommendation apparently is indeed to disable SQL Rewriting. There is a pretty good explanation of the ramifications in the middle of the thread along with alternative suggestions. But it appears that you got it right for now.


You don't need to code to do this. Have a look at the answers to this questions to find more information: How to modify user messages without hacking core user module?


Never mind I think I finally found the solution:

In addition to the settings above, I added a second relationships: Content: Vote results. It's the same relationship as before but instead of "Average vote" in the Aggregate function, I have "Number of votes." So as to avoid confusion, I also changed the identifier to: "Vote results (rank in group)"

So, I have two relationships, almost identical except for the Aggregate functions.

Then, in addition to the sort criteria described above, I added the same criteria again except that I chose the second relationship ("Vote results (rank in group)") instead. Order is also descending.

And that gave me the desired results: Nodes are properly ranked within the groups.

You can test this by enabling  Text to display under the stars: Both user's and average vote in the rating field.

:)

Hope that helps.


Quite a vast topic among many reasons:

MyISAM doesn't support foreigns keys and Drupal used this as a default engine until D7 (which now use InnoDB as default if available).
Schema now support foreign keys so you can benefit from this in documentation.
Enforcing FK in Drupal would be quite a challenge (Damien Tournoud - one of Drupal most prolific core contributor - stated: Drupal is far from being able to use foreign keys properly).


Try this

\Drupal::service('renderer')->render(views_embed_view('VIEWSID', 'DISPLAYID'));


insert fields for the links in my content type

If I understood the your question, your solution is here.
It gives you the chance to insert link such as field. Once you enabled the module, you can add the field through "manage field" tab of your content type.
If you want to access via php, you can use the Devel module.


How to replace "Enter quantity" text for Production variation?

I too had the same problem. Because this text is hardcoded and there is no configuration for updating the text.

Ways to change the text

Use String Overrides module.
Do a form_alter and change the text from Add to Cart to Buy Now

Form Alter for Enter quantity

function module_name_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'commerce_cart_add_to_cart_form') {
    $form['quantity']['#title'] = t('Enter your Quantities');
  }
}

Hope this code helps.


How can I stop js script from running on mobile?

You can deetect the screen size in Vanilla JS or jQuery. In jQuery you can use height() and width() to get screen size. So you can try this

jQuery(document).ready(function(){
  if($(window).width() > 480){
    $('#selllink').trigger("click");
  }
});

You could also use resize() to check for window resize event.


Get/modify taxonomy term info in node edit form field?

I know I can look up each term in
  hook_field_widget_options_select_form_alter since the tids and term
  names are available in the $element, but I hope there is a solution
  which won't require me to re-load/re-fetch the term from the database
  again.

Unfortunately I think you will have to load them again and do the hook_field_widget_options_select_form_alter. There are a lot of functions to load taxonomy information which might be helpful and some of those probably have caches and were used in building the node form so the cache is already primed.

Is your concern around performance or code complexity?


The answer is yes. The import_html module has a few tools available for this. You can:

Build a custom module that makes use of hook_cron() to trigger importing import functions in import_html. This would be good for standard periodic import based on certain times of the day.
Utilize the module's Drush integration and use the drush import-html command inside a shell script that's executed with crontab. This would be good for periodic import as well as one time imports that you can do with the command line.

The module also has an API to take action upon various parts of its import process too if you need it (e.g. alerting site admins of new imported site content).

As a starting point, you should review the documentation on the project page. It has a help document that walks you through the usage of the module. If #1 is your preferred goal, you'll want to get familiar with the Drupal API, so you can understand how to create modules and understand the code of import_html module. For #2, you'll need to install Drush, learn how to use the drush import-html, and write out a shell script.


Why does my select list not translate to another language in Views?

I found the answer for this finally ...

After doing all the steps like the image that I attached before,
you should delete the old FILTER CRITERIA and add the New translated one to make the select list translate :

After doing so, the select list will be translated.


To return $data in json format using Drupal-7's page callback output, you should return through :

drupal_json_output($data);

in your page callback function.
For more ref : http://api.drupal.org/api/drupal/includes!common.inc/function/drupal_json_output/7

Note : in your javascript in car.module, var pageUrl seems undefined. Make sure it is defined.


How do I find a Form_ID for hook_form_FORM_ID_alter?

The form ID is used as the id attribute on the form when it renders.

For content types the pattern is also predictable:  node-[TYPE_NAME]-form.  So in your case you're looking for:  hook_form_node_videos_form_alter().

Another way to handle it is to use the main hook_form_alter() and check the $form_id parameter when you load the form you'd like to target.


An AJAX HTTP error occurred. HTTP Result Code: 500

You guys were right and it was a problem with CKEditor and Media not working well together.  I fixed it using a patch found here: https://www.drupal.org/node/2455391


How can I force users to input a shipping address when using the Commerce Paypal WPS submodule?

Have you tested this:

You need to activate the Shipping pane under checkout process:

Go to Administration > Store settings > Advanced store settings > Checkout settings (admin/commerce/config/checkout),
Check Shipping service under "Checkout pane configuration" or if you use recent version of DC move "Shipping information" pane from disabled panes section to Checkout section,
Save.

If you want to alter data before sending, use the hook_commerce_paypal_wps_order_form_data_alter(). You need to fetch the customer shipping profile for the current order using commerce_customer_profile_load() and add the values you need from the shipping profile to the $data array.


How to order views by taxonomy term name?

Solved!
I create a relationship beetween the nome and the taxonomy term using the term weight to order the nodes ^^
Now it works!

Thank you Mołot to let me see the SQL query ^^


when i want to reinstall the modules i get this error

The content type you create is stored in your database, no reason to do what you are trying to do.
Check your db tables for that types.

These are core modules that are never meant to be uninstalled, cause these kind of functions are used by other modules and core files without even a dependency on them cause they are considered ... core.

Better try with a fresh install.


Multiple local Drupal sites for development on WAMPServer?

This question is a bit off-topic. What you need to do is to setup Apache with name-based virtual host support. Of course you could place your sites in sub-directories, but you would be much happier with virtual hosts, i.e. one local 'domain' and www root per site.


Messages are kept in the user's session, which by default is stored in a database table called 'sessions'. If your database server dies partway through the page request, the messages may not get cleared from the session.

You can see the MySQL server failing when updating the sessions table in this image due to a max_allowed_packet error.

1M is a very small max_allowed_packet for a Drupal installation. You may need to ask your host to increase this limit. Alternatively, you could turn off dblog and use syslog instead, which sends your Drupal logs to a system daemon - but this may require your host to set up a syslog location for you.

There may be a module that implements hook_watchdog() that can save logs to a standard file. I can't find one, but if one exists, that could be a good option in your situation too.


How can I save arrays of values in the database?

I would use the following code.

foreach ($user_emails as $value) {
  $query = db_insert('banned_users');
  $query->fields(array('email' => $value))->execute();
}

Alternatively, you could use the following code.

$query = db_insert('banned_users')->fields(array('email'));

foreach ($user_emails as $value) {
  $query->values(array('email' => $value));
}

$query->execute();

With MySQL, the query uses the multi-value syntax.

With other databases, the executed queries will be one for each call to $query->values(), wrapped in a transaction. This means the queries will be rolled back when one of them fails. In fact, the code executed from InsertQuery::execute() is the following one.

  // Each insert happens in its own query in the degenerate case. However,
  // we wrap it in a transaction so that it is atomic where possible. On many
  // databases, such as SQLite, this is also a notable performance boost.
  $transaction = $this->connection->startTransaction();

  try {
    $sql = (string) $this;
    foreach ($this->insertValues as $insert_values) {
      $last_insert_id = $this->connection->query($sql, $insert_values, $this->queryOptions);
    }
  }
  catch (Exception $e) {
    // One of the INSERTs failed, rollback the whole batch.
    $transaction->rollback();
    // Rethrow the exception for the calling code.
    throw $e;
  }

In short, I would use the code you are using if the inserted values are independent from each other; I would use the code I shown when the values depend from each other.

In your case, the emails are independent from each other. If you would use the second snippet I shown, the database table will contains all the values, when the sub-query don't fail, or none when a single sub-query fails.

You could also use drupal_write_record(), even though I much prefer the other snippets.

foreach ($user_emails as $value) {
  drupal_write_record('banned_users', array('email' => $value));
}

I don't see any pro in using this snippet, though.

Reference

Insert queries


Passing variable from preprocess block to the block body

Your variable will be available in block.tpl.php. Consider making your own block like described on How to theme a custom block?. (You probably do not need hook_theme().)

Using PHP directly in blocks (via UI) is not the best practice: It slows your site down, as the block needs to be rendered with every request, when it comes to caching.


Appears the same orders in the admin/commerce/orders and in the admin/commerce/orders/carts

In views list, there is one view named "Orders". In this view two pages are available:

"Orders"
"Shopping carts"

In "Shopping carts" page, click on Commerce Order: Order state from filter criteria and select states for which you want to display records.

Let me know if you face any future query with this.

Thanks!


Nope, the taxonomy module can handle as many terms-per-vocab as your hardware will allow it to (within some reasonable theoretical bounds I'm sure, but certainly 140,000 terms would not be too much these days).

The 'problem' is in your server configuration. Quite simply you don't have enough available memory for the taxonomy module to process as many records as it needs to.

Try increasing the PHP memory_limit setting gradually and hopefully you'll be able to come to an acceptable compromise between your available memory and the size of your vocabularies.

Just to preempt what I think your response will be - you're already allocating 256MB, which might be a large (even outrageous) amount of maximum memory to give to a single PHP script, but the fact that you're getting out of memory errors means it's simply not enough for your site and needs to be increased (unless you want to optimise the core taxonomy module which I don't think would be much fun).

If you're on shared hosting, the first thing to do would be to get the site on a dedicated server/VM. That should make a good bit of difference.


Set maximum / disable custom block cache for anonymous users

This is a known issue Bubbling of elements' max-age to the page's headers and the page cache.

The Internal Page Cache is designed for database content, which is handled by cache tags. So a workaround would be to add a custom cache tag to the block

$build['#cache']['tags'][] = 'weather_forecast';

which will bubble up to the page level and so you can invalidate both cached items, block and page, in a cron job:

/**
 * Implements hook_cron().
 */
function mymodule_cron() {
  \Drupal\Core\Cache\Cache::invalidateTags(['weather_forecast']);
}

All credit goes to @Berdir: Cache max-age and varnish ESI


Assign a submitted Node to a Single User of Role Editor

I haven't test it, but the module's description seems to match your needs:

https://drupal.org/project/nodeaccess

Otherwise it can be done with a custom module: add a field "authorized editor" of type user reference to your content type, and then use the node_access function to grant access to the update operation to the user who is currently trying to edit it.


Programmatically log in user not working correctly

Template files are not the proper place for your code, since at this level the headers are (probably) already sent. That's why the session cannot be saved on the client browser.

You'd better implement hook_init() in a custom module

function YOURMODULE_init() {
  if (!user_is_logged_in()) {
    global $user;
    $user = user_load(31);
    user_login_finalize();
  }
}

  If I refresh the browser or visit another pages, I am logged in.

You are seeing the correct user ID on your debug output, just because you are printing the user id which you have loaded just 2 lines before. It doesn't mean that the user is successfully logged in.


Sample Images not showing (Omega Kickstart theme)

The Omega Kickstart is just a theme; it doesn't contain any module. You are probably interested in the Commerce Kickstart distribution, which contains the Drupal Commerce module, and any of its dependencies.

  Commerce Kickstart is the quickest way to get up and running with Drupal Commerce. It includes the latest versions of Drupal core, Drupal Commerce, and the other modules it depends on. It also gives you a set of options to create a fully-featured demo store out of the box complete with an attractive theme, catalog and search configuration, and a custom back office interface.


Views fields configuration is not working

Apparently you're not the only one to encounter this issue. Here are some similar situations:

https://www.drupal.org/node/2151785
Views UI doesn't provide links to expand fieldsets anymore

It appears that no one has found out the solution yet. It doesn't seem to come from jQuery Update or backend theme. However, these advices show up each time:

Make sure that the needed JavaScript file is loaded in the header of the node (collapsible.js)
Perhaps a conflict with another module that would use Views hook. Disable enabled modules one by one and test.

If you find which module interferes with Views or why JS file is not loaded, I think you will make more than one happy people.


Entity Translation's Language Switcher (Content) is not showing

if you want to activate the Language switcher for User or for Content you have to go to:

../admin/config/regional/language

Use the second tab "Detection and selection" and activate for "Language switcher user" the first section:

User interface text language detection - Enabled: YES

After that, you will see the language switcher.

For your "Language switcher content" you have to activate the other section:

Content language detection - Enabled: YES


How to validate a form against a custom user profile field?

Try with this code it is helpful for you

<?php

function mymodule_form_alter(&$form, &$form_state, &$form_id) {
      if ($form_id == 'form_id') {
    $form['#validate'][] = 'my_validation';
                                      }
                                                                }

function my_validation($node, $form, $form_state){

    if (!isset($form_state['values']['field_text']['und'][0]['field_text']['und'][0]['value']))
    {
        form_set_error('Text', 'Select text');
        }

}


Drupal 8 (like Drupal 7) uses PDO to communicate with databases.

With PDO, the DB API makes use of prepared statements, specifically to avoid SQL injection attacks.

Practically, this means that you should use the database API methods. If you use the select, update, delete methods directly, you have a better chance of avoiding SQL injection as everything will be parameterised.

If you use query, you need to be more careful, as the API can only protect you so much. For example, if you do this:

$sql = "SELECT uid FROM users WHERE name = '$_GET[name]'";
\Drupal::database->query($sql);

Then you deserve what you get :) You should always use this instead:

$sql = "SELECT uid FROM users WHERE name = :name";
\Drupal::database->query($sql, [':name' => $_GET['name']]);

Aside: In reality, you'll only see the 2 functions you mentioned being used in very old, practically obsolete code these days. The MySQL extension has been removed now, and stripslashes was traditionally used with magic quotes, which were deprecated in PHP 5.3. SQL injection is still very much a problem, but those 2 perhaps aren't the best to use for comparison in this day and age.


If you don't need the case studies to appear in the secondary nav/sidebar menu, you could try using the Path Breadcrumbs module to set custom rules for any of the following scenarios:

all "Case Study" content resides in a fixed hierarchy
"Case Study" content with a specific tag goes in a fixed hierarchy
"Case Study" content breadcrumbs are defined by url alias/path that reflects parent pages.

The module is rather flexible in the rulesets you can define.


Rules reacting on an event that hasn't happened?

Have a read of https://www.drupal.org/node/2403851 .

In short, Rules 2.8 is causing issues with Commerce. The module maintainers are aware and looking at the problem but until it is sorted they are suggesting rolling back to Rules 2.7.


Is there a view for top selling products, including product kits?

easyrec for ubercart module provides the functionality for most selling products(most bought items) and it also provide the following options as blocks.

Available Blocks

easyrec: other users also bought
easyrec: other users also viewed
easyrec: recommendations for user
easyrec: most bought items
easyrec: most viewed items

  To use the "easyrec for ubercart" module a shop owner needs access to
  an easyrec server. It's possible to register a free easyrec account at
  http://easyrec.org/ if the owner cannot host his/her own. After
  creating an account on the easyrec server and a 'tenant' account for
  the specific shop, the shop owner just copies the tenantId and apiKey
  into the drupal module's administration interface to enable
  recommendations for the ubercart shop.


Using Infinite Scroll module with Views paging: Detrimental to Google SEO?

No it's not detrimental (well, not in the way you're thinking at least) - the standard pager links are hidden with infinite scroll, but still in the markup, so there's no problem from that perspective. Google will find and visit the subsequent pages as with a normal views pager.

The only question is whether Google apply some sort of penalty to the pages linked to from those hidden links. But that's something you'd need to get out of Google :)


In an Aegir platform how do I change what modules drush enables when a site is created

Both requirements (auto enable modules and autopopulating users) can be done by Drupal install profiles or distributions. Install profiles are in Drupal, not in Aegir, but fits perfectly to Aegir.

In short, I recommend you to compile your install profile and use this profile in Aegir.

See more: http://drupal.org/project/distributions


I'd like to add a second "Save" button that saves the node as usual, but I can use a module to alter the node

I had to do this with a validate handler instead of a submit handler. I'm not sure of the implications of that but it works.

<?php

function custom_assignment_save_form_alter(&$form, $form_state, $form_id) {
    if ($form_id == "assignment_node_form") {
        $form['secondsubmit'] = array(
        '#type' => 'submit',
        '#value' => t('Save Progress'),
        '#weight' => 100,
        '#validate' => array('node_form_validate', 'custom_assignment_save_form_validate'),
        '#submit' => array('node_form_submit'),
      );
    }
}
function custom_assignment_save_form_validate($form, &$form_state) {
    form_set_value($form['field_boolean'], array(LANGUAGE_NONE => array(0 => array('value' => 1))), $form_state);
}

This simply changes a hidden boolean value when the Save Progress submit button is used.


Check to see if content exists; if not, create it

I think doing this with Rules alone, will work if you have a very limited set of nodes. Once you pass 100 or so, then the overhead of all the object wrappers will soon force you to give PHP gigabytes of RAM instead of megabytes, and then set your servers CPU aflame.

I belive an approach that integrates Rules with Views bulk operations however, could do this neatly for you.
I have not attemped anything similar myself, but a VBO should be able to query the database for the node, and then if it exists, return it to Rules.

The code approach would be to implement hook_node_presave, query the database with an EntityFieldQuery for a Box node with the right terms, and assign the reference.


Using a field for populating the meta-tags of view pages

Assuming Drupal 7:

You can go for implementing hook_page_alter() in your theme's template.php and use drupal_add_html_head() to insert your own metatags. Following the link you will find lots of exmples in the comments.


Just adjust the values of the form element to your needs. Check this http://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/6#select to see how selects ar build using FAPI.


Welcome to Drupal!

Take a look at https://drupal.org/project/modal_forms - this performs the functionality that you've described and works with https://drupal.org/project/webform which you can use to build the survey.

I also recommend taking a look at https://drupal.org/project/examples to learn more about module building in general; it includes many practical examples.

If you want to use an existing form, check out the tutorial at http://deeson-online.co.uk/labs/insert-form-pop-modal-ctools-and-drupal-7 that describes how to use CTools Modal with existing forms.


How to list similar products using views in Commerce Kickstart?

Try this

Create view (block)
Add fields (title, a small image, date, whatever you like). Or teasers, what works as well.
“Arguments” is from now on called “Contextual filters”, so go there.
Add the filters: “Content: Has taxonomy term ID (with depth)” and “Content: Has taxonomy term ID depth modifier”
Configuration on this filter: → When the filter value is NOT in the URL: → Provide default value → Type: Taxonomy Term ID from URL → under that, check the box “Load default filter from node page, that’s good for related taxonomy blocks.” → now check the boxes of the taxonomies you want involved here
Now you need to add the second filter in order to exclude the current node from the list. Click [+] button of the contextual filters section.
Select Content: Nid
Set the ‘when argument is not present’ to ‘Provide default argument’
Set the ‘Default argument type’ to ‘Content ID from URL’
Go to “MORE” , and check the “Exclude” box.
Move the filter “Content: Nid” to the top position.
Add a block to your view and embed the block on your node pages
Save your view


I'm not entirely sure which one better fits your use case:
This blog post has an excellent way to accomplish product suggestions using the Radioactivity module.  http://www.wunderkraut.com/blog/drupal-commerce-product-suggestions-with-radioactivity/2013-08-22

There is also the Commerce Recommender module:  https://www.drupal.org/project/commerce_rec.
Again, I'm not sure if that is precisely what you're after.

A really straightforward way I could see is create a commerce product view that filters down to only products with the same taxonomy terms on the current article, create a block to hold that view, and display those products with/without their Add to Cart buttons.


How can I display a Browser Prompt for Confirmation before executing ajax callback for a button element?

This one should help you the same way you want to achieve the functionality.
Instead of ajax callback I have created a ctools modal which will return the delete and cancel button..

"delete/nojs/1" where 1 will be the Item which you want to delete.

use this in your form.

$form['delete'] = array(
  '#markup' => ctools_modal_text_button(t('Delete'),"delete/nojs/1", t('Delete'), 'ctools-modal-modal-popup-small'),
);

create a menu item.

function custom_module_menu() {
  $items = array();
  $items['delete/%ctools_js/%'] = array(
    'type' => MENU_CALLBACK,
    'title' => t('Delete'),
    'page callback' => 'delete_something',
    'page arguments' => array(1,2),
    'access callback' => TRUE,
  );
  return $items;
}

and call this function.

function delete_something($js = NULL) {
  if (!$js) {
    return drupal_get_form('delete_form');
  }
  ctools_include('modal');
  ctools_include('ajax');
  $form_state = array(
    'title' => t('Delete'),
    'ajax' => TRUE,
  );
  $output = ctools_modal_form_wrapper('delete_form', $form_state);
  if (empty($output)) {
    $output[] = ctools_ajax_command_reload();
  }
  print ajax_render($output);
  drupal_exit();
}

function delete_form($form_state = NULL){
  $form['message'] = array(
    '#prefix' => '
',
    '#value' => t('Are you sure want to delete?'),
    '#suffix' => '
',
  );
  $form['submit']['delete'] = array(
    '#prefix' => "
",
    '#suffix' => "
",
    '#value' => t('Delete'),
    '#type' => 'submit',
    '#submit' => array('delete_form_submit'),
  );
  $form['submit']['cancel'] = array(
    '#prefix' => "
",
    '#suffix' => "
",
    '#value' => t('Cancel'),
    '#type' => 'submit',
  );
  return $form;
}

function delete_form_submit($form, &$form_state) {
 //some code to delete
}


Give a try to User Points Contributed module: This module includes the module called userpoints_nodelimit which enables a limit on node creation based on user points.

However if you want to do it with the userpoints and rules module than the idea would be to create the rule to grant certain point on publishing the new nodes, and than create another rule whose event would be the node creation and in the condition  check if the user already has reached limit than prevent node creation and display the custom message.

Alternatively one easy way to achieve the same is using the hook_node_validate(), one example of using the same is as below:

/**
 * Implements hook_node_validate().
 */
function MyModule_node_validate($node, $form, &$form_state) {
  // For now assign the static value to MAX_NODES (No. of nodes),
  // however you can make it dynamic, and get those values using variable_get().
  $max_nodes = 'MAX_NODES';
  $node_count = 0;

  // Get the user uid from the global user variable.
  global $user;
  $user_id = $user->uid;

  if ((isset($node->uid))) {
    // Use entity query to get the number of nodes already published by this user.
    $query = new EntityFieldQuery;
    $node_count = $query->entityCondition('entity_type', 'node')
      ->propertyCondition('uid', $user_id)
      ->propertyCondition('status', 1)
      ->count()
      ->execute();

    // Check if the node count exceeds the max_node value.
    if ($node_count > $max_nodes) {
      form_set_error('FIELD_NAME', t('Reached the maximum limit of creation of nodes.'));
    }
  }
}


Links in view - wrong language selection

I found the solution here after one day struggling with same issue:

goto: Home » Administration » Configuration » Regional and language » Languages.
select the 'DETECTION AND SELECTION' tab.
Un-check all except 'URL' and 'default'. Keep 'URL' on top of 'default'


How to alter breadcrumbs from my controller in my module?

To customize your Breadcrumbs you need to take full control of the Breadcrumb for that particular route with your own Breadcrumb Builder service.

To do this, you need to create an entry in your module/profile services file:

e.g., mymodule/mymodule.services.yml

services:
  mymodule.breadcrumb:
    class: Drupal\mymodule\MyModuleBreadcrumbBuilder
    tags:
      - { name: breadcrumb_builder, priority: 100 }

You then need to create your Breadcrumb Builder class

e.g. mymodule/src/MyModuleBreadcrumbBuilder.php

<?php

/**
 * @file
 * Contains Drupal\mymodule\MyModuleBreadcrumbBuilder.
 */

namespace Drupal\mymodule;

use Drupal\Core\Breadcrumb\Breadcrumb;
use Drupal\Core\Breadcrumb\BreadcrumbBuilderInterface;
use Drupal\Core\Link;
use Drupal\Core\Routing\RouteMatchInterface;

/**
 * Class MyModuleBreadcrumbBuilder.
 *
 * @package Drupal\mymodule
 */
class MyModuleBreadcrumbBuilder implements BreadcrumbBuilderInterface {

  /**
   * {@inheritdoc}
   */
  public function applies(RouteMatchInterface $route_match) {
    $route = $route_match->getCurrentRouteMatch();

    // Add conditionals that return TRUE when the current route should have it's
    // breadcrumb handled here.
    return FALSE;
  }

  /**
   * {@inheritdoc}
   */
  public function build(RouteMatchInterface $route_match) {
    $breadcrumb = new Breadcrumb();
    $breadcrumb->addCacheContexts(['route']);

    // Add logic here that builds up the breadcrumbs based on desired behaviour.
    $links[] = Link::createFromRoute(t('Home'), '<front>');

    $breadcrumb->setLinks($links);

    return $breadcrumb;
  }

}

The applies method is where you register this Breadcrumb Builder to be used for the particular route, so build a conditional there that matches your route(s) and returns TRUE.

The build method is where you build your Breadcrumb for any routes that applies returns TRUE, so if you are dealing with multiple routes you will need to build the appropriate logic here to build said Breadcrumbs.

I recommend reading through Palantir's blog post for more background and details: https://www.palantir.net/blog/d8ftw-breadcrumbs-work


Is drush required on the remote server to do sql-sync or rsync operations?

Drush is needed on the remote server only to fetch the database credentials for the remote system.  If you declare your databases array in the site alias for your remote systems, then Drush will not need to have Drush installed on the remote machine to work.

I don't remember if I explained this in detail in the book, but there is an example on how to define database records in aliases in the example alias configuration file, example.aliases.drushrc.php.  Also, try running drush @site sa --with-db to see the whole site alias record for the given site with the databases array included.  This won't help you if Drush is not installed on the system where the site is installed, but you can run it on a local site, and edit the result to match the necessary settings for the remote end.


How to make a chart in Views with date as x-axis (using the charts module)?

Within the Charts module, there is an interesting issue about this, i.e. Graph node input over time (support date formatting on a continuous axis).

In Comment #3 of that issue is stated: 'The trouble here is that neither Views nor Date modules provide aggregation options for date-based fields.'. The patch(es) included in this issue are expected to soon be applied.


Why I can't use the same code from Drupal 7 in Drupal 8 to generate a button with FAPI?

The reason why it is not working in Drupal 8 as in Drupal 7 is, that prefix and suffix are passed to xssFilterAdminIfUnsafe() function in doRender() function. Thus preventing all tags except the tags specified in $adminTags.

Excerpt from doRender:

  // We store the resulting output in $elements['#markup'], to be consistent
  // with how render cached output gets stored. This ensures that placeholder
  // replacement logic gets the same data to work with, no matter if #cache is
  // disabled, #cache is enabled, there is a cache hit or miss.
  $prefix = isset($elements['#prefix']) ? $this->xssFilterAdminIfUnsafe($elements['#prefix']) : '';
  $suffix = isset($elements['#suffix']) ? $this->xssFilterAdminIfUnsafe($elements['#suffix']) : '';

  $elements['#markup'] = Markup::create($prefix . $elements['#children'] . $suffix);

You can use '#allowed_tags' property to enable specific tags. So this should work:

  $form['submit'] = array(
  '#type' => 'markup',
  '#markup' => "<button type ='submit'><span>" . t('Login') . "</span></button>",
  '#allowed_tags' => ['button', 'span'],
  );

But '#allowed_tags' property will not work for '#prefix' and '#suffix'.


Adding additional dynamic to a canonical view

This would be the answer to the two questions:

1) add additional HTML to the canonical view

When using hook_ENTITY_TYPE_view() you have a render array and you can place new array keys with additional render elements. Don't use echo for testing, put it in the build array like this:

$build['text1'] = ['#markup' => '
Text 1
'];

2) add a form to the canonical view

Build a form class for this form. Then you can place the form also in hook_ENTITY_TYPE_view():

$build['myform'] = \Drupal::formBuilder()->getForm('Drupal\mymodule\Form\MyForm');

You can pass additional parameters in getForm(), if you need information from the entity to build the form.

I don't understand what you are trying to do with Drupal\views\EntityViewsData. Other than mentioning this one class you are not writing anything else about views.


Popup w/overlay for content (Lightbox-esque)

See this question: Display node as a popup window

"There are a lot of solutions for this kind of stuff. I would do it in the theme layer to have something really light. You can also use the variety of popup modules for this. One simple way to do this, is use the Lightbox2 module, checkout this documentation page: http://drupal.org/node/252260"


Commerce kickstart select country and don't show product

Your best bet is to add a hook_form_alter and modify the commerce add to cart form to remove the button and/or change it up to your liking:

/**
 * Implements hook_form_alter()
 */
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if (strpos($form_id, 'cart_add_to_cart') === 0) {
    if (/* Insert your logic here */) {
      unset($form['submit']);
      $form['submit'] = array('#markup' => '
Not available in your country
');
    }
  }
}


How to display an alternative text if the comments are closed for the node?

Assuming you're using the default field definitions installed by the standard profile, what you want is the status property of the comment field of the node, which is accessible in twig via node.comment.status.

{% if node.comment.status == 2 %}
   {# comments are open #}
{% elseif node.comment.status == 1 %}
   {# comments are closed & visible #}
{% elseif node.comment.status == 0 %}
   {# comments are closed & hidden #}
{% endif %}


Upload large file to azure storage and link it in Drupal

How about the Remote File Source module?

  Remote File Source allows you to add a file from a remote server to a filefield without transferring it locally.

I haven't tried it, but it looks stable with only a couple of bugs


Show block for pages of every content type but one; including the front page

The Context module is perfect for this task.

Download and enable the Context module and add a new context under Structure -> Context
Add a 'Path' condition and set it to <front> http://d.pr/i/x4R5
Add a 'Node type' condition and check every node type, except the one where you don't want your block to show http://d.pr/i/PSO4
Add a reaction called 'Blocks', on the right check the block you want to show when the first to conditions are met, and click 'Add+' next to the region where you want your block to show. http://d.pr/i/a3RG
Save the context and that's it

Also make sure to leave 'Require all conditions' unchecked so the context will activate if the first or second condition is met.


Drupal's Form API is complex but gives you lot of things: is secure, is extensible, is themeable. Indeed is more difficult than coding a simple HTML form, but with a simpel HTML form you have a simple functionality: just that simple HTML form.

Form API generates the form HTML element and handles the POST requests, and validate and submithandlers, you don't and you shouldn't code your own HTML form.

I recommend you to read the Drupal 6 Form API Quickstart Guide. Drupal 7 form handling is pretty the same, but check the Drupal 7 Form API Reference and Form API Internal Workflow Illustration.

In the other hand you may prefer to use a module that address what you need without coding, that's a faceted search: Facet API. From its documentation page:

  Faceted search allows our search results to be filtered by defined
  criteria like category, date, author, location, or anything else that
  can come out of a field. We call these criteria facets. With facets,
  you can narrow down your search more and more until you get to the
  desired results.


Drupal 7 : I want "Access Denied on Node but Title listing in view"

Using view you can achieve this functionality,

In you view go to Query settings in others tab, In the popup select Disable SQL rewriting

This is what views says about this option

Disabling SQL rewriting will disable node_access checks as well as other
modules that implement hook_query_alter().

Then Content access will not able to alter this query, so your users who don't have permission to view the particular content type also can see the views results

While When they are trying to access the node, on that time content access will not allow them to see that node.

Hope this helps.


Under Page settings, in the view settings, you will find the Menu option; you need to set it to:

Menu tab for user/%/content
Default menu tab for user/%/content/published
Menu tab for user/%/content/unpublished

This is how it appears.

PS

I used the Tracker view that comes with the Views module, and altered it to obtain the desired result.


When I am logged-in the page doesn't look the same as when I am logged-off

What you see / notice is pretty standard Drupal ... The link like "Add content" is something you typically only want to be shown for logged in user (and maybe even limited to users with roles such as "content editor" (or whatever you'd call it). Also, the small icons in the upper left (above "logo" and "home") are typically also things you only should be able to use if you are logged in.

Should you want to change any of such things (eg: anonymous users should also be able to "add content"), then it's just a matter of finding out which permission it is that actually governs the specific function (such as "add content"), and then indicate in your "permissions" page within admin that is related to it that you want "role" anonymous to have the very same permission.


Use Token in contact form as default value

Usually this is done in hook_form_contact_site_form_alter, like this:

function YOUR_MODULE_form_contact_site_form_alter(&$form, &$form_state) {
      $args = \Drupal::request()->query->all();
      $form['subject']['#default_value'] = $args['foo'];
}


Language detection by domain breaks ajax requests over https

The problem is the CDN, which connects to Drupal via HTTP and to the client via HTTPS. Then all absolute URLs generated by Drupal have the wrong protocol. Not only this one for ajax, which is absolute because you've switched language detection to domain based. Prefix based it uses relative paths and then the protocol doesn't matter.

Normally CDN's add a header X_FORWARDED_PROTO to the request, which Drupal can use to determine the correct protocol. For this to work you have to configure the CDN as reverse proxy in settings.php.


I suggest truncate watchdog table, usually this table growth very quick.( maybe you can first  get a backup of this table then truncate(empty) it)

( maybe trucnate cache tables be useful but If you see table size u will see the watchdog have biggest size )


Firstly you must make all users users and not nodes. Somebody I know recently had an issue where users didn't have email addresses. His solution was to create fake email ids for those users since having an email id is mandatory for an account on a Drupal site.
Once you have everyone as users, I think you can add relationships between users using this module - User Relationships and hence easily show related users in views.


As you mention you're looking for setting the profile as default, I'm assuming you're using Commerce Addressbook or in any case looking for a very similar feature of what that module provides.

  Commerce Addressbook is a module that allows authenticated customers to reuse
  previously entered addresses during checkout.
  They can manage all entered addresses in their user panel (user/%user/addressbook).

You can use commerce_addressbook_set_default_profile function to set the default (one per type). Example:

$billing_profile = commerce_customer_profile_new('billing', $user->uid);
  $billing_profile->commerce_customer_address[LANGUAGE_NONE][0]['name_line'] = 'Sample Customer';
  $billing_profile->commerce_customer_address[LANGUAGE_NONE][0]['country'] = 'US';
  $billing_profile->commerce_customer_address[LANGUAGE_NONE][0]['thoroughfare'] = '16 Hampton Ct';
  $billing_profile->commerce_customer_address[LANGUAGE_NONE][0]['locality'] = 'Visalia';
  $billing_profile->commerce_customer_address[LANGUAGE_NONE][0]['administrative_area'] = 'CA';
  $billing_profile->commerce_customer_address[LANGUAGE_NONE][0]['postal_code'] = '93277-8329';
  commerce_customer_profile_save($billing_profile);
  commerce_addressbook_set_default_profile($billing_profile);

I'd recommend another way to create the profile, for example:

    // Create the new profile now.
    $profile = commerce_customer_profile_new('billing', $order->uid);

    // Add the address value.
    $profile_wrapper = entity_metadata_wrapper('commerce_customer_profile', $profile);

    $profile_wrapper->commerce_customer_address = array_merge(addressfield_default_values(), array(
      'country' => $country,
      'name_line' => $name . ' ' . $last_name,
      'first_name' => $first_name,
      'last_name' => $last_name,
    ));

    // Save the profile.
    $profile_wrapper->save();


After D8-rc1 install, homepage work but all other links gives a "page not found"

I fixed this.. Thanks to Sumit, I read the .htaccess file more carefully.. Inside the default .htaccess file that comes with the Drupal 8 download, around line 108, comments tells what to do if d8 is installed in a sub-directory instead of document root. I modified line to "RewriteBase /newD8" and now the site works. Even though the same comment is in the D7 version too, On the same Apache server and same document root, D7 works without the modification of the line but D8 needs the change. I don't know why. Because of Symfony perhaps?


Help! Can't Login - Accidently set Omega content zone to not display in content section

You can generate a one-time login link.

drush uli


Is it possible to allow duplicate usernames ?

There is no setting or existing module that will do this for you.  I do not think it is a good idea to let two users share the same username, because there is so much in Drupal that depends on usernames being unique, and this will break if you make two usernames identical.

You do not tell us why you want to have this feature.  However, if you are content with letting users authenticate using their email address (which is guaranteed to be unique), rather than their username, the Email registration module may solve your problem.

However, the Email registration module does not let the user pick his or her own username, but generates an unique username based upon the email address.  I want my users to pick their own username, so I use a variant of Email registration that does this.  It is named RealnameReg.  It is a sandbox, but since it is based on Email registration it is stable. I am using it myself on several production sites.


How to create a view to display only child nodes of a parent term?

I dont think that this way is possible,but a situation near to this is possible as:-
1. While creating a view,we have a field known as "filter criteria" field,in that add --*Content: Has taxonomy terms (with depth) (or Unknown) *

Go into the settings of this field*strong text* and choose depth of the field.**
Here Depth means-The depth will match nodes tagged with terms in the hierarchy. For example, if you have the term "fruit" and a child term "apple", with a depth of 1 (or higher) then filtering for the term "fruit" will get nodes that are tagged with "apple" as well as "fruit". If negative, the reverse is true; searching for "apple" will also pick up nodes tagged with "fruit" if depth is -1 (or lower).**
this can be of help if u don't mark any node with the fruit tag,but mark all nodes with the some children tags of fruit.


You want to use template_preprocess_views_view (see views theme functions)

function MYTHEME_preprocess_views_view(&$variables) {
  $view = $variables['view'];
  if ($view->name == 'my_view_name') {
    // add your variables here
    $variables['YOUR_VARIABLE'] = 'value';
  }
}

$YOUR_VARIABLE should be available in your template file.


Ajax error on dependent dropdown. Drupal 7

You need to remove the line

'#options' => _ajax_example_get_second_dropdown_options($selected),

Then, put your function call and update the #options on some condition. So, something like this:

if(isset($form_state['values']['first_select_box'])) {
  if($form_state['values']['first_select_box'] == 'something'){
    //the contents of your _ajax_example_get_second_dropdown_options function here
    //and instead of returning something... just SET #options to your new output.
    $form['second_select_box']['#options'] = 'new stuff';
  }
}

Furthermore, most of the time people will not even show the second select box until the first one is filled out with something useful for the second. In that case, you can set the #type of the second select box to 'markup' and then in that above if statement SET the #type to select.

$form['second_select_box'] = array(
  '#type' => 'markup',
  '#prefix' => '
',
  '#suffix' => '
',
);

if(isset($form_state['values']['first_select_box'])) {
  if($form_state['values']['first_select_box'] == 'something'){
    //the contents of your _ajax_example_get_second_dropdown_options function here
    //and instead of returning something... just SET #options to your new output.
    $form['second_select_box']['#type'] = 'select';
    $form['second_select_box']['#options'] = 'new stuff';
    $form['second_select_box']['#title'] => 'Choose';
  }
}


Sorry, I didn't find this issue before, it has been already reported here Set Update Manager to install to sites/all/modules/contrib?

I knew about drush, but I was wondering if it could be done with the update-manager.


How to make exposed filters to hide filed with no value

The below code comes from a current project of mine. I've made it more generic for your purposes, so it's untested. You'd need to modify the query depending on your usage - it's going to throw errors if you use as-is.

<?php
// Add this to a custom module, replace "mymodule" with your module name
function mymodule_form_views_exposed_form_alter(&$form, &$form_state) {
  //dsm($form); // Display available form vars
  $field_id = 'id_assigned_in_views'; // Change for the field ID in question.
  // Only alter forms with the necessary field.
  if (isset($form[$field_id])) {
    // Do your entity_field_query or db_query here
    $query = new EntityFieldQuery();
    $query->entityCondition('entity_type', 'taxonomy_term')
      ->entityCondition('bundle', array('tags'))
      ->propertyOrderBy('weight');
    $result = $query->execute();
    $terms = $result['taxonomy_term'];
    // Add a default so the filter is optional.
    $options = array('' => t('- All -'));
    foreach($terms as $tid=>$term) {
      //dpm($term);
      $options[$tid] = $term->name;
    }
    // Alter the field.
    $form[$field_id]['#type'] = 'select';
    $form[$field_id]['#options'] = $options;
    $form[$field_id]['#size'] = 1;
  }
}
?>


Can't programmatically fill address field on taxonomy term creation

You need to provide the country_code to your address field.

like

$city = [
  'zip' => 1000,
  'name' => 'Lausanne',
  'lat' => '47.3879577',
  'lng' => '8.044136',
];

$term = Term::create([
  'name' => $city['zip'].' '.$city['name'],
  'vid' => 'cities',
  'field_cities_zip_city' => [
    'country_code' => 'CH',  // country code is required
    'postal_code' => $city['zip'],
    'locality' => $city['name'],
  ],
]);
$term->save();


Webform Conditional is not firing when using a hidden field

Following up on my response above, things like FAPI autocomplete_path and as your seeing webform conditional (i think) use the States API. Which is a limited version of scriptable javascript API from within Drupal7.

Drupal does ship with jQuery UI built in. And you can make direct usage of jQuery to alter/modify forms directly using drupal core components -- such as the bundle standard jquery packages that come with Drupal 7. Want a working jqueryui autocomplete example as an example -- here's 1 in Russian (Google translate works well here):

http://serho.ru/notes/raznoe/jquery-ui-autocomplete-widget-v-forme-drupal-7

I realize your request may be a non-coding module only solution; but such modules and APIs basically have limits as you've seen. There are pieces of drupal core that exist to let you homegrow your own solution.


Replace existing content type with feature

Yes, it is possible to enable the feature. Enabling the custom feature module does not change anything on the site. The feature will have a different state depending on if the code in the feature module differs from what is stored in the database. A quick way to check the state of your features is the drush command:

drush fl

If your custom feature's components are simply the content type, and assuming field_base and field_instance components, then enabling the feature will tell you if they are either:

Overridden: the components (content type settings, field settings) are different in the database and the custom feature code.
Default: the components in the custom feature code are the same as the settings in the database.

If your custom feature is "Overridden" you have two options:

Update: drush fu featurename - Updating your feature will update the custom feature code with the settings that are stored in the database.
Revert: drush fr featurename - Reverting your feature will restore the feature's component's settings in the database to what is stored in the custom feature module's code.

So, either way, this shouldn't affect your node content. Unless you revert your feature components thus affecting the content type or field settings.

See the drupal.org documentation for more on using features & drush: https://www.drupal.org/node/960926


How to Group the same content into one in View?

Look the Archive view /archive it will give you solution.


How I do I remove the User menu from the top right corner?

In admin/structure/menu/settings, you select which is the source for the Main links, and the Secondary links.

By default, the source for the Secondary links is the User menu; if you set it to No Secondary links, or another menu, the user links will disappear from the page.


Assign custom id for user on registering

I presume you're referring to a login ID - you should be able to use hook_form_alter to access the registration form, and create a default value.

get Devel module and use dpm($form) in that function to look through the array to find the exact element you want to change.

after that you can probably use a number of options to hide the element, including css so that the user can't change it before being submitted.


I use Display Suite to arrange elements and css to style elements. You can create your own template layout in display suite if you need it.


Have you tried setting up development.services.yml?

Put this next to your sites.php.

development.services.yml:

# Local development services.
#
# Place this file in the /sites/ directory.
#
# To activate this feature, follow the instructions at the top of the
# 'example.settings.local.php' file, which sits next to this file.
services:
  cache.backend.null:
    class: Drupal\Core\Cache\NullBackendFactory
parameters:
  http.response.debug_cacheability_headers: true
  twig.config:
    # Twig debugging:
    #
    # When debugging is enabled:
    # - The markup of each Twig template is surrounded by HTML comments that
    #   contain theming information, such as template file name suggestions.
    # - Note that this debugging markup will cause automated tests that directly
    #   check rendered HTML to fail. When running automated tests, 'debug'
    #   should be set to FALSE.
    # - The dump() function can be used in Twig templates to output information
    #   about template variables.
    # - Twig templates are automatically recompiled whenever the source code
    #   changes (see auto_reload below).
    #
    # For more information about debugging Twig templates, see
    # https://www.drupal.org/node/1906392.
    #
    # Not recommended in production environments
    # @default false
    debug: true
    # Twig auto-reload:
    #
    # Automatically recompile Twig templates whenever the source code changes.
    # If you don't provide a value for auto_reload, it will be determined
    # based on the value of debug.
    #
    # Not recommended in production environments
    # @default null
    auto_reload: auto_reload
    # Twig cache:
    #
    # By default, Twig templates will be compiled and stored in the filesystem
    # to increase performance. Disabling the Twig cache will recompile the
    # templates from source each time they are used. In most cases the
    # auto_reload setting above should be enabled rather than disabling the
    # Twig cache.
    #
    # Not recommended in production environments
    # @default true
    cache: false

Then in your settings.php, or preferrably your settings.local.php add this line:

$settings['container_yamls'][] = DRUPAL_ROOT . '/sites/development.services.yml';


Assuming that you are using D7. Go to /admin/structure/types and select your content type.

Under the 'Manage display' tab, find the body field, and set the label to 'Hidden'. The field label will not display. You may have to repeat this for each display type (default, teaser etc.).


In Service Module API, Some hooks are presents to help you.
You need to alter or add your own implementation of this service.

The second link is a file where you have the default service implementation.
You can try to alter this configuration with your own by using "hook_services_resources_alter".

I can't test but you can try and custom this snippet :

function YOUR_MODULE_services_resources_alter(&$resources, &$endpoint) {
    $['node']['operations']['retrieve']['callback'] = '_your_retreive_method';
    $['node']['operations']['retrieve']['args']     = array(
        'name' => 'node_alias',
        'optional' => FALSE,
        'source' => array('path' => 0), // Put your path index here
        'type' => 'string',
        'description' => 'The alias node to get',
    );
}

function _your_retreive_method($node_alias){
    // transform your alias to nid
    $path   = drupal_get_normal_path($node_alias);
    if($path !== $node_alias && ctype_digit($nid = str_replace('node/','',$path))){
        return _node_resource_retrieve($nid);
    }
    return false;
}

Links :

Service API Docs
File with an implementation of a service


Drupal Commerce - Update profile on order without cloning?

How about something like this leveraging Drupal's Entity API:

//assume we retrieved the $order_id via a page callback argument or something similar
$my_order = entity_load('commerce_order', array($order_id));

$billing_profile_id = $my_order[$order_id]->commerce_customer_billing[LANGUAGE_NONE][0]['profile_id'];
$billing_profile = entity_load('commerce_customer_profile', array($billing_profile_id));

// **replace this comment with PHP logic to update the profile values**

//save our customer profile object using the updated values from logic above
$success = entity_save('commerce_customer_profile', $billing_profile[$billing_profile_id]);

This allows us to directly edit the customer profile object associated with a particular order, and leaves the rest of the profiles unaffected.


Limit the number of uploads per image field depending of role

Solution1 Limit on the form:

function <module>_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'center_node_form') {
    global $user;
    // Only allow to upload 2 images for role = staff
    if (in_array('staff', $user->roles)) {
      $center_image_limit = 2;
      $form['#field_info']['field_center_image']['multiple'] = $center_image_limit;
      $i = 1;
      foreach ($form['field_center_image'] as $key => $value) {
        if (is_numeric($key)) {
          if ($i > $center_image_limit) {
            unset($form['field_center_image'][$key]);
          }
          $i++;
        }
      }
    }
  }
}

Source: DRUPAL – LIMIT THE NUMBER OF VALUES OF A CONTENT TYPE FIELD BY ROLE @ 1

Solution2 Limit in validation:

function <module>_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'center_node_form') {
    // Add the extra validation
    array_unshift($form['#validate'], '<module>_addtional_validate');
  }
}

function <module>_addtional_validate($form, $form_state) {
  $count = 0;
  foreach($form_state['values']['field_center_video'] as $video) {
    if (!empty($video['value'])) {
      $count++;
    }
  }

  global $user;
  // Only allow to upload 2 videos for role = staff
  if (in_array('staff', $user->roles)) {
    if ($count > 2) {
      form_set_error('field_center_video', t('You cannot upload more than 2 videos'));
    }
  }
}

Source: DRUPAL – LIMIT THE NUMBER OF VALUES OF A CONTENT TYPE FIELD BY ROLE @ 2


Is there a way to alter the implementation of a hook given by a third-party module, or a core module?

You can use hook_module_implements_alter() to alter the list of modules which implement a given hook. So just implement the hook in your module too and then remove the one from the module you want to replace.

Note that this hook should be used very carefully, you can do really weird stuff with it which will make it very hard to maintain and understand, among other things.


How can I generate custom XML for a SOAP client?

This is how I've done it:

some-feed.html.twig

<?xml version="1.0" encoding="utf-8"?>
<rss xmlns:atom="http://www.w3.org/2005/Atom" version="2.0">
  <channel>
    <atom:link href="{{ some_variable_set_in_preprocess }}" rel="self" type="application/rss+xml"/>
      /* -- rest of feed omitted */
  </channel>
</rss>

Then hook_theme() to register the template:

function hook_theme() {
  return [
    'some_feed' => [
      'render element' => 'elements',
      'template' => 'some-feed',
    ],
  ];
}

You can then generate a response with that theme:

$build = [
  '#theme' => 'some_feed',
];

$response = new \Symfony\Component\HttpFoundation\Response();
$xml = \Drupal::service('renderer')->renderRoot($build);
$response->setContent($xml);
$response->headers->set('Content-Type', 'text/xml');

You now have a Response object to work with. Depending on where you are working, you can return that, or set it as a response.


How to show conditional tab in webform 7.x-3.x

If you specifically want to use this within webform you need to use webform conditional to work smoothly.


Although this is not related to Drupal but anyway you must convert from XML to array by using the sample code below from PHP.net

$simple = "<para><note>simple note</note></para>";
$p = xml_parser_create();
xml_parse_into_struct($p, $simple, $vals, $index);
xml_parser_free($p);
echo "Index array\n";
print_r($index);
echo "\nVals array\n";
print_r($vals);

Ref: xml_parse_into_struct — Parse XML data into an array structure


How to use dependency injection for Plugins/Blocks [\Drupal::formbuilder() and \Drupal::config()]?

For future reference, from the link by @Kevin:

  The key to making plugins use dependency injection is to implement the
  ContainerFactoryPluginInterface. When plugins are created, the code
  first checks if the plugin implements this interface. If it does, it
  uses the create() and __construct() pattern, if not, it uses just the
  __construct() pattern. - From Acquia's Lesson 11.4 - Dependency injection and plugins

The example code below is written by Mart Matsoo from Chromatic. Please check the full article here: https://chromatichq.com/blog/dependency-injection-drupal-8-plugins. As @Kevin already mentioned in the comments it is a great article about Depencency Injection in Plugins.

Dependency Injection example in a block

Note the injection of the 'current_user' service via $container->get('current_user') in the create() method. You can pass extra services there.

<?php

namespace Drupal\heytaco\Plugin\Block;

use Drupal\Core\Session\AccountProxy;
use Drupal\Core\Session\AccountProxyInterface;
use Drupal\Core\Block\BlockBase;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Provides a Hey Taco Results Block
 *
 * @Block(
 *   id = "heytaco_block",
 *   admin_label = @Translation("HeyTaco! Leaderboard"),
 * )
 */
class HeyTacoBlock extends BlockBase implements ContainerFactoryPluginInterface {

  /**
   * @var $account \Drupal\Core\Session\AccountProxyInterface
   */
  protected $account;

  /**
   * @param \Symfony\Component\DependencyInjection\ContainerInterface $container
   * @param array $configuration
   * @param string $plugin_id
   * @param mixed $plugin_definition
   *
   * @return static
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static(
      $configuration,
      $plugin_id,
      $plugin_definition,
      $container->get('current_user')
    );
  }

  /**
   * @param array $configuration
   * @param string $plugin_id
   * @param mixed $plugin_definition
   * @param \Drupal\Core\Session\AccountProxyInterface $account
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition, AccountProxyInterface $account) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);
    $this->account = $account;
  }

Dependency Injection example in a controller

The same concept applies here, pass extra services via $container->get() in the create() method.

<?php

namespace Drupal\heytaco\Controller;

use Drupal\Core\Session\AccountInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\Controller\ControllerBase;

/**
 * Controller routines for HeyTaco! block.
 */
class HeyTacoController extends ControllerBase {

  protected $account;

  public function __construct(AccountInterface $account) {
    $this->account = $account;
  }

  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('current_user')
    );
  }


when mouseover on username display popup views

Hope this will help you

In Drupal 7, for your requirement you can use qTip (Stylish jQuery Tooltips) module with Views.

After installing and configuring qTip, go through the qtip examples(refer qtip README.txt).
For this example I have created a view with some user fields, these fields will popup on hovering user picture
Create a new view and add fields which you want to show on the popup.

For showing user information in popup, you need to give the proper structure(read qtip README.txt).
I have added the HTML structure for profile_image view field

On mouse hover of the user picture, user information will popup. And make CSS changes as per your requirement.
You can also refer BeautyTips, for example you can refer this link

Drupal 7 : Ajax load

Steps

To show user details on hover you need to add attributes to the username, it can be done using preprocess function template_preprocess_username in your active theme tempalte file.

function themeName_preprocess_username(&$variables) {
  $variables['attributes_array'] = array('class' => array("user-info"), 'data-uid' => $variables['account']->uid);//adding more attributes for your requirement
}

Create a view with the fields you want to show on popup.
Create a menu to get user details like get/user_details/%, where % is the user-id. This menu will returns user details.

function test_menu() {
...
$items['get/user_details/%'] = array(
'title' => t(''),
'type' => MENU_CALLBACK,
'page callback' => 'get_user_details_ajax_callback',
'page arguments' => array(2),
'access arguments' => array('access content'),
);
...
return $items;
}
//Implement the ajax callback to get user details
function get_user_details_ajax_callback ($uid) {
$html = '';
$html = views_embed_view('VIEWNAME','display_id', $uid);
return $html;
}

For showing the user details on hover, you need to make a ajax call using
$.ajax
Once the user hover the username get the data-uid attribute and make a ajax call to get user info.
Once you get the user details append it and show as popup.

Drupal.behaviors.getUserDetails = {
    attach: function (context, settings) {
      var replace_wrapper = 'user-'+$(this).attr('data-uid')+'details';
      //add html to show user details
      $( "a.user-info" ).each(function( index ) {
        if(!$(this).closest('div').hasClass('user-details-wrapper')){

      $(this).append("

");
    }
  });
  $('a.user-info').mouseenter(function(){
    if($(replace_wrapper).is(':empty')){//if empty then make ajax call and
      var url = Drupal.settings.basePath + 'get/user_info/'+ $(this).attr('data-uid');
      $.ajax({
        url: url,
        type: 'GET',
        success: function (data) {
          //create html and append to replace_wrapper
          var user_detail_html = '';
          //code to get user html here
          $(replace_wrapper).each(function( index ) {
            $(this).html(user_detail_html);
          });
        }
      });
    }else{
      //show popup here
      $('user-details-wrapper').show();
    }
  }).mouseleave(function() {
    //hide popup here
    $('user-details-wrapper').hide();
  });
 }
}

Make changes as per your requirement

Note : views_embed_view


How to attach a paragraph to a node using node_updatehook?

I used this code in hooky_entity_presave

       $paragraph = Paragraph::create([
              'type' => 'attendance',
              'field_stakeholder' => array(
               "value"  =>  '". Seema Bist, PS Manjkot from Dunda, Uttarkashi (UTK_130000379) (49647)"',
               //"value"  =>  '49645'
            ),
          ]);
              $paragraph->save();

            $entity->field_attendance->appendItem($paragraph);

Paragragh array is display (target id), but didn't display value of target id  in input value.
in
Means data added in node__field_at table, but not target id with node id is doesnt add in paragraph__field_st (st is entity reference field in paragraph type.

How to save data in paragraph entity reference field


Add markup before form output for user-login

Unless someone has a more elegant solution, I used:

$form['#prefix'] = '
Header
';

What seems odd here is the potential for a lot of markup in your code. I'm relatively new to Drupal, so I'm not sure if this is common practice.


I managed to get it to work with a context filter.


If this is a fully bootstrapped Drupal site, the superglobal $base_url, should get you what you want. See: https://api.drupal.org/api/drupal/developer!globals.php/global/base_url/7

However, these globals are not initialized until Drupal is fully bootstrapped.

If you need to sniff the base URL before Drupal is fully bootstrapped you can use the PHP $_SERVER superglobal.

For example:

function _get_base_url(){
  $protocol = ($_SERVER['HTTPS'] && ($_SERVER['HTTPS'] != "off")) ? "https" : "http";
  return $protocol . "://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
}


How to configure the Answers module to organize questions by product subpages?

I'm assuming you're using the most recent 7.x.-4.x version of the Answers module. The new demo site uses a further enhanced version of the most recent dev release. For example the views have been enhanced and will be pushed to D.O shortly. These views are available already in Views Export format via files attached to comment #5 in issue #2783513).

Here is a screenprint of the (new) view to show all the questions:

Note the Topics column in the above views result: it's just a term reference field, added as an extra field to the "Question" content type (which comes with the module). With that in mind, you could use a similar approach:

Step 1: Add a similar (mandatory) field, I'd recommend an Entity reference field. So that when a question is created the question author indicates which product your question is about.
Step 2: Enhance the view to add a filter related to the product.
Step 3: Adapt the path of your enhanced view that matches your requirements.

Note: regarding the "...so that they can only see..."-part of your question it may be sufficient to just filter the view as described above. But if you actually want to restrict access to any of the questions, you can use the access method/module of your choice to limit access to the Question nodes. Red flag: be aware of the "Disable Query Rewriting" discussion (and tune that views setting if needed).

Disclosure: I'm a co-maintainer of this module.


I wouldn't check them into Git, just create an Audio content type and have a file/audio field. I would just check Pantheon to see what the file upload limit is.


Sorting a view on a taxonomy term with entityqueue

I think that the Queue Position sort is being overridden by the Title sort. (In other words, the Title sort may be applied after the Taxonomy term Queue Position sort, making it appear as though the queue is not respected.)

If that's the case, then removing the Title field from the Sort criteria should be enough to get this working.

In case that's not sufficient, here's a good video tutorial on Entityqueue.


How work BigPipe cache around block views?

I don't know why the second block is cached by big-pipe and not the
  first block.

This depends on the auto placeholder conditions defined in services.yml and the cache metadata of the block:

auto_placeholder_conditions:
  # Max-age at or below which caching is not considered worthwhile.
  #
  # Disable by setting to -1.
  #
  # @default 0
  max-age: 0
  # Cache contexts with a high cardinality.
  #
  # Disable by setting to [].
  #
  # @default ['session', 'user']
  contexts: ['session', 'user']
  # Tags with a high invalidation frequency.
  #
  # Disable by setting to [].
  #
  # @default []
  tags: []

As mentioned in the comments, when the module BigPipe is enabled you need to use Drupal.behaviors for your javascript, see:

https://www.drupal.org/docs/8/api/javascript-api/javascript-api-overview


How do I create a field that accepts only unique values?

You need to implement this in a custom module, here is a sample code to achieve this:

function custom_node_validate($node, $form) {
  if ($node->type == 'page') {
    //retrieve the value for your field using Entity API
    $wrapper = entity_metadata_wrapper('node', $node);
    $value = $wrapper->field_collection->field_unique->value();

    //Execute a count query to see if there's other similar values.
    $query = new EntityFieldQuery;
    $query->entityCondition('entity_type', 'field_collection_item')
      ->fieldCondition('field_unique', 'value', $value)
      ->count();
    $count = $query->execute();
    if ($count > 1) {
      form_set_error('field_unique', 'Unique field value is already used.');
    }
  }
}

A few disclaimers:

I am really stocked by the complexity of Field Field Collection API and it was pretty complicated to find good information about how to retrieve values and make queries.
I really enjoy doing SQL queries (see How to change the legnth of field settings) but I tried to only use the API instead of doing a simple query on the table field_data_field_unique. However it may not yet be perfect so please feel free to chime in.
The form_set_error() isn't highliting the field, I was unable to find the correct name.

Here are the documentation I used:

hook_node_validate()
Get value of a field collection field (answer from fago), the Entity API module and entity_metadata_wrapper().
Checking out EntityFieldQuery (by Ryan Szrama) and the API.

Edit: Following chx advice, to pass directly field_name to fieldCondition().


I think you're making that a bit harder than it needs to be...if I understand you right anytime a row is clicked you want to identify that row, extract a field from it and display it in a modal?

If so something like this would be a bit simpler:

(function($) {
  $(function() {
    $('.views-row').click(function() {
      // Find the modal within this row and show it.
      $(this).find('.forModal').modal();
    });
  });
})(jQuery);

Sorry if I've mis-understood what you're looking for, I wasn't 100% sure.


Setup voting/rating on content to require a "reason" field

There are probably many different ways to create a feature where a comment is required along with voting. I guess it all depends on which method you're using for the voting part.

You could use the Fivestar module to Set up fivestar widget for User/Author rating with comment on any content type. 7X. Here you use allow for rating to be available on each new comment. You can use the usual comment field permissions to require input on both the voting field and the comment text area.

There are more ways to create something similar with the Fivestar module, it all depends on your particular needs.

Another module that can be used for voting is Flag. You can add Fields to Flags just like you can on a Content type: Attaching fields to flags (Flag 3.x). This way Flags are used for the voting part, and the Text area field created on the Flag is used to type in the reason. You can configure both the Flag and the Text area field on the Flag to be required based on Roles and Permissions.

Basically it's all about attaching a Text field to your voting widget and setting up permissions to make it required so the form can't be saved if it's empty.


Node content in panels vs. configuration in code

One could

Use Fieldable panels panes, which can replace the custom entity you use, and put content directly into the pane.
Configure the view to find nodes with a certain tag. Tag the node that should show up. Require the tag to be uniquely applied if only a single node is allowed.


How do I get the public url of a file from the uri or filename

What do you mean by "public URL" exactly ?
file_create_url() can give the absolute URL to the image out of the box.
$videouri = db_query('SELECT uri FROM {file_managed} WHERE fid = :nidvideo', array(':nidvideo' => $nidvideo))->fetchColumn();
//drupal_set_message('<pre>'. print_r($videourl, TRUE) .'</pre>');
$videourl = file_create_url($videouri);

file_create_url() expects a valid uri. drupal_realpath() gives the server path which does not work.
I also changed your database query to avoid any SQL injection vulnerable.


Custom field validation condition not working

You anyway have a problem here:

//If the input length less then 9 and bigger then 5 add leading 0
while(strlen($IDnum<9))
{
$IDnum = '0'. $IDnum;

}

it should be:

while(strlen($IDnum)<9)
{
$IDnum = '0'. $IDnum;

}