Dependency Injection Syntax I'm trying to build a simple module (to learn DI) to return the current user ID, and and apparently I'm missing something in the syntax.

Here's my code and the error it's producing:

use Drupal\Core\Session\AccountProxyInterface;
use Symfony\Component\HttpFoundation\Response;

 class LSWController {
  /**
   * @var AccountProxy
   */
     protected $currentUser;

     public function __construct(AccountProxyInterface $currentUser) {
         $this->currentUser = $currentUser;
     }

     public function say() {
         return new Response("Hello");
        //return new Response($this->currentUser->id());
     }
 }

and the error

ArgumentCountError: Too few arguments to function Drupal\lsw\Controller\LSWController::__construct(), 0 passed in C:\wamp64\www\testdrupal\core\lib\Drupal\Core\DependencyInjection\ClassResolver.php on line 31 and exactly 1 expected in Drupal\lsw\Controller\LSWController->__construct()

What am I missing?  I'm including the AccountProxyInterface, etc.  How come it's saying that 0 arguments are being passed?

Classes aren't naturally aware of the container, you have to implement them in such a way that they are. The most common approach for controllers is to extend Drupal\Core\Controller\ControllerBase, and override the create method, e.g.

use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Session\AccountProxyInterface;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\DependencyInjection\ContainerInterface;

class LSWController extends ControllerBase {
  /**
   * @var AccountProxy
   */
   protected $currentUser;

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

   public function __construct(AccountProxyInterface $currentUser) {
     $this->currentUser = $currentUser;
   }

   public function say() {
     return new Response("Hello");
     //return new Response($this->currentUser->id());
   }
}

For you, though, this approach will be bittersweet...on the one hand you've learned how to inject services into a controller, which is great.

On the other hand, ControllerBase already has a $currentUser property, which resolves to the same object you'd be getting from the injected service. So in applying the common solution, you've removed your original need for DI, and made the create and constructor methods completely redundant ;)

As 4k4 very correctly points out in a comment, you don't have to extend ControllerBase; implementing ContainerInjectionInterface in your own controller class is enough. But the deliciousness of solving the problem with less code than when you started is surely too much to resist.


Commerce field with no value, but printed My commerce product type has a text field, which is printed even if it has no value.
Every commerce field is printed within a <div classes_here></div>. Is there any way to avoid this issue??

thanks

Here is a link to this issue, with a patch for commerce 1.3


How to customise order cart customer information pane During checkout, I can add fields to billing or delivery information, but how can I add fields to customer information, or create another customized pane for them?

Example:

Student Information:

Name: Skill interest: Phone: Email: etc.....

You can achieve this using Ubercart Webform Integration module.

This module integrates two other modules: webform and ubercart. It allows you sell products directly from your webforms. It is particularly suited to be used as part of a registration system.

Using this module you can create additional field in check page.


How to Use Exposed filter of Taxonomy term with depth in Taxonomy View I have a question which is similar to How to use taxonomy terms(with depth) on a views exposed filter?

But problem in my case is that I am using views of type Taxonomy, here I don't get option in Filter "Taxonomy Term: Has content with depth".

I have my Taxonomy like :
-Country
  -State 1
    -City 1
    -City 2
    -City 3
  -State 2
    -City 4
    -City 5
    -City 6

I want exposed filter which has 3 select boxes like : -Country- -State- -City-
- State and City boxes fillup by Ajax based on Country selected.

Then the view should be updated based on the selected filters.
i.e If I select State 1 then I should get results of all the Cities below it and even of State 1.

Please note that I am not using View of type content, My view type is Taxonomy.

Can anyone suggest me how should I get this working?

Thanks in advance!

But problem in my case is that I am using views of type Taxonomy, here I don't get option in Filter "Taxonomy Term: Has content with depth".

You can bring that option into scope if you add a Relationship of "Taxonomy term: Representative node" or "Taxonomy term: Content using MY_VOCABULARY" and general any relationship that will join the node (or other Entity) table with the taxonomy table.


Get term ID of a field vocabulary in for templating I have a node template with various taxonomy fields and I'm trying to get the term ID of a specific vocabulary field to pass it through an url.
I have tried many function but I can't seem to find the proper one.
Can anyone help me on this ?

It sounds like you need to inspect your node.
You can do this with the vital devel module.

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

Once installed it will give you a few new tabs on your node page to see how the node is constructed when it is loaded using node_load($nid) and rendered using node_view($node).

In the node template itself, you will have access to the rendered node as per node_view($node) so anything you see in the devel modules render page you can print out in your node.tpl.php

Devel uses the excellent Krumo library to display PHP objects and array nicely, this is also accessible using dpm($object); however it can not be used in templates, but you can call krumo directly using krumo($node);

So in your node template, call krumo($node); to find the field you want, then once found add it to a variables $tid = $node->taxonomy[LANGUAGE_NONE][0]['tid']; and pass it to you link print l("taxonomy", "view/$tid");


How to print CCK field on a custom node template? Drupal 7, Omega Theme base I've been trying to print out CCK fields (Devel screenshot) in my custom node template using this code below which I found from a number of different sources (eg. src1, src2, src3) but with no result.

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

The code above seems to work for most people, if not all. I'm quite baffled as to why it doesn't work for me = /

Could it be something to do with Omega theme that I'm using as a base theme? I've also tried looking for Omega related issue with cck fields but still no result.

Please share your solutions with clear explanation, preferably like a step-by-step guide/explanation as I'm quite new to Drupal. Thank you!

Go to you content type's manage display fields tab and check weather field is visible or not?


View filter by date not current I have two blocks on our Drupal 8 front page: one shows a list of events upcoming; the other a list of events past. The blocks are generated from views filtering nodes whose event dates are after and before today's date respectively (using an 'event date' field, not the date authored).  The granularity of the event dates is to an hour. The filter is set to compare to 'now'.

But ... the lists are rarely up to date, usually several days out in fact. With 'future' events having event dates of days recently passed.   So I'm not looking at caching as the source of the problem (rightly or wrongly) as we have cacheing configured in hours not days.

What can I do to ensure that the lists are correct each day?

Clearing the cache has no immediate effect.

Then it's very likely that is not a caching issue and it's a set up issue.

This should work, is greater than 0 minutes


How do I do custom shapes (Complex Multipoint Geometry) using Geofield and Leaflet? I need to create regional boundaries using Geofield 2.x and Leaflet. How gan I go about doing this?

I have tried using Leaflet Widget for Geofield but it currently doesn't support the 2.x version of Geofield and the patch in the queue to make it compatible doesn't work.

I am looking for alternative method to the Leaflet Widget for Geofield module, perhaps using just Geofield.

I am not looking for a complete walkthrough. Just point me in the right direction and I will figure the rest out. :)

I think this is already possible when using Geofield with OpenLayers. Although I'm not using complex geometries in my current case, all settings indicate that the module is capable of it. E.g. if you choose in the setting of your Geofield for the storage option for 'single collection' it indicates that the widget will allow complex geometries.


Where does the value $ds_content come from in display suite templates? After updating to the newest version of display suite I noticed that in display suite ds-reset.tpl.php the value for $ds_content is now blank.

<?php

/**
 * @file
 * Display Suite reset template.
 */
?>
<?php print $ds_content; ?>
<?php if (!empty($drupal_render_children)): ?>
  <?php print $drupal_render_children ?>
<?php endif; ?>

Where is this value assigned so I can better troubleshoot what the problem is.

Looks like it's set in ds/includes/ds.registry.inc in _ds_ds_layout_info() which implements a hook hook_ds_layout_info


How to use theming in other module Currently I am building a module by reusing the 'page callback' function in an other module. The data array are successfully rendered. However The presentation is poor.

I suspect that after page callback it doesn't successfully load the theme (probably css?), but I don't know how to do that.

------update------

Here is the code. I add node_add_page from node module to a new menu named 'node/add/add-art'. The data is rendered successfully, however the format is broken. Is it possible to not only reuse the data process function, but also reuse the theme it is using?

$items['node/add/add-art'] = array(
  'title' => 'Add art work',
  'parent' => 'admin/commerce/manage-products/actions',
  'type' => MENU_LOCAL_TASK | MENU_NORMAL_ITEM,
  'page callback' => 'node_add_page',
  'access callback' => TRUE,
  'file' => 'node.pages.inc',
  'file path' => drupal_get_path('module', 'node'),
);

You should use the drupal_get_form() to render the node form.
For art content type.

$items['node/add/add-art'] = array(
  'title' => 'Add art work',
  'parent' => 'admin/commerce/manage-products/actions',
  'type' => MENU_LOCAL_TASK | MENU_NORMAL_ITEM,
  'page callback' => 'drupal_get_form',
  'page arguments' => array('art_node_form'),
  'access callback' => TRUE,
  'file' => drupal_get_path('module', 'node') . '/node.pages.inc'
);


Best way to deal with node data that should only be displayed in views Possible Duplicate:
  How to prevent access to Views-only content?

Sometimes I build a content type whose data really only makes sense to display in a View.  An example would be a content type called "Slide" and a View called "Slideshow". I may not want people or search engines to actually go to the node because the slideshow is displaying a series of slides, and by itself, the "Slide" is not very interesting.

So what strategies do site builders usually employee in this situation? Do they style the "Slide" node so that if someone goes there, it looks OK? Do they un-publish the "Slide" so only admins can access it, and then program the view to not filter on only published content?

A couple strategies here...

One is the obvious one you mention: Don't publish the 'Slide' content type, so it never appears on the 'live' site.

Another is that you don't make special 'slideshow' content types. You just add fields to your normal content types that will be displayed in a slideshow display mode. Then you hide them for other display uses like Default and Teaser.

Drupal's flexibility with this type of scenario is one of its major strengths. But it also means that site editors have to remember which field does what, or which type of nodes not to publish.


Publishing option is not available for one content type I have drupal 6.25. I have some content types like article, editors, slideshow and others.
publishing options are listed normally for all content types except "article" (although i gave "administer nodes" permission to my editors). i have tried some modules like Override Node Options but i still have the same problem for this content type for all users (of course except the admin user, admin can see it normally).
any idea of what might cause this and how to fix it?
Thanks for your help

I have managed it already.
I found a form_alter hook in one of my modules. and in this hook there was the line below (i just commented it)

$form['options']['#attributes'] = array('style' => 'display:none');


Injecting configuration into mock config object I'm trying to set up a unit test based on UnitTestCase in Drupal 8 that uses some config variables. Unfortunately I was not able to find a way to insert those config variables into the system in the setup (searched Drupal documentation and any Drupal unit test example involving config), so the function being tested always works with null config and fails. I am trying to test individual functions in isolation, so a browser test is not really appropriate for this.

I have simplified the problem to the minimum code necessary to explain/reproduce the issue. Here are the three components. Where in the mock/setup do I insert the array('bucketName' => 'test_bucket') and other properties so that it can be read from the tested function?

Function:

public function example() {
    return \Drupal::config('my_module.job')->get('my_module.bucketName');
}

Test function:

public function testExample() {
    $myModuleHelper = new MyModuleHelper();
        $expected_config = array(
            'bucketName' => 'test_bucket',
        );

    $this->assertEquals($expected_config, $myModuleHelper->example());
}

Test setup:

public function setUp() {
    $this->config = $this->getMockBuilder('\Drupal\Core\Config\ImmutableConfig')
        ->disableOriginalConstructor()
        ->getMock();

    $this->configFactory = $this->getMockBuilder('\Drupal\Core\Config\ConfigFactory')
        ->disableOriginalConstructor()
        ->getMock();
    $this->configFactory->expects($this->any())
        ->method('get')
        ->with('my_module.job')
        ->willReturn($this->config);

    $this->container = new ContainerBuilder();
    $this->container->set('config.factory', $this->configFactory);
    \Drupal::setContainer($this->container);
}

Test response:

  null does not match expected type "array".

Your mock of the Config object needs to also have a ::get method and return the appropriate value using your array. The core UnitTestCase class provides ::getConfigFactoryStub(array $configs), which does all of this automatically.
In your setup, create the config factory like this:
$this->configFactory = $this->getConfigFactoryStub([
  'mymodule.job' => ['bucketName' => 'test_bucket'],
]);

Unfortunately, the mocked config does not quite work like a real config object; namely, it doesn't accept dotted keys but only top-level keys. The following will not work:
$this->configFactory = $this->getConfigFactoryStub([
  'mymodule.settings' => [
    'key' => [
      'subkey' => [
        'subsubkey' => 'value',
      ],
    ],
  ],
]);
$this->container = new ContainerBuilder();
$this->container->set('config.factory', $this->configFactory);
\Drupal::setContainer($this->container);

\Drupal::config('mymodule.settings')->get('key.subkey.subsubkey');

This bug report shows a workaround: https://www.drupal.org/node/2862248
Update: The above problem was fixed in Drupal 8.5.0, so the workaround is no longer needed.


How to prevent empty token from showing I want to capture a value from the url and display it in a piece of content, if available.
In my node body I enter text like:

The sid is "[current-page:query:sid]".

If I then view that node at http://example.org/node/123?sid=foo the content shows as:

  The sid is "foo".

Excellent, all working great. Here's the problem: if I visit the page without the ?sid argument in the url (just going to /node/123), then the content displays literally as:

  The sid is "[current-page:query:sid]".

I would prefer the token to just be blank in that case. How can I get it to output

  The sid is "".

The reason for what you experiencing is the default behavior of token_replace() to leave tokens untouched if no replacement value was provided.

In your case, the Token Filter module would have to provide the option 'clear' => true when calling token_replace().

You may want to try to apply the patch in this issue to the token_filter module.


Hide views tab display on user profile to profile owner I have a use case where I need to create a page for members of two specific roles (Contributor and NAD Contributor) to see their own unpublished content. Using views relationships and filters, I've created a tabbed page display at the path user/%/unpublished that only displays unpublished content belonging to the logged in user. All that works great except for one thing; the tab itself is visible on all user accounts, even though it's only visible to users of the specific roles. What this means is that there is a Unpublished tab (with no content) for other roles that don't need this page, so for instance the two Contributor roles would see an Unpublished tab on users of other roles.

Is there a way within Views to control the display of this tab to only be displayed on the profile pages of the roles specified in the Access settings for the display?

Thanks.

You might have already thought about this, but you could make a Panel Variant that only shows to those roles.


What does the "Empty srcset[]" breakpoint in Picture Module? I'm using the Picture Module.

What does the Empty srcset [] breakpoint exactly do? Why should I use it, and why shouldn't I use?

The empty srcset is to be used when there is a breakpoint where you don't want to display your image. An example might be where the image in question, or a parent div, is display:none in the css. The image would normally be downloaded anyway, but by having an empty srcset at that breakpoint, no images will be downloaded.


SQL error after using Feeds Import with Taxonomies I have been using intensively the Feeds module. After many imports of data doing test, I sometimes get the following error message: ´SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry taxonomy_term-32591-0-0-und' for key 'PRIMARY'

Can I clean the database in such a way that I will no longer have this error message? Of course, when it happens, the taxonomy terms are not imported. After deleting the Feeds and importing again, it goes perfect, but the problem happens from time to time.

I don't think I have many extra modules which will store taxonomy tid's on them, so maybe the problem is with the core database tables, but I cannot find where there are still rows to be deleted manually to solve the problem.

Because the data are already corrupted, I pretend to manually repair the integrity of database (or with the help of a module) without having to look for a previous backup, which would imply losing hours of work done on other sections (and thus tables of the database).

Finally, I have discovered the problem. I deleted the taxonomy data with the module Taxonomy Manager. When importing the data with Feeds again, it believes that the data remains there, even if they longer no exists. From here, some failed imports can make database corrupted.

To regain integrity, I looked for the problem tid, and checked that it appears in field_data_* with entity_type = 'taxonomy_term' and field_revision_* with the same entity_type. I also appears in url_alias, and didn't find any more instance of tid's with the problems in any more tables. I truncated all these tables.

I also checked that both modules, when deleting taxonomy terms, if the tables are empty, they don't make an additional TRUNCATE, so the new tid's don't start at tid = 1.


How to know from which country people are accessing my website? I am using Drupal7. I have a Chinese version of my site and I want to know whether they are using it or not. So I want to know which countries are using my website.

I tried to find that out like this -> if I go to the Reports>>Recent Hits then I find the hostname for the anonymous users.

I found some website that tells the country name taking the host IP address as input.

Is there any module that shows country from which the website got accessed?

You do not need a module for that. Simply make use of any web analytics system such as
 Google analytics, Piwik analytics and such like.


Commenting on each paragraph of node body I want to provide this option in Drupal that users be able to put comment on each paragraph of an article beside putting comment on the whole article.

I use explode command to make an array which contains paragraphs:

$paragraphs = explode("<p>",render($content));

In order to put comment for the whole article I write:

print render($content['comments']);

I am trying to find the file where $content is defined, so I can add another array like $content[]['paragraphcomments'] for comments for each paragraph of an article. Does anyone know in which file $content is defined. Also does anyone have any suggestion?

$contentis defined in node.module in the function template_preprocess_node().
You can add elements to the nodes content using hook_node_view()(D7) or hook_nodeapi() (D6).

See the accepted answer of this question for more details.


Change CSS class based on number (length) of entity reference items, in a paragraph entity In my paragraph twig file paragraph--call-to-actions.html.twig, I want to render and build up the entity reference items (the child items from a certain Paragraph type).

There could be 3 or 4 items. Based on the length of the items (3 or 4) I want to change the markup/change a CSS class so I could have 3 or 4 columns.

In paragraph--call-to-actions.html.twig I could do something like:

{% if content.field_call_to_actions|length == 3 %}
  {# Build 3 column item markup here #}
{% elseif content.field_call_to_actions|length == 4 %}
  {# Build 4 column item markup here #}

But how do I loop through my entity reference items (Paragraph type items) so I can print all of the fields of my paragraph type?

Or is there a cleaner approach?

Update:
I found a solution by extending field.html.twig to field--paragraph--call-to-actions.html.twig and in there:

{% for item in items %}

  <div class="card mx-6 md:mx-4 mb-6 md:mb-0
  {% if items|length == 3 %}
    md:w-1/3
  {% elseif items|length == 4 %}
    md:w-1/2 lg:w-1/4
  {% endif %}
  ">
    {{ item.content }}
  </div>

{% endfor %}

I can't use loop.lenght here because of the different breakpoints.

Can I write this more cleaner without duplicate classes (DRY)?

{% for action in paragraph.field_call_to_actions %}
    {{ paragraph.action.value }}
{% endfor %}


Create a Rule that assigns a specific role to a user after they have completed a form Ok, I have a customer that is wanting to have an applicant complete a specific webform and then have their user account be assigned to a specific role automatically.

My thought was to go the following route using rules:

Applicant creates their user account
They are then automatically taken to the specific webform
Once the webform is completed, then they are automatically assigned a specific role (this is the part where I'm lost as to the best option or if it's even possible)

Is this something that would even be possible using rules? Or are there other options that may work? Any assistance would be greatly appreciated!

I hope I've explained the situation enough :) Let me know if you need any further info.

Thank You!!

Nicole

Sure you can! This is a way of doing it with the Rules module.

This also requires the Webform Rules Module.

Download that, enable it, and be sure that the Rules UI module within it is enabled as well.

Step 1 - Create Rule

Start by creating a new Rule under Admin>Config>Workflow>Rules.

Name it whatever you'd like, but have it react on "After a webform has been submitted"

Step 2 - Find Webform's NID

In another tab, view your Webforms in Content>Webforms. Hover your mouse over the Edit link next to the Webform you were talking about to find its Node ID (NID). You will need this in a second.

Step 3 - Only Apply Rule to that Particular Webform

Return to the Rule you created a bit ago and click the "Add condition" link under "Conditions".

Select "Data Comparison" as your condition.

Here, you are going to select "node:nid". This is because you only want this rule to fire up when the Webform you mentioned earlier is submitted.

Below that, enter in the Node ID for the Webform

Step 4 - Add Action for Adding Role

Return to your Rule and click on the "Add Action" link in the "Actions" settings.

For your Action, you are going to select "Add user role"

Under the Data selector, you are going to choose "user"

Below that, select the Role(s) that you want the submitter to gain.

Hope this helps!


Where is name defined in image_effect_info_alter(&$effects)? function my_module_name_image_effect_info_alter(&$effects) {
    $effects += array(
        'whatever' => array(
            'label' => t('blabla'),
            'help' => t('Everything you need to know about this effect'),
            'effect callback'=> 'function_I_wrote',
            'dimensions callback'=> 'another_function_I_wrote',
            'form callback'=> 'image_resize_form', //This one is sufficient
            'summary theme'=> 'image_resize_summary', //No need for own summary
            'module'=> 'image', //dunno?
            'name'=> 'image_rotate', //this is where my question is about
            'data'=> []
        )
    );
}

So I was looking at https://api.drupal.org/api/drupal/modules!image!image.api.php/function/hook_image_effect_info/7

They don't even mention name, but without it I get error:

  PDOException: SQLSTATE[HY000]: General error: 1364 Field 'name'
  doesn't have a default value

And if I specify my own name it doen't show up under the Image styles effect section after adding. Using an existing one gives it that name. So my guess it's some kind of constant. Where does it come from?

First of all: I think the alter method should not exist if this is the easier way.

Call hook_image_effect_info() and just pass

  label, help, effect callback, dimension callback and form callback

this way it won't ask for

  name


How to display a field in a content type template? I edit my template field--field-email--customer.tpl.php and it works but I would like to display a field twice. I tried with this but it doesn't work :
    print render($content['field_nom']);

As per my knowledge you can not use $content array in field.tpl.php.
You need to use $items.

  Available variables:

$items: An array of field values. Use render() to output them.
$label: The item label.
$label_hidden: Whether the label display is set to 'hidden'.
$classes: String of classes that can be used to style contextually through CSS.

  from preprocess functions. The default values can be one or more of
  the following:

field: The current template type, i.e., "theming hook".
field-name-[field_name]: The current field name.
field-type-[field_type]: The current field type.
field-label-[label_display]: The current label position.
$element['#object']: The entity to which the field is attached.
$element['#view_mode']: View mode, e.g. 'full', 'teaser'...
$element['#field_name']: The field name.
$element['#field_type']: The field type.
$element['#field_language']: The field language.
$element['#field_translatable']: Whether the field is translatable or not.
$element['#label_display']: Position of label display, inline, above, or hidden.
$field_name_css: The css-compatible field name.
$field_type_css: The css-compatible field type.
$classes_array: Array of html class attribute values


Purpose of Media module If I am using the IMCE file uploader combined with CKeditor, is there any point in installing the media module?

Or does media replace the imce when wysiwyg module is used?

The Media Module (2.x) uses the File Entity module. Files become 1st class citizens in your Drupal installation just like a Node or Entity or a variable. A FileEntity can be queried using Views for instance.

IMCE (to my knowledge) is simply a file browser (bridge) for your server compatible  with TinyMCE and I suppose CKeditor now. Files are just files on the system and drupal isn't 100% aware of them and their meta-data.

If you only need to browse files then IMCE has its usages. If you want something more meaningful and integrated with Drupal as a whole look at Media, and maybe like Media Browser Plus.


Custom module block programmatically assigning it to a specific role I have a Custom module that implements a block how do I programmatically assign it to a specific role or roles in drupal 8?

This is how I did it.

function _<module-name>_check_user_access() {
  $roles = [
    'editor',
    'admin',
  ];

  $current_role = \Drupal::currentUser()->getRoles();
  foreach($roles as $role) {
    if($role == $current_role[1]) {
      return TRUE;
    }
  }

  return FALSE;
}

See my blog post for more information about it


Setting date_popup year range to more than the 3 years default in Drupal 7 I have a custom module and using date_popup. Currently the popup only shows a 3 year range in the date popup.

  $form['startdate'] = array(
    '#type'       =>  'date_popup',
    '#title'      =>  'From',
    '#default_value'  =>  filter_get('browse-startdate'),
    '#date_format'    =>  'Y-m-d',
  );

What is needed to make the range higher?

Use the following option in the array:

    '#date_year_range' => '-8:+8'

That goes up to 8 years or more. Generally you don't use minDate as that only goes back up to 3 years only.


Need to identify higher value and lower value stored in the multivalue field I have a Multivalued field called temperature in that everyday temperature values are stored. In that i would like to identify the highest and lowest value from that field.I found computed field module will do that but i would like to know how i achieve same in computed field.please anyone guide me do this.

Thanks

Never put code in the database. It is impossible to maintain and debug, and you spend hours wasting your time.

The computed field gives you the option to add the code to a custom module.

My answer used these three fields added to the content type:

Temp (machine name field_temp, integer, multi-value)
Highest (machine name field_highest, computed, int)
Lowest (machine name field_lowest, computed, int)

Method:
Create a custom module (just module and info files), then add this to the module file:

function computed_field_field_highest_compute(&$entity_field, $entity_type, $entity, $field, $instance, $langcode, $items) {
  $temps = field_get_items($entity_type, $entity, 'field_temp');
  if (count($temps)) {
    $max = $temps[0]['value'];
    foreach($temps as $temp) {
      $max = $temp['value'] > $max ? $temp['value'] : $max;
    }
    $entity_field[0]['value'] = $max;
  }
}

function computed_field_field_lowest_compute(&$entity_field, $entity_type, $entity, $field, $instance, $langcode, $items) {
  $temps = field_get_items($entity_type, $entity, 'field_temp');
  if (count($temps)) {
    $min = $temps[0]['value'];
    foreach($temps as $temp) {
      $min = $temp['value'] < $min ? $temp['value'] : $min;
    }
    $entity_field[0]['value'] = $min;
  }
}

Read the documentation page for the computed field module to see the naming convention for adding a custom function. The function name is also visible in the field settings.

In the two functions I refer to 'field_temp'. It is the machine name of the multi-value field holding the temperature values.


Drupal Commerce Authorize.net gateway and POODLE I got a notice today that Authorize.net is going to shut off their SSLv3 protocol on November 4 (7 days from today) in response to the POODLE threat.  I'm using Drupal Commerce's commerce_authnet module to accept credit cards on our web storefront, how can I tell whether I connect via SSLv3?  And if I do, how can I change that to connect via TLS or whatever I need to do?

Thanks.

The commerce_authnet module is using the PHP curl() functions to communicate with Authorize.net, and it does not explicitly requests the SSLv3 protocol in the curl options (see file commerce_authnet.module, lines 1163 to 1172).

curl will therefore rely on the HTTPS handshake to determine the protocols and ciphers, and since the Authorize.net will not advertise SSLv3, another protocol will be selected during the handshake (most certainly TLS v1.2).

So you have nothing to change, the transition will be handled automatically by the HTTPS handshake. I would only advise you to upgrade your openssl library to the latest version.


Focus problem when Ajax call for multiple fields calling the same callback function I have implemented a custom form. I put same Ajax callback function for multiple field. When one Ajax call completes, I click on other field. But I can't unfocused previous field. Sometimes the Ajax call runs for multiple field.

My code:

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

   '#autocomplete_route_name' => 'advance_search_autocomplete_callback.advancesearch_autocomplete_callback',
    '#autocomplete_route_parameters' => array('type' => 'worklocation'),
    '#ajax' => array(
      'callback' => [$this, 'friends_advance_search_results'],
    ),
    '#attributes' => array('class' => array('form-control')),

  );

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

    '#autocomplete_route_name' => 'advance_search_autocomplete_callback.advancesearch_autocomplete_callback',
    '#autocomplete_route_parameters' => array('type' => 'school'),
    '#ajax' => array(
      'callback' => [$this, 'friends_advance_search_results'],
    ),
    '#attributes' => array('class' => array('form-control')),

  );
  $form['college'] = array(
    '#title' => t('College / University'),
    '#type' => 'textfield',

   '#autocomplete_route_name' => 'advance_search_autocomplete_callback.advancesearch_autocomplete_callback',
    '#autocomplete_route_parameters' => array('type' => 'college'),
    '#ajax' => array(
      'callback' => [$this, 'friends_advance_search_results'],
    ),
    '#attributes' => array('class' => array('form-control')),

  );

Callbakck:

function friends_advance_search_results(array &$form, FormStateInterface $form_state) {

 $search_result = array(
                    '#theme' => 'friends_advanced_search_list',
                    '#friends' => $friends_list,
                    '#info' => array('display' => 'hide', 'friend_recommend' => 0, 'load_more' => $load_more, 'no_results' => 1,'search_action' => 1),

                    );

   $output = render($search_result);
   $id = '#advanced-friend-list';
   $response = new AjaxResponse();
   $response->addCommand(new ReplaceCommand($id, $output));

   return $response;

}

Problem:

Enable disable-refocus when adding the ajax callback:

'#ajax' => [
  'callback' => [$this, 'friends_advance_search_results'],
  'disable-refocus' => TRUE,
],

See https://www.drupal.org/project/drupal/issues/2627788


Views: Change path and redirect old to new path? I would like to change the path for one of my Views. How do I redirect the old Views path to the new one including all the variables that may follow the old path?

Use this Path redirect module to redirect path.

  This module allows you to specify a redirect from one path to another
  path or an external URL, using any HTTP redirect status.


how to add wrapper div for a image via image formatter in drupal 7? I am creating custom formatter for images using hook_field_formatter_settings_form() in drupal 7.. I need to add wrapper div for my custom formatter. Means when I select this formatter then image should be wrapped by div.
for example .

You need to add one more hook to default add  to field wrapper.

 function hook_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  $settings = $display['settings']; // Key needs to be defined in info array (who knew?)
  $element = array();
  if ($display['type'] == 'default_formatter') {
    foreach ($items as $delta => $item) {
      $element = array(
        '#prefix' => '
',
        '#suffix' => '
',
      );
    }
  }
  return $element;
}


Drupal 7.2, Views: Adding Author's Name of a node I'm sure this is VERY basic, but after 1/2 day or searching, I am finally posting for help.

I have a simple view that is displaying a list of node titles & other fields (view count, comment count, etc). I can't find how to add the name of the author who wrote the corresponding node to a field.

For example- the final result SHOULD look like this-

Title
by: Author Name
Views: #  Comments: #

I have everything else working- just can't figure out how to add the author name field. What's the secret?
Thanks guys!

You need to add a connection between users and content. This is done through relationships. Go to relationships and select Content: Author. Then if you add fields you will see several new fields to choose from including User: Name. When configuring User: Name there will be a drop down that lets you choose which relationship since there is only one choose that one.


How to configure ckeditor for different toolbars? In D7 I would like to use ckeditor with a specific profile for a user role. The user is only allowed to use bulleted listed. How to do this?

I did the following:

Configured in drupal a ckeditor profile call "builder"
For a role say"Client" I added a text format say "Bullitsformat"
for a field in a content type "testfield" I configures user can choose own filter.

If I test the edit form no toolbar is displayed when user selects Bullitsformat.

What to do?

Found the solution to first add the bullitsformat and then edit the profile, so this profile is shown in the profile of the ckeditor.


Guard/LiveReload/Sass/Compass CSS Caching Issue Here is a quick primer on my setup.
Running an aurora sub theme that utilizes guard, guard compass, guard livereload.
Basically what is happening is I make a change in a sass file, the files compile and the style change is shown right away on the browser. Great.
The problem arises when I click a link to go to another page, the CSS that is on the newly visited page is from the previous state. So my test cases are.. change the background color from blue to red. Background changes to red on the screen. Click a link to another node, background remains blue. Simple browser refresh, background turns to red.
I've been trying to find some info on this specifically, but having a heck of a time.
Things I've tried so far

Turn off sass caching in my config.rb file, so no .sass-cache generation {:cache => false}.

Reference my stylesheet via a hard coded entry in the html.tpl.php template instead of via the info file.

Tried a basic 2 .html page test case, nothing to do with drupal, and I get the results I wanted (no css cached).

I've even looked at Chrome settings before really deciding I felt this is a Drupal thing.

I made a color change, watched the result in my browser, went into the sites/default/files/css/ directory and deleted all the css files, went back to my browser and clicked on a link to another node, and the same result happened, previous CSS rendering.

Did the same thing above except instead of deleting CSS files from the folder, I just ran a drush cc css-js in terminal, then went and visited the second node link, and still old CSS renders.

I have not implemented this, but I know I can run drush commands via guard shell and was wondering if I can do the above in 6, just automate it.

Messed around with config.rb settings such as debug, line_comments, environment or production variables, etc.

I am running out of ideas on how to get this to work a bit better.
Any suggestions?

Ensure that you have scss files in your LiveReload "files to watch" option, this will ensure your changes apply from node to node, without having to manually refresh just because you changed pages. Not sure of any side effects as of yet.


Understanding the Basic Context of Trusted Hosts I got the trusted host settings error.

  The trusted_host_patterns setting is not configured in settings.php. This can lead to security vulnerabilities. It is highly recommended that you configure this. See Protecting against HTTP HOST Header attacks for more information.

I read the Trusted Host Settings documentation but I'm not understanding some of the basic context.

Are the "trusted hosts" me and other administrators who want to be able to administer the site remotely?
If so, would I add my PC's domain to the trusted host list?

Trusted hosts refer to the domain that your Drupal site is hosting, not your remote PC's domain that is administering the site. For example, if your site running on Drupal was www.thedrupaldude.com, the trusted host regular expression would be ^www\.thedrupaldude\.com.


Import LoginToboggan settings Is it possible to import the LoginToboggan settings to a feature ? Logintoboggan doesn't seem to have an api either

You'll want to use the strongarm module. That will expose the variables that logintoboggan stores it's settings in to features. When building your feature it will add an option for "strongarm: variables" to the edit components section.
You will need to know the actual internal variable name. You can get that by either looking at logintoboggan's code or from the field names in the settings page's html source.


Adding metadata to a node through a module I am developing a module that sync selected nodes with an outside site (another API on the web).  I need to add some meta-data to each node:

Last sync time (timestamp) - Not editable through UI
Outside API ID for this item - Not editable through UI
Sync enabled for this node (yes/no) - Editable through UI

Should I have my module create a new table through the Drupal Database API to store this data, or should I use the Field API?

Your requirement seems pretty straight forward. If you want to save some time, I would suggest that you use the Field API. To make those fields non-editable by users and administrators, all you need to do is implement a hook_form_alter and hide the form elements. You can also implement hook_form_FORM_ID_alter, which I find more efficient.

Example. Hide the author field:

$form['author']['#access'] = FALSE;


After updating to user_restrictions-7.x-1.0 in drupal7, I can no longer run cron from another host I've been updating several drupal7 installations from one browser on the same host as ONE of them.  I just did this, updating to user_restrictions-7.x-1.0 on both machines.  This caused no problems on the host where my browser was running, but on the other host drupal will no longer run cron manually at my request, and clicking on the "To run cron from outside the site, go to http:///drupal/cron.php?cron_key=..." link yields an "Access Denied" message.

Under the circumstances, I must conclude that something significant has changed in user_restrictions-7.x-1.0 that enforces some exclusion on the basis of IP address that didn't exist before or was not previously being enforced.

How do I grant my other host permission to use the cron_key in question?

The User restrictions module just restricts which users can log in basing on their username and email address; if the username or the email address matches a regular expression set in the module settings, the user is not allowed to log in. At the same time, the module doesn't allow users to change their usernames or email addresses to values that match those regular expressions.

The modules doesn't restrict user access basing on their IP, since that functionality is still present in Drupal 7 core, although Drupal core just allows you to set an IP address, not a range of IPs to ban.
If you are experiencing what you reported, then it could a module bug. Report it in the project queue, once you verified there isn't a issue already opened for that, and that the module is really the responsible for that behavior.

Disclaimer

I am the maintainer of the module, although I didn't change the module code recently. I don't plan to develop any Drupal 7 module, since I am focusing on Drupal 8 development.


Can't login to Drupal after Varnish install (reverse proxy) I setup Varnish for Drupal 7.x; when I go to settings.php to uncomment the following line, and I try to login as administrator, I am just redirected to the same page; nothing happens. No idea what could I have done wrong.

$conf['reverse_proxy'] = TRUE;

I'd like more details.  To start, here's what I have in my settings.php:

/**
 * Varnish settings
 */
$conf['cache_backends'][] = 'sites/all/modules/varnish/varnish.cache.inc';
$conf['cache_class_cache_page'] = 'VarnishCache';
$conf['reverse_proxy'] = true;
$conf['cache'] = 1;
$conf['cache_lifetime'] = 0;
$conf['page_cache_maximum_age'] = 21600;
$conf['reverse_proxy_header'] = 'HTTP_X_FORWARDED_FOR';
//$conf['page_cache_invoke_hooks'] = false;
$conf['reverse_proxy_addresses'] = array('127.0.0.1');
$conf['omit_vary_cookie'] = true;
$conf['page_cache_invoke_hooks'] = FALSE;

All of that might not be necessary, like $conf['page_cache_invoke_hooks'] = FALSE - but it's working for me

First, did you set Varnish to port 80 and Apache to port 8080?  First try to access the site via http://example.com:8080 to see if Apache is still serving pages.  Another way to check for servers working is by opening terminal via ssh and typing 'netstat -anp | grep httpd'.  Here is my output:

netstat -anp | grep httpd
tcp        0      0 0.0.0.0:8080                0.0.0.0:*                   LISTEN      324/httpd

netstat -anp | grep varnish
tcp        0      0 0.0.0.0:80                  0.0.0.0:*                   LISTEN      24841/varnishd
tcp        0      0 127.0.0.1:6082              0.0.0.0:*                   LISTEN      24840/varnishd

You can see that apache (httpd) is working on :8080 and varnishd (d for daemon i.e. service) is running on :80 and :6082 where :80 is varnish and :6082 is its backend.

If you CAN see site on :8080 and you have varnish running on :80 and :6082 you should go to the varnish drupal config page via http://example.com:8080/admin/config/development/varnish

From there you should select the correct Varnish version set, the Varnish Control Terminal set to 127.0.0.1:6082, and your Varnish Control Key set.  You can find this by seeing the output of the secret file.  In CentOS you can do this by: cat /etc/varnish/secret - this will give you a 30ish char long string to input.  At the bottom of this settings page you will find "Status: Varnish Running" hopefully.

If you have all of this working and still can't get the site to show, it will be giving you an output noting Varnish and a Guru Meditation.  This shows you that varnish is indeed running but just isn't configured correctly, most likely in your .vcl file.  If no guru meditation and site not working, you probably haven't set the sysconfig correctly.  Edit - again CentOS - /etc/sysconfig/varnish using vi or nano.  I have the following uncommented:

// using Alternative 2, Configuration with VCL
DAEMON_OPTS="-a :80 \
             -T localhost:6082 \
             -f /etc/varnish/default.vcl \
             -S /etc/varnish/secret \
             -s file,/var/lib/varnish/varnish_storage.bin,1G \

Check that the .vcl file is correctly referenced and that the port (:6082) is the same as what you found with netstat above.

Finally, if you are getting the Varnish Guru Meditation the .vcl is the issue.  In this case here's some of what I have for the .vcl:

BEGINNING OF FILE ->
backend default {
  .host = "127.0.0.1";
  .port = "8080";
  .connect_timeout = 600s;
  .first_byte_timeout = 600s;
  .between_bytes_timeout = 600s;
}

sub vcl_recv {
//TRY THIS AT BEGINNING ->
return(pass)
..
}

The return(pass) will pass EVERYTHING and thus Varnish won't actually be caching anything, but you can use for diagnosis.  Remember after changing anything varnish related you need to restart varnish by: service varnish restart - if you .vcl has any errors it won't restart.


How to override system.menus.css system.menus.css has it's own styles for the menu block. How can I override this style?

Would creating a folder called CSS in my theme and adding a file system.menus.css override it?

add your css file through your themes's .info file

  stylesheets[all][] = myStyle.css


Variable containing HTML is not rendering when sent by message notify I am trying to send e-mails with message notify and rules, everything is running pretty well, but there's one variable which contains a "HTML code", It describes a table of items that were bought for someone.
I NEED to pass it as a HTML table, but it renders like these on the users E-mail Inbox:

Peep Toe Colorido (34, Marrom) (415-01612--11163-11184)
1
10990

Sandália Clássica (34, Nude) (577-02357--11163-11186)
2
19980

and the tags which were entered in the message type  and  are rendered right, showing not the markup tags but the table itself.

How can i make the HTML generated by a variable render properly when sent by message notify?

Try using the HTML Mail module, Which will help you to render HTML in your email notification

Lets you theme your messages the same way you theme the rest of your website.


How to force drupal to use English version of the field? I have bean block with a list (list_block) of other bean blocks (content_block) which I use in slider. I have multilingual site, so I have 2 languages English and Spanish. Each content_block has translation (so it has both English and Spanish variants). So the problem is:

I have an empty field Description in one of my content_blocks and it's empty only for English version, but it has data in Spanish version. So when I go to see the slider (with the list of content_blocks) on my homepage in English version I see Spanish value of this field but not empty value. When I add English value to that field the problem disappearing and English value appears in the slider. So why this happening? And how to force Drupal to use English version of the field even if it has no value but it has Spanish version of the field ?

Go to the Views admin of the block, and filter by language. It will automatically only show the node in the language that you select.


Drupal and Hiphop php VM Faceboock has just released on GitHub their new Hiphop PHP VM, please follow this link:

https://github.com/Facebook/hiphop-php/wiki

Do you know if it is possible to enhance Drupal performance with HipHop PHP VM?

If yes, do you have a good howto, or the different steps to make it work, with a CDN?

At the time of writing Drupal does not work out-of-the-box with HipHop VM (1). Some people have managed to make it work with previous versions, but there isn't a simple easy option.

On php.webtutor.pl you can find a number of useful resources:

A benchmark of Drupal comparing standalone PHP, PHP with APC, and HipHop ;
The patch that was used to make Drupal run under Hiphop

These are for an older version of Drupal 7 (7.2) and an older version of Hiphop. However the patches are still useful as a place to start. Some of the issues addressed in the patches (eg. the infinite loop caused by drupal autoload) are still current - others may or may not be, I have not investigated further myself though the article by @tvlooy suggests the PDO issues have been fixed.

The article at http://nickveenhof.be/blog/getting-drupal-7-almost-running-hhvm (on which the tests by @tvlooy was based) provides an example configuration - even though the author failed to get Drupal to run under HHVM, it gives a helpful starting point in addition to the webtutor patches.

(1) As tested with Drupal 7.22 and the latest development version of HipHop (HEAD on the master branch) as of 01/08/2013

Edit: A post made on the 12/09/13 (after this answer was written) on the HHVM blog suggests that HHVM now passes 98% of Drupal core unit tests. There has been more HHVM releases since then - a comment on the 2.2.0 release that came out a month later suggests that Drupal 7 can be installed using HHVM, though file uploading, clean URLs and php-gd do not work. I do not want to change my original answer as I have not tested this myself, however the comment (together with the 2.2.0 changelog) suggests that some of the issues, such as the autoload loop, have been fixed.


How to set the default value of an exposed filter rather than -Any-? I have a view with exposed filters in Drupal 7 and I need to set the default value of a filter to current year. I also need to unset/remove the - Any - option from the select list.

You can use hook_form_alter() to alter the any drupal form.
example :

function yourmodule_name_form_alter(&$form,&$form_state,$form_id){
  if($form_id == 'views_exposed_form'){
  $form['field_width_value']['#default_value'] = 'whatever you want';
  unset($form['field_width_value']['#options']['All']);

 }
}


Returning alternate HTTP codes for unpublished node I'm trying to return the 404 page instead of 403 response for unpublished nodes in Drupal 8.

I tested  kernel response subscriber, but found the code I was using would only change the status code to 404 from 403, not actually display the 404 page.  So maybe someone can show me how to generate a 404 page Response object there?

This is the code I was using:

class ResponseSubscriber implements EventSubscriberInterface {

  /**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents() {
    return [KernelEvents::RESPONSE => [['alterResponse']]];
  }

  /**
   * Change status code to 404 from 403 if page is an unpublished node.
   *
   * @param FilterResponseEvent $event
   *   The route building event.
   */
  public function alterResponse(FilterResponseEvent $event) {
    if ($event->getResponse()->getStatusCode() == 403) {
      /** @var \Symfony\Component\HttpFoundation\Request $request */
      $request = $event->getRequest();
      $node = $request->attributes->get('node');
      if ($node instanceof Node && !$node->isPublished()) {
        $response = $event->getResponse();
        // This changes the code, but doesn't return a 404 page.
        $response->setStatusCode(404);

        $event->setResponse($response);
      }
    }
  }

}

I finally resorted to removing this response subscriber completely and used hook_node_access like this:

use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Drupal\Core\Access\AccessResult;

function unpublished_404_node_access(\Drupal\node\NodeInterface $node, $op, \Drupal\Core\Session\AccountInterface $account) {

  if ($op == 'view' && !$node->isPublished()) {
    if (\Drupal::moduleHandler()->moduleExists('workbench_moderation') && $account->hasPermission('view any unpublished content')) {
      return AccessResult::neutral();
    }
    elseif (\Drupal::routeMatch()->getRouteName() == 'entity.node.canonical' && \Drupal::routeMatch()->getRawParameter('node') == $node->id()) {
      throw new NotFoundHttpException();
      return AccessResult::neutral();
    }
  }

  return AccessResult::neutral();
}

This seems to be in line with several answers on this site for Drupal 7.  But I wanted to see if anyone has a better way of doing this either with a KernelEvent subscriber, rather than hook_node_access.  It seems like what I want to do is test if a node is returning a 403 and then generate a new response with the 404 page and 404 status code.  I'm not sure how to do that.

You can try to do this earlier in an exception instead of a response subscriber. Extend HttpExceptionSubscriberBase, so you need less code to do this. Then replace the 403 with a 404 exception with the method $event->setException()

/src/EventSubscriber/Unpublished404Subscriber.php

<?php

namespace Drupal\mymodule\EventSubscriber;

use Drupal\Core\EventSubscriber\HttpExceptionSubscriberBase;
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

class Unpublished404Subscriber extends HttpExceptionSubscriberBase {

  protected static function getPriority() {
    // set priority higher than 50 if you want to log "page not found"
    return 0;
  }

  protected function getHandledFormats() {
    return ['html'];
  }

  public function on403(GetResponseForExceptionEvent $event) {
    $request = $event->getRequest();
    if ($request->attributes->get('_route') == 'entity.node.canonical') {
      $event->setException(new NotFoundHttpException());
    }
  }

}

mymodule.services.yml:

services:
  mymodule.404:
    class: Drupal\mymodule\EventSubscriber\Unpublished404Subscriber
    arguments: []
    tags:
      - { name: event_subscriber }

This replaces all 403 exceptions for canonical node routes. You can get the node object $request->attributes->get('node') if you want to check if this is really because the node is unpublished.


How to create multi sites I have just started to learn Drupal. So, I apologize to ask such a silly question here.

I wanted to create multi sites in Drupal. I have unlimited access to create Subdomains, Parked Domains, Addon Domains, Email Accounts and All SQl Databases with my hosting provider.

I wanted to create total 4 websites.

One that I have already created just to play and learn drupal with just Basic Structure and layout.

Rest of the three websites should have same layout and theme but different layout and theme then what I have already created called Basic Structure.

So, theses three purposes should have Same Theme and Same layout with Different Databses with Same User Names and Password.

One for Development purposes,
One for Staging purpose and
One for Clients Editing purpose (where client can play with our mock-up website for their content editing purpose).

I have read lots of reviews and steps to create multi sites in Drupal. Everyone explained it nicely in different ways. And I tried all the different ways to make it work. So, by trying and doing all those, I have messed up everything.

So, now I wanted to create again from beginning.
Can anyone help me with that? Can any one provide steps to how to create multi site in Drupal? I am just beginner for Drupal. So, can anyone please explain the steps in detail?

Also, What is the best practice to create multi sites? With Parked Domain or with Sub Domain?

Thanks for your help!

If the only purpose is to have a a dev/test/live environment, you should just go with a service like Pantheon which provides all of those for you with an ease of maintenance.

If you want to host it yourself, here's the gist of what you do...

Make sure you only have one Drupal root. Can't stress this enough. If possible, also be on version control (git) as this will help immensely.
Create 4 separate MySQL databases. Would go with a naming convention of like CODE_dev, CODE_test, etc.
Inside of your sites directory, create 4 directories, each with their own settings.php and files directory. You can name them whatever, just keep it consistent for ease of use. ie, dev.example, test.example, etc. Add their database credentials to their settings file.
In your sites directory, you will create a file called sites.php. In there, you will assign a directory name to a URL. So if you used dev.example as the name of your development site directory, and your subdirectory URL looks like dev.example.com, the format will look like this:

$sites['dev.example.com'] = 'dev.example';

Do that for each directory/site.
In your registrar for your DNS settings, point all of the subdirectories to the same IP or path as the top level domain (example.com), which should be the Drupal root directory. From there, Drupal will take care of the rest.

I think that's it, but anyone feel free to correct me. As far as the themes go, put it in sites/all/themes so all sites will have access to them. If you want a site to only have access to a specific theme/module, put it in THAT site folder.

For example: sites/dev.example/themes/THEMENAME


Customise Publishing Options based on Role Is there a simple way to customise the Publishing options so that certain Roles are only able to create content but not publish it. I have tried the Workflow and Workbench modules but they are way too complicated!

The Revisioning module automatically generates separate create, edit, and publish permissions by role for all content types for which revison control is enabled.  It also integrates with the Rules module.  You may find this to be a simpler approach.


D7 : Plupload version could not be determined I have installed the Plupload module and downloaded the library files v1.5.8.

I then uploaded the 'js' folder to '/sites/all/libraries/plupload/'

Having done so, 'admin/reports/status' now returns a message saying 'Plupload version could not be determined.'

Have I missed something obvious?

I have also tried the same with the latest v2.1.1 , with the same results.

Ok.

The problem was that i never uploaded the changelog.txt along with the js folder.


Syntax to use form_alter with array in name attribute I would like to modify some custom fields with form_alter in a contact form.

I know for example how to change placeholder for this "name" field  :
Note : I removed all the unnecessary html elements to make my question clearer

<input name="name" >

In form_alter :

$form['name']['#attributes']['placeholder'] = t('Nom');
$form['name']['#title_display'] = 'invisible';

But I don’t find the correct syntax when the name is with an array like :

<input name="field_prenom[0][value]" >

How to use form_alter with field_prenom[0][value] ?

I’ve tried this but it doesn’t work :

$form['field_prenom']['0']['value']['#attributes']['placeholder'] = t('Prénom');

Why are you using field's attribute 'name' instead of it's machine name 'field_prenom'? If you check in 'kint' you would get the hierarchy of 'placeholder' attribute.

You can update placeholder using form_alter only. Check the below example.

$form['field_name']['widget'][0]['value']['#placeholder'] = 'Nom';


How to create a relationship between user and some content type? I am new to Drupal and I need to create a relationship between user and content type.

There is a content type called 'Property'. The user who creates a property page must specify either:

I am an owner, OR
I am a tenant.

And I need to show this relationship on the property detail page.

How can I achieve this?

Note: I want to keep record of this, it mean the property detail page would always shows the previous tenant and owner information. And later that I want to show the reviews of user under owner and tenant tabs.

but I want to keep record of this, it mean the property detail page would always shows the previous tenant and owner information. And later that I want to show the reviews of user under owner and tenant tabs.

The initial question sounds simple but the added comment turns it
into a fairly complicated site build which I believe is outside the
scope of StackExchange questions. I'm just going to give the OP a brief overview of what I would do. Mods, feel free to edit or whatever you need to do.

So along with normal fields like images, locations etc., you need a place to store all of the information relating to each owner or tenant in each property.. The screenshot below gives a basic example of this.

Field Collection will let you store this information. You should have one field collection for owners and another for tenants. All reviews etc. of each person will have to be inside a field collection. Or reference a field collection using the module below.

Entity Reference will let you reference the people and vice versa. You'll use this a massive amount on a site like this for almost everything.

Entity Forms + Rules should allow tenants / owners to create property and also add themselves to a property by creating field collections from form data. You don't want to give them the ability to change other people's data so forms are essential.

Entity Reference Prepopulate will be essential for pre-filling form data and then disabling or hiding fields. This way, people can't view the workings of your site and more importantly, add and edit whatever they like. (for a regular end-user anyway).

Etc. Etc. Etc.

Anyways, that should be enough for you to look at for a couple of months. Good luck!


How do I show the site-wide contact form on a page in Drupal 7? I have seen other posts about this, but none specifically for Drupal 7, and I can't get it to work. I am trying to get the default contact form to show up below the main content of a page, perhaps in a block.

Do you have any suggestions?

You could create a custom block in a module and embed the form there. Something like this (I haven't tested this code!):

/**
 * Implements hook_block_info().
 *
 * This hook declares what blocks are provided by the module.
 */
function MODULENAME_block_info() {

  $blocks['contact_block_form'] = array(
    'info' => t('Contact Form'),
    );

  return $blocks;
}

/**
 * Implements hook_block_view().
 *
 * This hook generates the contents of the blocks themselves.
 */
function MODULENAME_block_view($delta = '') {
  //The $delta parameter tells us which block is being requested.
  switch ($delta) {
        case 'contact_block_form':
      $block['subject'] = t('Contact Us');
      // Load contact pages inc as the form definition sits there.
          module_load_include('inc', 'contact', 'contact.pages');
      $block['content'] = drupal_get_form('contact_site_form');
    break;
  }
  return $block;
}

Hope this helps


Why use constuctor injection in controllers or forms? Documentation is proposed to use injection in constructor instead of using \Drupal::service(). Why?

Example with injection:

class MyController extends ControllerBase implements ContainerInjectionInterface {
  protected $database;
  public function __construct(Connection $database) {
    $this->database = $database;
  }
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('database')
    );
  }
}

Example without injection (it is easier):

class MyController extends ControllerBase {
  protected $database;
  public function __construct() {
    $this->database = \Drupal::service('database');
    // or
    $this->database = \Drupal::database();
  }
}

As soon as you start to test MyController you will run into problems

The test harness must be able to instantiate the minimum amount of stuff  around your class to still be able to put it through its paces.

It is easier to mock up and inject a simple container.. rather provide \Drupal::service as it will rapidly spiral out of control and your test harness will have to provide a full drupal environment.

In more formal language you have just "tightly coupled" MyController to the drupal eco-system, and so you have made your code less reusable.


Is it possible with one of the template suggestion hooks to also specify a new template location? In a custom module I'm adding a custom page template suggestion per multi-site like following which would then search for page--MYSITE.html.twig in the current theme's /templates folder.

/**
 * Implements hook_theme_suggestions_HOOK_alter().
 */
function MYMODULE_theme_suggestions_page_alter(array &$suggestions, array $variables) {

  $site_path = \Drupal::service('site.path');
  $site_path = explode('/', $site_path);
  $site_name = $site_path[1];

  $suggestions[] = 'page__' . $site_name;
}

Question: Is it possible to also specify a new location for this template. Like let's say inside my custom module's /templates folder?

Why: It would let me use a core theme but with my custom template (without the need to add something custom to core or to create a new sub-theme, lazy as I am).

There are 3 suggestion hooks that come into my mind but with none if them it seems possible to also specify a custom location. Is this right? Or is there a way? Is it bad practice to do so?

hook_theme_suggestions_alter
hook_theme_suggestions_HOOK_alter
hook_theme_suggestions_HOOK

Is it possible with one of the template suggestion hooks to also specify a new template location?

You can specify a new template location in hook_theme():

  path: Override the path of the file to be used. Ordinarily the module or theme path will be used, but if the file will not be in the
  default path, include it here. This path should be relative to the
  Drupal root directory.

  Like let's say inside my custom module's /templates folder?

This means when using hook_theme() instead of hook__theme_suggestions_* the module's template folder is already default and you don't need to specify path.

So you can use this answer  hook_theme_suggestions_page() provide default template file inside module folder.


Rule to check specific field of content every week I have a content type called change_note, and within that I have a field called action, action_owner, a field called action_date, and one called action status. What I am trying to do, is get the site to check if the action status = pending, and if true send an email to the person listed in action owner.

I can work out how to do this if it is based on someone saving the content (using the rules module in drupal 7) but I can't see how you do it based on just a specific schedule. I've looked at the schedule module also, but am struggling to see how to do it in that.

A possible solution is to transform the rule you already have, into a Rules Component, so that your original Rule "schedules the execution" (using the Rules Scheduler submodule) of that Rules Component (eg X secs or mins "after saving the content") ... That Rules Component will then be executed next time cron runs.

If you then also add an extra Rules Action in that Rules Component (as last Rules Action) to reschedule the same Rules Component after 1 week, you should have achieved what your question is about.

Obviously, as soon as at least 1 of the Rules Conditions in your Rules Component are no longer satisfied, its Rules Actions will not be performed anymore, so that is when the weekly rescheduling also stops.

Easy, no?


From a custom module. How can I get the typed value from a textfield and put it in a variable? In a drupal page, I have a form where I need to read a text field value of an element, via javascript, when it is typed by the user, just after the input field lost the focus and before submit is done, I need to save it in a variable.

All entered values are in the $form_state array on submit. It is up to you to process that data and store it in a variable.

For example...

function mymodule_myform_submit($form, $form_state) {
  $text = $form_state['values']['myfield'];
  variable_set('mymodule_var', $text);
}

Then wherever else in the site you want to show it...

$myvar = variable_get('mymodule_var', '');

Of course, be sure to validate your input in the validate handler and anything else you want to process and save. This is pretty much the most basic approach in 7 to collect and store variables (especially not knowing the rest of your setup).


Failed to disabled specific page I'm creating an e-commerce using drupal.

In this site I have several catalogs to distinguish between some products. Let's say I have url site_home/catalog/1 , site_home/catalog/2, site_home/catalog/3, and site_home/catalog/4`.

I need to disable view for /catalog/1 , /catalog/2 and /catalog/3, but everyone can view /catalog/4 and newly created catalog in the future which will have id > 4.

I've tried using Pages Module to disable those pages.

I've created new rule with this module which is called /catalog/%catalog with arguments for %catalog is string. And then for Access Rule I added a criteria String: URL path. Current path type is not one of "catalog/1, catalog/2, catalog/3" but when i enabled this rule I got:

/catalog/1 - /catalog/3 --> access denied
/catalog/4 --> page not found

Any ideas why this is happening, and which settings did I missed?

If you are using taxonomy terms for your catalog you could try using taxonomy term permissions https://drupal.org/project/term_permissions. If you are using a view for each catalog you can just restrict access to each view as you like.


How to alter the welcome message after successfull registration A message is shown upon successful registration, with the following contents:

  A welcome message with further instructions has been sent to your e-mail address

I would like to change the content of that message and use a different HTML structure, e.g.:

Thanks for registering

 continue

How can I do that?

you can achive this and much more similar things with LoginToboggan module, from module page:

  The LoginToboggan module offers several modifications of the Drupal login system in an external module by offering the following features and usability improvements:
  Allow users to login using either their username OR their e-mail address.
  Allow users to login immediately.
  Provide a login form on Access Denied pages for non-logged-in (anonymous) users.
  The module provides two login block options: One uses JavaScript to display the form within the block immediately upon clicking "log in". The other brings the user to a separate page, but returns the user to their original page upon login.
  Customize the registration form with two e-mail fields to ensure accuracy.
  Optionally redirect the user to a specific page when using the 'immediate login' feature.
  Optionally redirect the user to a specific page upon validation of their e-mail address.
  Optionally display a user message indicating a successful login.
  Optionally combine both the login and registration form on one page.
  Optionally have unvalidated users purged from the system at a pre-defined interval (please read the CAVEATS section of INSTALL.txt for important information on configuring this feature!).
  Integrates with Rules module to do various tasks when a user validates via email validation process (see http://drupal.org/node/880904 for an example)

UI settings are simple and straight forward, and are located in admin/config/people/accounts


Changing font size to percent in theme I want convert font size in existing theme from px to percentage. The theme and the CSS. Should I change font-size in body and headers only, or better to change font size in all places in CSS? What is the correct way to specify font-size in percent in this particular CSS?

body {
  font-family: 'Open Sans', sans-serif;
  line-height: 160%;
  color: #666;
  font-size:13px;
  background: #fff;
}

h1 {font-size: 18px;}
h2 {font-size: 16px;}
h3 {font-size: 14px;}
h4 {font-size: 13px;}
h5 {font-size: 13px;}
h6 {font-size: 13px;}

This is the perfect place to use em instead of px for your font sizes. Change the font size in your body to font-size: 13px; or something, whatever size you want to be your standard size font.

Then, for all of the other elements, you can use em to adjust the size of the font based on percent. For example, font-size: 1.5 em; would be 1.5x larger than the standard size of 13px, and font-size: 0.5 em; would be 0.5x the size of the standard of 13px;


Show markers on gmap from all nodes exposed in view I'm using gmap module to mark job locations on a map. It now shows all locations of content type: jobs. Is there any way I can only mark the displayed jobs from my view block? I filter the jobs through exposed filters.

EDIT:

Just going to add this code here, might be useful for some. It puts the attachment in a block so you have more control over it.

<?php
//Puts gmap attachment in block so it's easier to theme

function gmap_block_block_info() {
  $blocks['gmap_attachment'] = array(
    'info' => t('Gmap Attachment'),
    'cache' => DRUPAL_NO_CACHE,
  );
  return $blocks;
}

function gmap_block_block_view($delta = '') {
  $block = array();
  if ($delta == 'gmap_attachment') {
   // $block['subject'] = t('Gmap Attachment');
    // Load the view.
    $view = views_embed_view('jobs_view_block', 'gmap_attachment');
                        //('machine_name_view', 'machine_name_display)
    if ($view) {
      $block['content'] = $view;
    }
    else {
      $block['content'] = t('The view is empty');
    }
  }
  return $block;
}

If you set up the map display as an attachment, you can set it to inherit the exposed filters that you've defined for your job listing. You'll get one set of exposed filters that controls both the listing and the map.

There may be some issues - see this blog post by someone solving what looks like the same problem.


Update node from comment form Is there a way in drupal 7 where you can change a value of a field from the comment form of that node you are commenting on? At the moment I have a comment form within a node which has the same field as that node. When I change that value, it does not update the nodes field but only changes the comment form's field.

Thanks for your help in advance!

I wrote a module to do this, you can probably modify it to suit your needs. http://drupal.org/sandbox/jrowny/1281972 I was using this for 'casetracker' type functionality.

Basically you install this and check for each field "this field is editable by comments."


Alter field settings using hook? EDIT: I need to alter the settings of an entity reference field for administrators only. I need to change from the settings in the first image, to the settings in the second image.

The reasoning is that normally when creating content, I want users to select from the options available in the view. The options in the view are the "Bands" (a content type) that each individual user has created. However, if an admin needs to moderate the content, they are not allowed to save it after editing because the content of the field is not an option available to the admin (i.e. the band entered by the original user, and currently saved to the entity reference field, is not a band created by the admin and is therefore not an option in the admin's array). On save by an admin, it fails to save and throws an error of "The referenced entity (node: XXX) is invalid", staying on the edit page.

I tried changing $form_state through hook_form_alter, but apparently $form_state settings aren't saved on submission. So, I tried adding the alters to a validation function, which also didn't work for me. Then, I found the settings within $context of hook_field_widget_properties_alter, but it seems that $context can only be referenced and not altered. I also came across this post, which seems to state that there isn't really a hook for altering field settings.

Unfortunately, I have realized that I really need this feature in order to moderate my site. As always, any help is incredibly appreciated, as this issue seems to be beyond my abilities.

Here's some screenshots as requested by Minty:

Casual user's options, populated by the view, include only their own bands

What I want in the admin's options, which should be all the bands authored by all users. (note that it currently shows all bands, because I figured out how to do contextual filter in the view based on the current user, not because I was able to alter the field settings as asked by the issue):

Without the above fix, only the admin's bands appear in the list when editing a node. Therefore, as stated in the issue, it throws an error that the previously saved band is not a valid option for the field, and the node cannot be saved.

With respect to your original post, I ran into this exact issue here in drupalsixlandia and resolved it with a dull ax inside of views.  By exact meaning I wanted to have a select list of bands created by a user presented to them when they wanted to add an album, but when an admin went in to add/edit things, s/he should see all of the bands on the system.

So, I created a view and used this view to populate the band Node Reference field in the album type in CCK.

I called it my_band and it filters on published bands and returns the Node Title of the band as the field. It has one argument, or in D7 a contextual filter, User Uid and in action to take if argument not present I provide a default argument via PHP code:

global $user;

if (in_array('super user', array_values($user->roles))) {
  return -1;
} else {
  return $user->uid;
}

Then in the Validation of that argument, I again use PHP:

if ($argument == -1) {
  return FALSE;
} else {
  return TRUE;
}

with display all values if validation fails.

So, now what happens (here at least) is if a casual user wants to create an album, s/he is presented with a list of only the bands s/he has created.  But, if any user with the super user role wants to create or edit an album, the validation is forced to fail, and the argument is ignored and all bands in the system are returned.

Perhaps with some D7ing of the code above this might work for you.


How to require a password when login in I'm making a CMS for my job on Drupal 7. when i go onto the login page I'm able to access the content on the site without having to enter the password. how do i change this?

Content created with drupal UI:

You need to configure proper user permissions for content. e.g. If you don't want to show content from Content type "Article" to anonymous user, Go to the permissions page (Administer > People > Permissions) and remove content view permissions for anonymous user.

Content Created programmatically :

1) Menu page :
While you register your custom menu with hook_menu, you should assign proper value to "access arguments". e.g.

/**
 * Implements hook_menu()
 */
function mymodule_menu() {
  $items['example'] = array(
    'title' => 'Example Page',
    'page callback' => 'example_page',
    'access arguments' => array('access content'),
    'type' => MENU_SUGGESTED_ITEM,
  );
  return $items;
}

2) Custom block:

For custom blocks, you need to define your access by user role. You can assign role visibility either by drupal UI(block configuration page) or you can do same thing programmatically.
Please refer below reference.

https://drupal.stackexchange.com/a/69897/57643

After configuring user permissions over content, drupal will show access denied page if user don't have permission to view content. Its drupal's default behavior. If you want to override this behavior, you can use contributed module Redirect 403 to User Login. This will redirect user to login page instead of just showing access denied page.


Behat @javascript test can not login user - incorrect username or password message I am running:

Drupal 7
Behat 3.5.0
Selenium 3.5.0
Chrome Driver 73.x

Using this test:

Feature: User Profile

Background:
  Given users:
    | name | status | roles |
    | incomplete | 1 | authenticated user |
    | complete | 1   | authenticated user |

  Given profiles:
    | drupal_username | field_profile_completed:value | field_first_name | field_last_name | field_birth_month | field_birth_day | field_degree | field_profession | field_specialty | field_organization | field_department |
    | incomplete | 0                                  | |  |  |  |  |  |  |  |  |
    | complete   | 1                                  | John | Doe | 08 | 03 | APRN | 15 | Anesthesiology | MyOrganization | MyDepartment |

@api
@noEncrypt
@defaultRegistration
@javascript
Scenario: As a user with an incomplete profile I should NOT see an icon indicating my profile is not complete.
  Given I am logged in as complete
  Then I should not see an ".js--user-profile-incomplete" element

@api
@noEncrypt
@defaultRegistration
@javascript
Scenario: As a user with an incomplete profile I should see an icon indicating my profile is not complete.
  Given I am on "/user/login"
  And I fill in the following:
    | name | incomplete|
    | pass | password |
  And press "edit-submit"
  Then I should be on "/"
  Then I should see an ".js--user-profile-incomplete" element
  When I wait for ".profile-notify__incomplete"
  Then I should see an ".profile-notify__exclamation" element

As you can see, I've tried  logging in using Given I am logged in as and tried logging in via a meta-step.  I can watch it in the browser and I'm getting an "Unrecognized username or password" error.

Login works fine without @javascript but I can't test the "When I wait" functionality.  If I use a break I can see that the users are created in the database.

Why are my @javascript tests not able to login?

It was a pain to track down but I traced it to the Security module.  It encrypts the password field on form submit - disabling the module allows Behat @javascript tests to run fine.


Restrict block visibility by page url Can I restrict the block visibility only show for /worker/*/ but not /worker/*/...?

I think block_exclude_pages was created for these types of scenarios


Does drush sql-sync support inter-db syncing? Can I use drush sql-sync between MySQL and PostgreSQL?

No, you cannot switch database types using drush sql-sync.  However, the DBTNG Database Migrator tool will do the conversion for you.


Simple drupal admin for clients? Basically Drupal is bit complicated for normal clients. Drupal 7 is better but still its not that user friendly for clients especially when comes to admin content or taxonomy!

Is there any module or themes which designed the client in mind? I found tabtamer and quickbar very helpful :) Any other to simplify admin section?

Although Workbench is good I use to build a custom admin with:

admin menu and admin menu source to build a custom admin menu per editor.

Also is good to have menu per role to choose what menus can edit editors.

With views and views bulk operations you can build a better administration interfaces.

With this you must built it, but I think you will get a better options that Workbench.

Also you can use dashboard to help user to see their options.


Where do I input drush commands? I am developing a Drupal 6.28 core website from a PC and was wondering where I would make drush commands to update the Drupal core to 7.

I am new to Drupal and PC Development, but I assume that it is a terminal command? Can I use the Windows Command Prompt? What directory would I need to be in to successfully run drush pm-update projects drupal-7.

Drush core does not support upgrading from Drupal 6 to Drupal 7 with any of the built-in commands pm-update only supports minor updates.  You'll need the Drush Site Upgrade command to advance to the next major version.

Note that this command has not been tested on Windows; it would probably be safer to run the command in a Linux environment.  Use a virtual machine (e.g. virtualbox) if you do not have a dedicated Linux environment.

Doing a major upgrade from Drupal 6 to Drupal 7 is a serious endevour; the Drush site-upgrade command will help you walk through the process, but it does not do all of the work for you.  The process isn't too hard if it goes smoothly, but you may run into contrib bugs that complicate the process.  An alternative method to upgrade would be to just make an equivalent Drupal 7 site from scratch, and then use drupal-to-drupal migration to move your content over.

Finally, to answer your specific question, there are a number of ways to specify the Drupal site that you would like Drush to operate on, but the easiest and most straightforward way would be to cd to the directory that contains your settings.php file (often sites/default).  You will also need to set up an alias (for your target Drupal site) if you use the Drush site-upgrade command; see the file examples.aliases.drushrc.php for instructions on how to do that.


Do I need to create a database table or are there already tools on offer? Pretty new to drupal, I'm afraid!

I have a excel table of survey results which I need to display certain cells from on a drupal page. I was thinking of creating a new table in my drupal database and then using PHP to link to it. I can't seem to create this table and what I've read suggests that this isn't a good way to go about it.

Does anyone know a better tool within drupal for this? Views or creating a custom module?

Thanks

Ed

Unless you need some additional styling or processing of data, the easiest way is to Embed a spreadsheet using Google Docs. You don't need any module for that.

If you need to have that data in Drupal as well, then check out Feeds Excel or this thread on drupal.org. The latter relies on the PHP Excel reader class which you should use in your custom module.


List Drupal Revisions I just discovered the revisions function of Drupal. I tried it and the new revisions are stored in the database. I expected to get a list of revisions on the edit node page. But i don't see anything like this.

Is it possible to list and switch between revisions from within the UI?

If you are viewing a node that has revisions enabled, there will be a tab which will show all revisions of the current node.  If you want to see a list of all revisions on the site you could use Views to create a view of node revisions.  Then you can even add filters on content types, creation date, etc to customize your list.


How do I create custom tokens? Possible Duplicate:
  Programmatically create a token

How do I create custom tokens?  Also, is it possible to attach a token to a callback function?  For example: If my string is 'this is my [name]', can I somehow make it so that [name] will be replaced with the return value of a function?

Take a look this link: token.inc
What you need is to create a module that implements hook_tokens and hook_token_info.


Installing Drush on Mac OS 10.13 (High Sierra) I've been struggling for a few days getting drush to install properly on my Mac.

I've followed the instructions on https://www.drupal.org/node/1674222

Composer installs fine, but when I cd into drush-master and run composer install, I get:

Loading composer repositories with package information
Updating dependencies (including require-dev)
Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - Installation request for drush/drush No version set (parsed as 1.0.0) -> satisfiable by drush/drush[No version set (parsed as 1.0.0)].
    - drupal/core 8.0.0-beta9 requires phpunit/phpunit 4.4.* -> satisfiable by phpunit/phpunit[4.4.0, 4.4.1, 4.4.2, 4.4.3, 4.4.4, 4.4.5] but these conflict with your requirements or minimum-stability.
    - drupal/core 8.0.0-beta8 requires phpunit/phpunit 4.4.* -> satisfiable by phpunit/phpunit[4.4.0, 4.4.1, 4.4.2, 4.4.3, 4.4.4, 4.4.5] but these conflict with your requirements or minimum-stability.
    - drupal/core 8.0.0-beta7 requires phpunit/phpunit 4.4.* -> satisfiable by phpunit/phpunit[4.4.0, 4.4.1, 4.4.2, 4.4.3, 4.4.4, 4.4.5] but these conflict with your requirements or minimum-stability.
    - drupal/core 8.0.0-beta6 requires phpunit/phpunit 4.4.* -> satisfiable by phpunit/phpunit[4.4.0, 4.4.1, 4.4.2, 4.4.3, 4.4.4, 4.4.5] but these conflict with your requirements or minimum-stability.
    - drupal/core 8.0.0-beta15 requires phpunit/phpunit 4.6.* -> satisfiable by phpunit/phpunit[4.6.0, 4.6.1, 4.6.10, 4.6.2, 4.6.3, 4.6.4, 4.6.5, 4.6.6, 4.6.7, 4.6.8, 4.6.9] but these conflict with your requirements or minimum-stability.
    - drupal/core 8.0.0-beta14 requires phpunit/phpunit 4.6.* -> satisfiable by phpunit/phpunit[4.6.0, 4.6.1, 4.6.10, 4.6.2, 4.6.3, 4.6.4, 4.6.5, 4.6.6, 4.6.7, 4.6.8, 4.6.9] but these conflict with your requirements or minimum-stability.
    - drupal/core 8.0.0-beta13 requires phpunit/phpunit 4.6.* -> satisfiable by phpunit/phpunit[4.6.0, 4.6.1, 4.6.10, 4.6.2, 4.6.3, 4.6.4, 4.6.5, 4.6.6, 4.6.7, 4.6.8, 4.6.9] but these conflict with your requirements or minimum-stability.
    - drupal/core 8.0.0-beta12 requires phpunit/phpunit 4.6.* -> satisfiable by phpunit/phpunit[4.6.0, 4.6.1, 4.6.10, 4.6.2, 4.6.3, 4.6.4, 4.6.5, 4.6.6, 4.6.7, 4.6.8, 4.6.9] but these conflict with your requirements or minimum-stability.
    - drupal/core 8.0.0-beta11 requires phpunit/phpunit 4.6.* -> satisfiable by phpunit/phpunit[4.6.0, 4.6.1, 4.6.10, 4.6.2, 4.6.3, 4.6.4, 4.6.5, 4.6.6, 4.6.7, 4.6.8, 4.6.9] but these conflict with your requirements or minimum-stability.
    - drupal/core 8.0.0-beta10 requires phpunit/phpunit 4.4.* -> satisfiable by phpunit/phpunit[4.4.0, 4.4.1, 4.4.2, 4.4.3, 4.4.4, 4.4.5] but these conflict with your requirements or minimum-stability.
    - Installation request for webflo/drupal-core-strict 8.6.x-dev -> satisfiable by webflo/drupal-core-strict[8.6.x-dev].
    - drupal/alinks 1.0.0 requires drupal/core * -> satisfiable by drupal/core[8.0.0, 8.0.0-beta10, 8.0.0-beta11, 8.0.0-beta12, 8.0.0-beta13, 8.0.0-beta14, 8.0.0-beta15, 8.0.0-beta16, 8.0.0-beta6, 8.0.0-beta7, 8.0.0-beta8, 8.0.0-beta9, 8.0.0-rc1, 8.0.0-rc2, 8.0.0-rc3, 8.0.0-rc4, 8.0.1, 8.0.2, 8.0.3, 8.0.4, 8.0.5, 8.0.6, 8.0.x-dev, 8.1.0, 8.1.0-beta1, 8.1.0-beta2, 8.1.0-rc1, 8.1.1, 8.1.10, 8.1.2, 8.1.3, 8.1.4, 8.1.5, 8.1.6, 8.1.7, 8.1.8, 8.1.9, 8.1.x-dev, 8.2.0, 8.2.0-beta1, 8.2.0-beta2, 8.2.0-beta3, 8.2.0-rc1, 8.2.0-rc2, 8.2.1, 8.2.2, 8.2.3, 8.2.4, 8.2.5, 8.2.6, 8.2.7, 8.2.8, 8.2.x-dev, 8.3.0, 8.3.0-alpha1, 8.3.0-beta1, 8.3.0-rc1, 8.3.0-rc2, 8.3.1, 8.3.2, 8.3.3, 8.3.4, 8.3.5, 8.3.6, 8.3.7, 8.3.8, 8.3.9, 8.3.x-dev, 8.4.0, 8.4.0-alpha1, 8.4.0-beta1, 8.4.0-rc1, 8.4.0-rc2, 8.4.1, 8.4.2, 8.4.3, 8.4.4, 8.4.5, 8.4.6, 8.4.7, 8.4.8, 8.4.x-dev, 8.5.0, 8.5.0-alpha1, 8.5.0-beta1, 8.5.0-rc1, 8.5.1, 8.5.2, 8.5.3, 8.5.4, 8.5.5, 8.5.6, 8.5.7, 8.5.8, 8.5.x-dev, 8.6.0, 8.6.0-alpha1, 8.6.0-beta1, 8.6.0-beta2, 8.6.0-rc1, 8.6.1, 8.6.2, 8.6.3, 8.6.x-dev, 8.7.x-dev].

etc...

Can someone tell me how to do this right?

Drush 9 only supports one install method. It requires that your Drupal
  8 site be built with Composer and Drush be listed as a dependency.

See http://docs.drush.org/en/master/install/

There it's recommended you start your Drupal 8 project with Composer. Then add Drush as local dependency to your project and use this local Drush to do things.

$ cd drupal
$ composer require drush/drush
$ vendor/bin/drush cr

Using the Composer template for Drupal projects Drush already is listed as a dependency.

$ cd ~/Sites
$ composer create-project drupal-composer/drupal-project:8.x-dev some-dir --stability dev --no-interaction
$ cd some-dir
$ cd web
$ ../vendor/bin drush si

Additionally you then can install the Drush Launcher which will replace the global drush command with a wrapper that always automatically finds and executes the local Drush in every directory.

If all of this is no option for you you might want to have a look at Having multiple Drush instances for different core versions where I show how you'd still be able to install a global Drush quite easily.


How do i create complicated content type? My apologies for bad english.

I want to create educational website with user generated content. Sort of like wikipedia. The problem is content is a little bit complicated.
It must have 4 tabs, which represent 4 stages of learning. Each individual tab must have guide (a basic content page with a text), a f.a.q. page, and a forum for users to open topics related to subject of learning and current stage.
I draw a markup for better undearstanding:

I tried to make it myself by creating a content type with a Field Group module and ended up with this:

Current problems are: a) guide on each tab is just a text but needs to be a title, which leads to page with a guide; b) have comments instead of forum under the tabs and no idea how to make it.

I would absolutely appreciate any help.

Install Field Collection

  Provides a field-collection field, to which any number of fields can
  be attached.

  A field collection is internally represented as an entity, which is
  embedded in the host entity. Thus, if desired field collections may be
  viewed and edited separately too.

and Field Collection Tab formatter

  Field collection tabs provides a field formatter that allows you to
  output a multi value field collection field as a tabset, with one tab
  per field collection item.

  You can optionally choose a field from the field collection item to be
  used as the tab title.

modules.

Your common elements, guide, faq, forum goes into the field collection. Also put the stage title as a field in the field collection. Then use the stage title field as the title for the tabs.


Prevent users of role from being flagged? The Flag module is pretty robust, so maybe I am missing something. It has a lot of access features as to who can flag/unflag but I can't seem to find a way to prevent a user/role from being flagged.

Scenario: Creating a flag where all administrators posts should not be able to be flagged but "authenticated users" should be able to flag other content for other roles. All roles content should be flaggable except for administrators (or "premium users")

There doesn't seem to be a "if user is of role X, disable the ability to flag/unflag using FLAG NAME" permission or setting.

Here is a sample code you could use for your custom template.

// Load the currently logged in user.
global $user;

// Check if the user has the 'standard' role.
if (in_array('standard', $user->roles)) {
  // enter the code to print your flag
}


Drupal 7: How to create a slideshow using Twitter Bootstrap Carousel? I'm a newbie when it comes to Drupal. But I know HTML/CSS, jQuery and Twitter Bootstrap quite well. I already have Bootstrap and jQuery installed and working fine.

I want to take advantage of Twitter Bootstrap responsive features and create a Twitter Bootstrap Carousel (photo slideshow) on the homepage. http://twitter.github.com/bootstrap/javascript.html#carousel

How can I set that up so that the photos and article links can be setup from Drupal 7 admin?

It's very late to answer this question, but I guess it will be helpful to any other like me who seeks for assistance in creating a carousel with the use of TB(Twitter Bootstrap).
Drupal community has come up with a module called views_bootstrap or bootstrap_carousel

which will help you create a responsive carousel powered by TB and Drupal.
The instructions given in the project page should almost give you what you want cheers!


How to delete stuck batch? What is a good way to delete a stuck batch in Drupal 7?

It is on a production server, we are using the Background Batch module so it shows us which one it is at admin/config/system/batch/overview.

I know I can just run a query and delete that row from the DB but wondering about other cleanup I should do too.

Another approach (if you don't want to run sql-statements directly) would be Queue UI:

  View queues and number of items
  Developers can define meta info about queues they create and process
  Process queue with Batch API
  Process queue during cron
  Remove leases
  Delete queue