How can I override the markup of a view I printed in a template file? I installed the Twig Tweak module on my site to render Views on the home page.
I want to make the display mode frontpage_tasks for the current user, his account, his stores and his groups.
{{ drupal_entity('user', user.id, 'frontpage_tasks') }}
{{ drupal_view('accueil_page_liste_des_taches_boutique', 'block_1') }}
{{ drupal_view('accueil_page_liste_des_taches_groupe', 'block_1') }}

Here is one of my Views :

The problem is that the Views module adds a lot of unnecessary markup that makes it impossible to display it correctly.
I just want to make the display mode, without any additional tags.
How to do this ? Is there a Twig code to render only Views without the additional View tags ?

UPDATE
I created an views-view--accueil_page_liste_des_taches_boutique.html.twig template. It only contains the following code :
{{ rows }}

I display the Views blocks with the code below, on my homepage :

                    {{ drupal_entity('user', user.id, 'frontpage_tasks') }}
                    {{ drupal_view('accueil_page_liste_des_taches_boutique', 'block_1') }}
                    {{ drupal_view('accueil_page_liste_des_taches_groupe', 'block_1') }}

I still have this damn markup :

                    ...

Is there a code in TWIG to remove this basisage ?
https://ibb.co/b1tKXhQ

You can enable Twig debugging for your site in sites/default/services.yml

    parameters:
      twig.config:
        debug: true

Clear cache
Inspect element in the browser and you will see the path to the template
Copy the template to your custom theme's templates/ directory and adjust the markup


How do I add the ability to change font size in CKEditor? I'm trying to install the CKEditor Font Size Module in my my editor. I installed the module via composer and then proceeded to copy the font/plugin.js file from the Font Plugin's page into libraries/ in my document root, per the instructions.

I also threw in a console.log() call into the font/plugin.js file to make sure it was loading. I modified the configuration of the Basic HTML editor to include the font size and family buttons in the toolbar on the /admin/config/content/formats/manage/basic_html page of my site. When I go to create a piece of content that uses the Text Editor, I don't see the font/size buttons I've configured.

Checking the Javascript console, I see my log message so I know the font/plugin.js file is being loaded. There are no error messages in the console. Why would the buttons not be showing up in this case?

Kevin's comment was spot on and it was in fact the Basic HTML configuration that was preventing the button from rendering. Specifically, the filter "Limit allowed HTML tags and correct faulty HTML" was the issue. The buttons rendered correctly in Full HTML mode so that was the hint.

In the filter configuration at the bottom of the /admin/config/content/formats/manage/basic_html page, I modified the allowed tags. By default the filter allows plain span tags without any attributes. However, this plugin uses span tags with inline style attributes. As a result, I had to change  to  in Allow Tags list.

I can now see the font and size buttons in the editor, and using the tool injects HTML like the following:

The Quick red fox jumps over the lazy brown dog


Drush Make for a custom module hosted at github I am trying to fetch a custom module versioned at github.com via drush make, but I get

Could not retrieve version information for custom_migration
Non-existent project type  on project techarena_migration

My drush make file section for the custom module is the following:

projects[custom_migration][subdir] = "custom"
projects[custom_migration][type] = "module"
projects[custom_migration][download][type] = "git"
projects[custom_migration][download][url]="git@github.com:qed42/custom_migration.git"

I also tried giving the branch parameter, but no change

projects[custom_migration][download][branch] = "master"

This is a private repository, could it be that?

Update: I am so sorry, I was using the wrong makefile. Sorry to have wasted your time. I am not sure if I should close the question?

P.S git:// doesn't work with private repo on github, git@github.com does!!

According to the documentation, you have to write the download url line this way:

projects[mytheme][download][url] = "git://github.com/jane_doe/mytheme.git"


Call to undefined function ctools_ajax_text_button() What I need is a link to click and open a form in a modal.

Call to undefined function ctools_ajax_text_button() in ctools\includes\modal.inc on line 184

This is how I'm calling the function in hook_page_build() function.

ctools_include('modal');
ctools_modal_add_js();

$links[] = ctools_modal_text_button(t('Modal Login'), 'modal_forms/nojs/login', t('Login via modal'));

And this also not working.

$test = ctools_modal_text_button('Test Link', 'node/123', 'alt here', 'no-class');

I forgot to add ajax :)

ctools_include('modal');

ctools_include('ajax');

ctools_modal_add_js();


Problem with programmatically creating a redirect Background

Client has Event webforms hosted externally by a marketing automation service, leading to an unusual situation: a node of Event content type should have its summary displayed in certain Views on the client site, but navigating directly to the node address should result in a 301 redirect to the offsite form.

Client can achieve this manually by using the Redirect module:

/admin/config/search/redirect/add?redirect=node/1234

... and then entering the node path in the From field and the offsite destination in the To field. (Yes, this is exactly backwards, but it kind of works.) However, they would like to automate this process.

I tried to do this with Rules:

Events:

After saving new content of type Event
After updating existing content of type Event

Conditions:

NOT Data value is empty (Parameter: Data to check: [node:field-external-url])

Actions:

Page redirect (Parameter: URL: [node:field-external-url])

Unfortunately, this does not modify the Page Redirect settings on the node by adding an entry to the redirect table in the database.

Instead, it fires a one-time system event and redirects the site administrator to the desired URL at the moment that the Event content node is created or updated. Subsequent visits to the node URL do not redirect site visitors; instead, they see the node at that URL.

So, I'm trying a different approach, with a small custom_event_redirect module:

/**
 * Implements hook_form_alter().
 */
function custom_event_redirect_form_alter(&$form, &$form_state, $form_id) {
  // add submit handler only to Event content forms
  if ($form_id === 'event_node_form') {
    array_unshift($form['#submit'], 'custom_event_redirect_search_form_submit');
  }
}

/**
 * Drupal FAPI submit handler implementation
 */
function custom_event_redirect_search_form_submit(array $form, array &$form_state) {
  if (!empty($form['field_external_url']['und'][0]['value']['#default_value'])) {
    //create redirect programmatically

  }
}

Is it possible to use the Redirect API to fire off a redirect_edit_form_submit() when the event_node_form is submitted?

This is such an edge case. Google results are skewed heavily toward drupal_goto() redirects after form submission -- but if that was what I wanted, I could have used Rules.

I don't want to fire off a one-time redirect on form submission; I want to add an entry to the redirect table on form submission.

¯\_(ツ)_/¯

Rabbit Hole should get you close, if not entirely there. After enabling the rh_node submodule, admin/structure/types/manage/event will show "Rabbit Hole settings" where you can set the behavior to "Page redirect" and the "Redirect path" field has "You may enter tokens in this field" in the help text, so [node:field-external-url] should work there. You probably need custom code for your "Conditions: NOT Data value is empty" but you might be able to have a custom module for that, so long as you set the weight of your custom module such that it runs earlier than rh_node (alternatively, Rabbit Hole offers a PHP filter, but that has an implied dependency on Bad Judgement).

Out of the box, Rabbit Hole does offer a "Bypass Rabbit Hole action for nodes" permission that you can grant to administrators.


Where do I find a list of commonly used features? I've been searching around for some useful features.  I would assume that there are some common features that people use all the time, like an image gallery. Is there a place where people contribute these? I have searched Google and drupal.org but can't seem to find anything.

It looks like the Debut Project collection might be up your alley. From the project description:

  Debut is a set of baseline Drupal features available as apps and designed to work independently yet integrate seamlessly together.


Image redirection problem I have created a product teaser using views and included images as one of the fields (by including  *(Products referenced by field_product) Field: Images* ). In the settings for  " (Products referenced by field_product) Field: Images " I linked the image to "content". But the result is something different. Instead of linking the image to "original content", Drupal is linking it to the edit page of that content. Please help me fix this problem. I want my "product Image" to link to its "original content(the product itself)".I Followed this procdure to create product teaser (Advanced Product Display Listing using Views).

You can follow these steps to achieve what you want.

Add a field in your views Content:Nid.
Rearrange the field & place above added field at the top of yours (Products referenced by field_product) Field: Images.
Edit (Products referenced by field_product) Field: Images & set Link image to Nothing.
Click on Rewrite results & check Output this field as a link.
Paste node/[nid] token in Link path.
Save it & you are done :)


DraggableViews not displaying drag-handles I installed the DraggableViews module on Drupal 8.
On one of my views, I replicated the page that I currently use to display the content that I want.
I renamed the new page adding "Admin" to the title
Then I follow the instructions I found on various places:

Change the Admin block Format section and choose Table.
Add the field "Draggableviews: Weight" at the Fields section, place it after the "Content: Title" field.Make sure not to check "Exclude from display". Please note that the instructions mention the "Draggableviews: Content" field but I don't have this option (Is there something wrong here?)
Add "DraggableViews: Weight" at the Sort criteria section and place it as the first Sort criteria.
Save the view.

then I get a page the list all my items, show the weight of each of the items (0 by default) but I can't change the weight and no drag-handles are shown.

Any help?

All "draggable" tables in Drupal have a switch that turns the draggable javascript interface off, and allows you to order the items using a less interactive "ordinary" form with fields to enter weight numbers and a submit button.

There is a link, usually at the top right of the table, that says Hide row weights if you have the draggable option turned off, and Show row weights if you have it on.

Look for that link, it's probable you just have it turned off.

Once you make the switch it will be "remembered" in a cookie so it will apply for all the draggable tables on the site. Maybe you changed it on some other table, Drupal remembered it, and you're simply seeing the non-draggable case in your draggable views.

I guess this brings up to the surface that "Draggable views" isn't quite an accurate name, because it works even without dragging. Maybe it should be called "Order views" or something similar, but javascript tools usually win that race and this example illustrates it.

I hope this is the issue here. Nothing broken, just a temporary UI blindspot, we've all been there :)


Colorbox grouping content linked from same page - how to stop it? I have a page with two links on it that each open in Colorbox modals.

When I click on one of them, it opens them both, as if they were a gallery, with forward and back arrows to navigate between them.

I have looked through the Colorbox configuration options and I can't figure out how to stop this behavior.

I figured this out, with crucial help from the #Drupal IRC channel.

I was using Colorbox Node along with Colorbox, and I was confusing the documentation from the two of them. Specifically, Colorbox requires links to have the class colorbox-load while Colorbox Node requires that they have the class colorbox-node. The really confusing thing about this is that if you use colorbox-load instead of colorbox-node, it works, sort of. It was loading the entire page including headers, footers, and all markup and styles, into the modal, as if it were an iframe.

So step one was to start using the correct link class.

After changing the link class to colorbox-node, however, all I saw in the modal was the title of the target page, unstyled, on a white background. Poking around in the Colorbox settings was, unsurprisingly, unhelpful. Again, #Drupal pointed me in the right direction: Colorbox Node creates a display of the content type and makes the body hidden by default for some reason.

So step two was going to structure > content > [content type of target node] > manage display and choosing "Colorbox" (next to "Default" and "Teaser") to unhide the body of the target node.

Voilá, you now have the title and body pulled out from your target node and appearing isolated in your Colorbox modal.


Can't update Drupal core to 7.34 I am trying to update Drupal core from 7.32 to 7.34 using drush. It initially appears to be sucessful, however the status report and /modules/system/system.info still show the version number as 7.32. I have tried running update.php but it says that there are no updates.

I have another Drupal site on the same server that is very similar and had no issues updating it to 7.34.

The output of drush when updating is:

drush5.5-sp pm-update
 Name    Installed Version  Proposed version  Message
 Drupal  7.32               7.34              SECURITY UPDATE available

Update information last refreshed: Thu, 11/27/2014 - 22:43
Code updates will be made to drupal core.
WARNING:  Updating core will discard any modifications made to Drupal core files, most noteworthy among these are .htaccess and robots.txt.  If you have made any modifications to these files, please back them up before updating so that you can re-create your modifications in the updated version of the file.
Note: Updating core can potentially break your site. It is NOT recommended to update production sites without prior testing.

Do you really want to continue? (y/n): y
Project drupal was updated successfully. Installed version is now 7.34.
Backups were saved into the directory                                [ok]
/srv/users/site/drush-backups/u7i6t765rib76nb7tionytbyi_site/20141127154450/drupal.
No database updates required                                         [success]
'all' cache was cleared.                                             [success]
Finished performing updates.                                         [ok]

You don't need the drush. download the latest version, remove the /sites folder from the downloaded files and then simply copy and replace the files with the existing ones.


How do I display a sorting button in views? I need to create functionality so that the user can switch between different sort/filter behaviors in a view.  Hopefully, without loading a different page.

For example, I have a list of projects on my site and I want buttons that the user can click to hide projects that aren't of a specific type.  ie: show only print, show only web, show only video, etc.

Is there any way to do this asynchronously with views, rather than custom scripting stuff with jquery or linking to totally different pages?

You can set your filters and sorts to be exposed, which means the end user can interact with them choosing how to sort or filter the results,

There is also a setting in the "Advanced" column on the right of the views admin page called "Use AJAX". Set that to "Yes" and you will no longer have to have page loads when the user changes filters and sorts.

Note: If your view is a block view, you must turn on ajax for exposed filters to work.

Also, in the "Advanced" column if you click the "Settings" link for the "Exposed form style" option. In there you can check the "Autosubmit" checkbox, which will mean the view will be reloaded when the user selects a filter, without them having to click submit. This may or may not be desirable depending on your use case.

One last thing is the "Exposed form in block" setting. If you set that to "Yes" then a block will be available that will contain the filter and sort settings, so you can put them wherever you want, instead of them having to be in the top of the view.

Note: You cannot use exposed form in block with a block view. A potential workaround (I have not actually tried it) is here - https://drupal.stackexchange.com/a/38994/10729


Dynamic section-specific submenu I have a problem that's driving me bananas on Drupal 7.

My need is very simple. I have a site with a bunch of communities with URLs like

http://domain.example/community/communityname

All of these communities have similar structures with pages like "learning", "blog" etc. which are at URLs such as

http://domain.example/community/communityname/learning

I need to create a navigation menu for each of these communities without actually creating a separate menu item for each. How can this be achieved?

I tried doing this with hook_menu and even after 3 hours of relentless googling and fiddling about I just can't seem to get this working.

Any help is much appreciated.

Here's my non-working code:

function mymodule_menu(){
    $items = array();
    $items['community/%mymodule_arg/learning'] = array(
        'title' => 'Learning',
        'page callback' => 'mymodule_view_page',
        'page arguments' => array(1),
        'menu_name' => 'menu-community-menu',
        'type' => MENU_NORMAL_ITEM,
        'access callback'=>TRUE
    );
    return $items;
}

function mymodule_arg_to_arg($arg) {
    return (empty($arg) || $arg == '%') ? "community-a" : $arg;
}

function mymodule_view_page($context) {
    return drupal_goto("community/" . $context . "/learning");
}

If I replace the wildcard from the items array key and replace it with a static string, the code works. Also if I just return a string from mymodule_arg_to_arg() it works. But I just can't seem to make it dynamic.

You seem to me trying to make it more complicated as necessary. You can simply use the arg function http://api.drupal.org/api/drupal/includes--bootstrap.inc/function/arg/7

in your example domain http://domain.example/community/communityname

arg(0) = community;

arg(1) = communityname;

so why not just use arg(0) and arg(1) in your dynamic link url


JSON Schema of my entities In the process of building a headless website and one of the first requirements it was to provide JSON schema of my data model (JSON data from my entities.)

Here will be an example of the user entity.

{
    "User": {
        "type": "Object",
        "fields": {
            "first_name": {"type": "String"},
            "last_name": {"type": "String"},
            "age": {"type": "Number"}
        },
    }
}

This does not provide any real values rather than extra information to front-end developers to have an understanding of API. This is also useful for making sure that the API is always valid because we could provide a middleware that tests the API before even gets to the front-end app.

There are more examples of these JSON schemas at - https://www.npmjs.com/package/web-service-api

Do you know if there is an away to get this type of information in Drupal 8 programmatically?

The following code exposes an API that returns the field and properties data of the user entity type.
It uses a recursive method and the nature of typed_data to achieve such goal.

The post and get methods are called because they are the lowercased versions of GET and POST.

The below code relies on Drupal 8.2 because GET requests are problematic in Drupal 8.1 See this issue

<?php

namespace Drupal\sandbox\Plugin\rest\resource;

use Drupal\Core\Entity\EntityFieldManagerInterface;
use Drupal\Core\Field\FieldStorageDefinitionInterface;
use Drupal\Core\TypedData\ComplexDataDefinitionInterface;
use Drupal\Core\TypedData\DataDefinitionInterface;
use Drupal\Core\TypedData\DataReferenceDefinitionInterface;
use Drupal\Core\TypedData\ListDataDefinitionInterface;
use Drupal\Core\TypedData\PrimitiveInterface;
use Drupal\Core\TypedData\Type\BooleanInterface;
use Drupal\Core\TypedData\Type\FloatInterface;
use Drupal\Core\TypedData\Type\IntegerInterface;
use Drupal\Core\TypedData\Type\StringInterface;
use Drupal\rest\ModifiedResourceResponse;
use Drupal\rest\Plugin\ResourceBase;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Represents entities as resources.
 *
 * @see \Drupal\rest\Plugin\Deriver\EntityDeriver
 *
 * @RestResource(
 *   id = "user_type",
 *   label = @Translation("User type"),
 *   uri_paths = {
 *     "canonical" = "/user_type",
 *   }
 * )
 */
class UserTypeResource extends ResourceBase {

  /**
   * @var \Drupal\Core\Entity\EntityFieldManagerInterface
   */
  protected $fieldManager;

  /**
   * UserTypeResource constructor.
   * @param array $configuration
   * @param string $plugin_id
   * @param mixed $plugin_definition
   * @param array $serializer_formats
   * @param \Psr\Log\LoggerInterface $logger
   * @param \Drupal\Core\Entity\EntityFieldManagerInterface $field_manager
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition, array $serializer_formats, \Psr\Log\LoggerInterface $logger, EntityFieldManagerInterface $field_manager) {
    parent::__construct($configuration, $plugin_id, $plugin_definition, $serializer_formats, $logger);
    $this->fieldManager = $field_manager;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static(
      $configuration,
      $plugin_id,
      $plugin_definition,
      $container->getParameter('serializer.formats'),
      $container->get('logger.factory')->get('rest'),
      $container->get('entity_field.manager')
    );
  }

  public function post() {
    return $this->resolve();
  }

  public function get() {
    return $this->resolve();
  }

  protected function resolve() {
    $field_definitions = $this->fieldManager->getFieldDefinitions('user', 'user');

    $data = [
      'type' => 'Object',
      'fields' => [],
    ];

    foreach ($field_definitions as $field_name => $field_definition) {
      /** @var \Drupal\Core\Field\FieldStorageDefinitionInterface $storage_definition */
      $storage_definition = $field_definition->getFieldStorageDefinition();
      $data['fields'][$field_name] = [
        'type' => 'Array',
        'element' => $this->transformFieldDefinition($storage_definition),
      ];
    }

    return new ModifiedResourceResponse($data);
  }

  protected function transformFieldDefinition(FieldStorageDefinitionInterface $storage_definition) {
    $fields = [];

    foreach ($storage_definition->getPropertyDefinitions() as $property_name => $property_definition) {
      $fields[$property_name] = $this->transformDataDefinition($property_definition);
    }

    return [
      'type' => 'Object',
      'fields' => $fields,
    ];
  }

  protected function transformDataDefinition(DataDefinitionInterface $definition) {
    if ($definition instanceof ComplexDataDefinitionInterface) {
      $fields = [];

      foreach ($definition->getPropertyDefinitions() as $property_name => $property_definition) {
        $fields[$property_name] = $this->transformDataDefinition($property_definition);
      }

      return [
        'type' => 'Object',
        'fields' => $fields,
      ];
    }
    elseif ($definition instanceof ListDataDefinitionInterface) {
      return [
        'type' => 'Array',
        'element' => $this->transformDataDefinition($definition->getItemDefinition()),
      ];
    }
    elseif ($definition instanceof DataReferenceDefinitionInterface) {
      return $this->transformDataDefinition($definition->getTargetDefinition());
    }
    else {
      $type = "Unknown ({$definition->getDataType()})";

      $class = new \ReflectionClass($definition->getClass());
      if ($class->isSubclassOf(PrimitiveInterface::class)) {

        if ($class->isSubclassOf(StringInterface::class)) {
          $type = 'String';
        }
        elseif ($class->isSubclassOf(IntegerInterface::class) || $class->isSubclassOf(FloatInterface::class)) {
          $type = 'Number';
        }
        elseif ($class->isSubclassOf(BooleanInterface::class)) {
          $type = 'Boolean';
        }
      }
      else {
        switch ($definition->getDataType()) {
          case 'language':
            $type = 'String';
            break;
        }
      }

      return [
        'type' => $type,
      ];
    }
  }

}

The definition of rest.resource.user_type configuration.

id: user_type
plugin_id: 'user_type'
granularity: method
configuration:
  GET:
    supported_formats:
      - json
    supported_auth:
      - cookie
  POST:
    supported_formats:
      - json
    supported_auth:
      - cookie
dependencies: {}


Remove menu item from display How can I programatically remove/hide a menu item when the menu is displayed?

If I understand well your question, you can use theme_menu_item_link() function to your template.php of your theme.

This is an example that I have tested (in this example Garland is the theme used, so you must replace the name of the function with the respective name):

Here is the example menu:

This is the function to remove the items:

function garland_menu_item_link($link) {
  if (empty($link['localized_options'])) {
    $link['localized_options'] = array();
  }
  if ($link['title'] != 'item 1') {
    $link['localized_options'] += array('html' => TRUE);
    return l('' . $link['title'] . '', $link['href'], $link['localized_options']);
  }
  else {
    unset($link);
  }
}

Please note that I have added if($link['title'] != 'item 1'){.. to detect the menu item, and remove it (with unset($link)).

This is the code for changing the text:

function garland_menu_item_link($link) {
  if (empty($link['localized_options'])) {
    $link['localized_options'] = array();
  }
  if ($link['title'] == 'item 1') {
    $link['title'] = 'new text';
  }

  $link['localized_options'] += array('html' => TRUE);
  return l('' . $link['title'] . '', $link['href'], $link['localized_options']);
}

Remember to clear the cache to see the changes.

I found these other resources related with theme_menu_item_link(): http://drupal.org/node/245156, http://drupal.org/node/249864, http://drupal.org/node/417482.


How can I make SMTP plugin work with multiple languages? I'm using the SMTP Authentication Support plugin for mail from my Drupal 8 server.

Sending mail from a webform works fine as long as the visitor is using the default language, which is English. It does not send when using any other language.

The message in the error log is not helpful:

  Error sending e-mail from email@site.com to email@site.com: SMTP Error: Could not connect to SMTP host.

This makes no sense to me. How can it not be connecting, when the same connection information is ok on English?

How can I resolve this? Here's what I've tried to do:

I've asked for support on SMTP's issues page, but have not received any response yet.
Set the language detection up two different ways: by domain or by URL. Same result on both.
Tried two different SMTP servers, with the same result on both.
Tried SSL and standard protocols for SMTP.

The problem is that the parameters are not translatable. In my case it has been solved by overriding the values of the port and protocol variables in settings.php.

$config['smtp.settings']['smtp_port'] = '587';
$config['smtp.settings']['smtp_protocol'] = 'tls';


Clean way of receiving image_dimensions after applying image_style I'm quite a Drupal-Newbie and am wondering what would be the best way to receive the dimensions of an image after applying some styles.

I have the URI of the image before the style and absolute URL after applying the style with image_style_url

I found one solution, which does not look neat, but works:

$sizes = getimagesize(drupal_realpath(image_style_path('style', $imageURI)));


Why are we getting anonymous account creation on a site where this is turned off? On one of our Drupal 7 sites (it's at v. 7.32) we're getting occasional 'bot based account creation requests. This is an information-only site where regular users will never log in, only administrators should be allowed to create accounts and only administrators and content creators can log in.

In Configuration under People "Who can register accounts?" is set to "Adminstrators only." Is that not sufficient to stop this from happening?

The accounts are being created but the admin email is being contacted to approve them, so these users are not actually able to log in, but we'd like to stop this account creation altogether.

Has anyone ever seen this?

Does your drupal version is up to date ?

Versions before 7.32 need a fix to protect your Drupal from SQL injection ...

https://www.drupal.org/SA-CORE-2014-005

Theres a link to a patch if you cant do the full update


Control content access based on field value in user profile? I have two specific user types on my website: "Manager" and "Employee". I will have ten managers and 100 employees. Each Manager will manage 10 employees.

Employees will have permissions to create "Content Type A" nodes. I want their managers to be able to edit/view only those "Content Type A" nodes that were created by their employees.

I created a User Reference field in the profile form. that UR field is populated only with the names of the Managers. When a new employee is registered their manager's name will be selected from that UR field.

I feel like I should be able to control each Manager's access to Employee-created content based on that UR value in each employee's profile, but I can't quite wrap my head around how to accomplish that. Would Views be the best bet, or would I need to develop a custom permissions module that compares the logged-in Manager's UID with the UID related to the Manager selected in the UR field on the employee profile? Or perhaps some kind of Rules setup?

Thanks!

User Relationships module seems to be the answer:

  User Relationship Node Access lets users control access to their content based on relationships


How to get rid of empty blocks on the dashboard? I created a View called Recent comments and added a block to my dashboard. Afterwards, I deleted the View, which results in an empty block on my dashboard

and the following error message:

  Notice: Undefined index: recent-comments-block in
  dashboard_page_build() (line 192 of
  C:\wamp\www\mysite\modules\dashboard\dashboard.module).

I tried to drag the empty block away after clicking Customize dashboard, but every time I hit Done, it is displayed again. Clearing caches did not help either.

What should I do to get rid of the empty block?

I think this is a long-standing issue with dashboard blocks. See the discussion, and several patches, here: https://drupal.org/node/936798

I haven't tried any of these patches myself.

If you just want to get rid of the error, I believe you can delete inactive blocks in the database directly, as described here: https://drupal.org/node/1202500

The gist is that you look for and remove blocks in the block table where region = dashboard_inactive


How can I programatically add a shipping method to a store? I am using Commerce with Marketplace, and am using the Shipping module.
In my commerce marketplace, users become sellers via a custom form, where I create the store entity on submit.  Currently, to attach a shipping method, it has to be done in commerce admin via a checkbox:

My marketplace can have an unlimited number of stores, making management of them via checkboxes unfeasible.  How can I add a shipping method to a store?  There's a table commerce_shipping_method__stores:

Can I simply make an insert into this table and set the stores_target_id value to the new store id after the new store is created?

With custom module code, you can add a new store like this:
function mymodule_entity_insert(Drupal\Core\Entity\EntityInterface $entity) {

  if ($entity instanceof Drupal\commerce_store\Entity\StoreInterface) {

      $sm_id = 1; // I can see Shipping Method ID is 1 from your table screenshot
      $shipping_method = Drupal\commerce_shipping\Entity\ShippingMethod::load($sm_id);
      $store_ids = $shipping_method->getStoreIds(); // get existing IDs
      $new_store_id = $entity->id(); // get new id
      $store_ids[] = $new_store_id; // add new to existing
      $shipping_method->setStoreIds($store_ids); // set
      $shipping_method->save();

  }

}

In the above code, when a store is created, it automatically adds it to the shipping method.

But if your question is to add already existing stores to the shipping method, then run this code only once:
      $sm_id = 1; // I can see Shipping Method ID is 1 from your table screenshot
      $shipping_method = Drupal\commerce_shipping\Entity\ShippingMethod::load($sm_id);
      $store_ids = [1, 2, 3, 4, 5, 6]; // Array of all the store IDs that belong to this shipping method.
      $shipping_method->setStoreIds($store_ids); // set
      $shipping_method->save();

The better API solution
Thanks to 4k4's answer I was able to commeup with a more efficient solution.
function mymodule_entity_insert(Drupal\Core\Entity\EntityInterface $entity) {

  if ($entity instanceof Drupal\commerce_store\Entity\StoreInterface) {

      $sm_id = 1; // I can see Shipping Method ID is 1 from your table screenshot
      $shipping_method = Drupal\commerce_shipping\Entity\ShippingMethod::load($sm_id);
      $new_store_id = $entity->id(); // get new id
      $shipping_method->{'stores'}[] = $new_store_id; // appends new store to existing list.
      $shipping_method->save();

  }

}

Manual Solution

Quick follow up, do I have to load all the stores at once? When I have
1000+ stores and more, that seems like it will be a little resource
intensive. Is it possible to just add the new store?

At this point, you wouldn't want to use the entity API and do Drupal\commerce_shipping\Entity\ShippingMethod::load as this would contain all the 1000+ store IDs, you will have to manually DB query & insert:
function mymodule_entity_insert(Drupal\Core\Entity\EntityInterface $entity) {

  if ($entity instanceof Drupal\commerce_store\Entity\StoreInterface) {

    $sm_id = 1; // Shipping Method ID
    $connection = \Drupal::database();

    $query = $connection->select('commerce_shipping_method__stores', 'csms');
    $query->range(0, 1)
      ->orderBy('delta', 'DESC')
      ->condition('csms.entity_id', $sm_id)
      ->addField('csms', 'delta');
    $last_delta = $query->execute()->fetchField();
    $new_delta = $last_delta + 1;
    $new_store_id = $entity->id(); // new store ID

    $insert = $connection->insert('commerce_shipping_method__stores')
      ->fields([
        'entity_id' => $sm_id,
        'stores_target_id' => $new_store_id,
        'revision_id' => $sm_id,
        'delta' => $new_delta,
        'bundle' => 'commerce_shipping_method',
        'langcode' => 'en',
      ])
      ->execute();

    $storage = \Drupal::entityTypeManager()
      ->getStorage('commerce_shipping_method');
    $storage->resetCache([$sm_id]); // Flush Cache

  }

}


REST Export Serializer adds quotation marks to my field I'm using the REST export to expose a list of my nodes including some fields.
One of the fields is paragraphs field with subfields.

I have written a formatter for this paragraphs field that puts together some of the fields within the paragraph and renders them as a json object.

The only problem I have is that the serialiser automatically adds quotation marks, which turns my json object into a string and thus renders the formatter futile.

Can I somehow tell the serializer to not do that to my field and just print the json string without doing anything to it? I couldn't find any setting in the view that would help me. Using a "raw output" only prints the paragraph ID.

EDIT: A couple of hours later I stumbled upon this article (https://blog.karmacomputing.co.uk/drupal-8-rest-endpoint-with-entity-reference-field-set-to-unlimited-using-views/) and the REST Views module (https://www.drupal.org/project/rest_views) which basically does what I want to achieve, but unfortunately only renders the entire paragraph content as an array and doesn't allow to change the labels. A boolean field is also printed as a string.
It's close to what I need, but not quite it.

I had to change my overall approach to the problem, but managed to solve the serialising problem by using two additional modules:

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

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

The description of the REST Export Nested explains everything.
The only thing that might provide problematic is the performance as this involves potentially calling a lot of sub-views. So maybe writing a custom normaliser as indicated in one of the comments is a better approach.


Form Rebuild by Ajax Call I have a form which is built using some data which is partially random. Unfortunately, at the first AJAX call (nothing has been submitted yet, neither AJAX, nor in the normal way) the form will be rebuilt so that all random inputs are lost. Is there any way to avoid it?

class AjaxTestForm extends FormBase {

  public function getFormId() {
    return 'ajax_text_form';
  }

  public function buildForm(array $form, FormStateInterface $form_state) {
    $options = $this->_getOptions();
    $form['select'] = [
      '#type' => 'select',
      '#title' => 'Select',
      '#options' => $options,
      '#ajax' => [
        'callback' => [$this, 'ajaxCallback'],
      ],
      '#empty_option' => 'Please select',
      '#required' => TRUE,
    ];
    $form['submit'] = [
      '#type' => 'submit',
      '#value' => 'Save',
    ];
    $form_state->set('ajaxoptions', $options);
    return $form;
  }

  private function _getOptions()
  {
    // Actually data from an external Controller
    // But those, too, are random
    $options = [
      mt_rand(1000, 9999),
      mt_rand(1000, 9999),
      mt_rand(1000, 9999),
    ];
    return $options;
  }

  public function submitForm(array &$form, FormStateInterface $form_state) {
    // Do nothing
  }

  public function ajaxCallback($form, $form_state)
  {
    print_r($form_state->getValue('select'));
    echo "\n";
    print_r($form['select']['#options']);
    print_r($form_state->get('ajaxoptions'));
  }

}

When the user selects an option, in the Ajax callback (or Ajax submit, if I had one) I can't know which options were originally in the select box available.
Is there any way to preserve that information?

Get the value from:

$_temp_var_ = $form_state->getUserInput('_field_name_');

Use getUserInput() instead of getValue().

And then set the value to:

$form['_field_name_'] = $_temp_var_;


Show a maintenance page while moving the site I am going to move the finished drupal site from the sub-directory to root, because the files are quite large, it takes a while to do so, I want to put a html file there to show 'site maintenance in process, be back soon'.

How can I do this while I move everything?

First put your site into the maintenance mode than ("Administer > Site configuration > Site maintenance"), and than do the following:

Create the template file for maintenance page as maintenance-page.tpl.php.

Tutorial for creating a template file for maintenance page: https://drupal.org/node/195435


Drupal: user directory shows blocked users I have a simple user directory in drupal, but when I block certain user in the admin, they still show up in the directory, although clicking on the user gets you to "access denied" page for the user profile. Do I need to add something about the user status to make this work?

Here is the code:

$result = db_query('SELECT * FROM users_roles LEFT JOIN users ON users_roles.uid = users.uid left join node on users.uid = node.uid left join content_type_bio on node.vid = content_type_bio.vid WHERE users_roles.rid = 6 and node.type = "bio" ORDER BY users.name');

while ($data = db_fetch_object($result)) {
  // we're working off user names, so replace . with space and captitalize   $string = $data->name;   $pattern = '[\.]';   $replacement = ' ';   $name = preg_replace($pattern, $replacement, $string);   $name = ucwords($name);   $data->picture = 'http://example.com/' . $data->picture;   $image = $data->picture != "http://example.com/" ? theme_image($data->picture, $alt = $name, $title = $name, $attributes = array('class' =>'left'), $getsize = FALSE) : theme_image('http://example.com/files/pictures/default.jpg', $alt = $name, $title = $name, $attributes = array('class' =>'left'), $getsize = FALSE);
  $item[] = array('text' => $name, 'path' => 'user/'. $data->uid, 'avatar' => $image, 'title' => $data->field_occupation_value); //  $item[] = l($text = $name, $path = 'contact/'. $data->uid); //  $item[] = l($text = $name, $path = 'user/'. $data->uid .'/contact');   // this is an example of the url we're constructing   //http://example.com/user/27/contact
}

From your query and the default Block User account user settings option available to the Site Administrator per User:

Simply add into your SQL query WHERE clause the following:

and users.status <> 0

and this will change your user list to NOT include blocked users.


Contextual link for individual node? When I hover over a block on the front end, I get the Contextual Links popup to edit the block.  Can I also set this so when someone with permissions to do so hovers over a node, they get a link popup to edit that story?

To avoid hacking core, this code put in a custom module accomplishes the exact same thing as the solution by Psykoral/Clive:

//Implements hook_node_view_alter()
function mymodule_node_view_alter(&$build) {
  if(isset($build['#node'])) {
    $node = $build['#node'];
    if(!empty($node->nid)) {
      $build['#contextual_links']['node'] = array('node', array($node->nid));
    }
  }
}


How to hide empty fieldset, but leave prefix and suffix in place? Simple as this - I have a Form API fieldset with dynamically changing content. When it's empty, I don't want to show it at all. I use #prefix and #suffix to generate div my AJAX works with.

When I use:

$fieldset['#access'] = FALSE;

it disappears with it's div and no future AJAX call can make it reappear. So, how to hide it with empty, but leave wrapper intact?

The easiest way would be to wrap the fieldset itself in another element.

$fieldset_wrapper = array(
  '#prefix' => '
',
  '#suffix' => '
',
);

$fieldset_wrapper['fieldset'] = array(
  '#type' => 'fieldset',
  '#access' => FALSE,
);

As you might expect, setting #access to false will prevent an element from being rendered at all.


states multiple triggers I have looked at previous posts but can't seem to get the following to work. It just displays the form line all the time, I can get it to work when checking for just a single option.

$form['type'] = array(
  '#type' => 'radios',
  '#options' => array(
    '10' => '10',
    '29' => '29',
    '30' => '30',
  ),
  '#title' => '',
);

$form['line'] = array(
  '#type' => 'radios',
  '#options' => array(
    '1' => '1',
    '2' => '2',
    '3' => '3',
  ),
  '#title' => '',
  '#states' => array(
    'visible' => array(
      ':input[name="type"]' => array(
        array('value' => '29'),
        array('value' => '30'),
      )
    ),
  ),
);

The problem is that this will work as OR, not as AND, so one or the other will make it pass:

'#states' => array(
  'visible' => array(
    ':input[name="type"]' => array(
      array('value' => '29'),
      array('value' => '30'),
    ),
  ),
),

This will do AND, however because you cannot have 2 array keys the same, you run into trouble:

'#states' => array(
  'visible' => array(
    ':input[name="type1"]' => array(
      array('value' => '29'),
    ),
    ':input[name="type2"]' => array(
      array('value' => '30'),
    ),
  ),
),

Since the array keys you see there are just jQuery selectors the key is to use 2 different selectors that apply to the same field. For example, something like this might work:

'#states' => array(
  'visible' => array(
    ':input[name="type"]' => array(
      array('value' => '29'),
    ),
    '.form-item :input[name="type"]' => array(
      array('value' => '30'),
    ),
  ),
),

This assumes your type field is in a .form-item div.
There would be a number of possibilities here depending on your markup.

However, making something show when 2 different radio buttons are checked at the same time is impossible because you can only check one at a time.

If you were using checkboxes you could make it so that line only showed if type was 29 AND 30 by doing this:

$form['type'] = array(
  '#type' => 'checkboxes',
  '#options' => array(
    '10' => '10',
    '29' => '29',
    '30' => '30',
  ),
  '#title' => '',
);

$form['line'] = array(
  '#type' => 'radios',
  '#options' => array(
    '1' => '1',
    '2' => '2',
    '3' => '3',
  ),
  '#title' => '',
  '#states' => array(
    'visible' => array(
      ':input[name="type[29]"]' => array(
        array('checked' => TRUE),
      ),
      ':input[name="type[30]"]' => array(
        array('checked' => TRUE),
      ),
    ),
  ),
);


Migrating disqus comments from non drupal site to drupal 7 site I have installed an set up Disqus (add shortname and public key). How can i show/migrate my old comments to my new drupal site.

Disqus offers variety of migration tools depending on your needs - https://help.disqus.com/customer/en/portal/articles/286778-migration-tools. I performed migration of comment threads from static website to Drupal 7 recently. Main change to the pages with comments was new clean URLs, so in my case all I needed to do is to use URL mapper tool. It is very straight forward and comment threads were migrated in minutes.


Dynamic webforms workflow I know how to setup a multi-page webforms (basically add page breaks' between each page).  I also know how to use the conditionals to skip certain questions based on the values or state of previous questions.

However, I would like to do this dynamically.  So instead of using conditionals to change the workflow, I would like to use my own logic (code) to decide what the next question should be.  The reason is I have a webforms with 42 questions (pages) and the actual workflow can change significantly.

All I am really asking is how do I tell webforms what the next question is that should be shown.

I guess it is similar to this question (How to jump to a specific page in a multipage Webform) but the solution quoted (Webform steps Module) does not solve my problem.

Solved.

I added hook_form_alter and checked if I am working with webforms (I suppose you can check if you are working with a specific webform), and then added a custom validation call-back:

  if (strstr($form_id, 'webform_client_form') !== FALSE) {
    if (empty ($form['#validate']['_set_next_page'])) {
      $form['#validate'][] = '_set_next_page';
    }
  }

In the _set_next_page function I get the value of the submitted component.  In my case there is only one question per page, but you can easily adapt that

$submitted = array_keys($form_state['values']['submitted']);

Remember if this is the first page (question), the array looks slightly different, so:

  if ($form_state['webform']['page_num'] == 1) {
    $Q = $submitted[0];
  }
  else {
    $Q = $submitted[1];
  }
  // Get the value that was submitted
  $value = $form_state['values']['submitted'][$Q];

Assuming $destination holds the 'form_key' of the question you want to jump too:

   if ($destination) {
    foreach ($node->webform['components'] as $component) {
      if ($component['form_key'] == $destination) {
        $nextPage = $component['page_num'] - 1;
        if (($nextPage > 1)
          && ($nextPage < $form_state['webform']['page_count']))
        {
          $form_state['webform']['page_num'] = $nextPage;
          break;
        }
      }
    }
  }

I set the page_num to the page_number for the destination component to one less, because webforms will increment this value once the submission is processed.

I am sure the code needs some re-finement (make sure that I do not crash and burn while accessing array elements / objects that does not exist) - but you get the idea.

Hope this helps someone else.


Views: Show current user-entered filter I have a view with an exposed form for searching titles/bodies of content. Is there a way I can display "Showing results for: $keywords" with the values that the user enters?

You can use the PHP text filter in core. It is quick and dirty.

Add a Header of global text area to the view. Then add this PHP code using the PHP code text format:

<?php
$query_params = drupal_get_query_parameters();
if (isset($query_params['title'])) {
  print t("Results for @query", array('@query' => $query_params['title']));
}
?>

Exposed filter and sort queries in views are passed as query parameters in the form of:

?title=test

In the above code I am just looking at the parameter 'title', but you can adapt that code snippet to suit your needs. Just look at your url to see what query parameters are passed along.


Hyphens or underscores when referencing a path alias in Drupal 7 templates? I have a hyphenated path alias in my site and I need to reference it in a template hook, but it seems hyphens get converted to underscores in templates, so I'm wondering how I would go about outputting the code correctly.

My function is something along the lines of if my path alias is "change-directory" then use the "page__change-directory" template. So my question is, would it be "change-directory" or "change_directory" in my template?

When a hyphen is used in a template filename, or template suggestion, the hyphen is replaced with an underscore. That is done in theme_get_suggestions(), and drupal_find_theme_templates() which use, respectively, the following code.

// Remove slashes or null per SA-CORE-2009-003 and change - (hyphen) to _
// (underscore).
//
// When we discover templates in @see drupal_find_theme_templates,
// hyphens (-) are converted to underscores (_) before the theme hook
// is registered. We do this because the hyphens used for delimiters
// in hook suggestions cannot be used in the function names of the
// associated preprocess functions. Any page templates designed to be used
// on paths that contain a hyphen are also registered with these hyphens
// converted to underscores so here we must convert any hyphens in path
// arguments to underscores here before fetching theme hook suggestions
// to ensure the templates are appropriately recognized.
$arg = str_replace(array("/", "\\", "\0", '-'), array('', '', '', '_'), $arg);

// Transform - in filenames to _ to match function naming scheme
// for the purposes of searching.
$hook = strtr($template, '-', '_');
if (isset($cache[$hook])) {
  $implementations[$hook] = array(
    'template' => $template,
    'path' => dirname($file->uri),
  );
}

Whenever you are adding a theme template suggestion, or you are looking for a template file to use, you should replace hyphens with underscores, in the same way Drupal does.


Anonymous users cannot see listed Commerce products in a View with a relationship to product Commerce products when listed in a View with a relatioinship to Commerce Products cannot be seen by anonymous users. I am using the Views Reference module in the product display and the View is not showing up when logged out. I cannot seem to find any permissions relating to this setup.

By default commerce products do not give anonymous permissions to be viewable. This is the reason when a View contains Commerce product relationships it will show nothing when your logged out. You will have to give users the permission setting:

--- View any product of any type ---


Problem getting rid of theme error Fatal error: Unsupported operand types in `includes/theme.inc on line 980`

In my homepage im getting that error. I have no idea why I keep getting that error.

I'm on the process of upgrading my Drupal 6 to Drupal 7.

Thanks

It's hard to impossible to know where this error come from without adding some debug statements before the line 980.

Try enabling devel.module and adding following code on line 977:

dpm(func_get_args());
dpm($info);

This will reveal which theme hook is being called and its parameters (variables). It should give enough clues to help you find where the error comes from.


Create a View Block that shows a taxonomy vocabulary applied to the current node I have a news section of a Drupal 8 website that contains an ever-growing list of nodes. To avoid a messy menu in the long term, they do not have a menu position assigned but instead are shown via Views, which render News nodes tagged with certain taxonomy terms.
Because they aren't part of the main navigation, the regular Menu Block doesn't work here. Instead, I'm trying to replicate this part of the nav using the taxonomy term structure and exposing that in a View block. The terms IA matches the page IA, down to the News node level.
How can I expose the taxonomy term used on the Node, plus it's siblings and parent:
- newsroom
  - media release
    - 2019
    - 2020
    - 2021
  - records
  - blog entries

So a News node tagged with records should show this in the View block:
- newsroom
  - media release
  - records
  - blog entries

And a News node tagged with 2020 would show:
- media release
  - 2019
  - 2020
  - 2021

There are plenty of questions about exposing related Nodes to a certain term, but not related Terms on a Node...any help?

It is a common request to show reverse connection information through Views. It can be done with the help of reverse Relationships when starting from Taxonomy term type Views. You can find other answers with simple examples where you can learn about how it works. You are looking to list sibling terms, but commonly siblings are usually called nodes that share the same terms, so be mindful of the difference when reading those answers.
Your case is a bit more complicated because it involves more than one level of connections, and you want both cases to be solved with one Views. I don't know if it can be solved, I suspect it can with the Views Contextual Filters OR module but it still wouldn't be a trivial solution. It's out of scope of an answer here, so I'll just post as much as I can so you can take it to learn and expand on your own time.
This solution will list all three levels of Taxonomy tree for the node that has been tagged with the second level term, and will list third level siblings, (not second level as you'd requested). This requires a lot of tweaking to get it to work the way you want. first independently find the two solutions for each hierarchy level, then combine them with the Contextual OR option.

Create Views of the type Taxonomy term and Block Display, Filter it to your Vocabulary, and you should have the Taxonomy Name Field there. Set the Pager to Display all items. So far it will list all the terms.

Add a new Relationship from the Taxonomy term Category for the term Parent. It will be called Taxonomy term but you will see its Description explains it's the parent (search for "parent" when on the Relationships list to find it quickly). You can Require it since all your terms will have a parent (no nodes with only the grandparent)

Add another Parent Relationship the same way, only make it use the previous Parent Relationship. This second one will introduce the Grandparent term information. Don't require it because some terms will be from the second level and won't have a grandparent so requiring it would exclude them (records)

Add the third Relationship but this time the one for your Taxonomy reference field. It will be called something like Content using field_myTaxonomyField. Make it use the first Parent Relationship, you can Require it since all the relevant nodes will have that Taxonomy field filled in.

Add the Field Term Parents and set it to Exclude from display. This will show the Parent term for each term but we're hiding it because we'll use it later for grouping. This can probably be done with the term Name Field that has the Parent Reationship applied.

Add another Term Parents Field but this time make it use the Parent Relationship (the first one). This will show the grandparent term if it applies. Exclude from display because we'll use it for grouping later so don't need it repeated here.

Under Format select HTML list and set the first grouping to use the Grandparent Field (Parent Field with Parent Relationship), and the second grouping to Parents field (Parent Field without Relationship). You will now see the grandchild terms grouped under their parents and grandparents.

Lastly add the Contextual Filter ID from the Content Category, this will pass on the node ID to views to filter out only the terms referenced from this node. Configure the Contextual ID Filter:
When the filter value is NOT available
Provide default value
Content ID from URL
When the filter value IS in the URL or a default is provided
Specify validation criteria
Validator: Content
Content type News
Set the option for the case when the argument doesn't validate to something that makes sense to you.
With the Contextual Filter present you will see no results unless you enter a node ID into the Preview field. Enter the number of a known node to test it's showing the correct terms and their hierarchy.

Lastly save the Views and place the Block into a Region in your theme, and configure the Block Contextual option along with Visibility and other Block settings. Visit a node to test it's showing the hierarchy correctly

If the output doesn't look exactly as you'd like you can play with the Style settings and Override output in the Fields to get closer to what you need. In the end you can control it completely through twig templates. You might also want to look into Views tree.


Entity Reference and Views Actually, I am looking for a solution of entity reference module, I don't know whether its possible or not. Please let me know if its possible.

Example:

Content Type : A
Content Type : B

Content type B  (a field) referencing Content Type A,

So, if I want to make a list of content of content type A, which is referencing in content type B, I can do it with views and entity relationship.

But I am looking for a solution where I want to make a list of content of Content type A, which is not referencing in content type B yet.

Is it possible, if yes then how?

This is really hard to answer with the information provided, but why not try adding a filter to your Filter Criteria in your View?  In that filter make sure that you set the Relationship Field to the correct Entity Reference Field, the set the Operator to "Is empty (null)".  That would filter Nodes which have no reference.


Programatically updating node immediately after creation causes PDOException I'm working on a Drupal 7 site where nodes represent jobs in a queue. When a node is created, a custom module with hook_node_insert launches another program using exec. This program tells Drupal that the job has finished by requesting a page on the site at site.com/jobcomplete/NODE_ID/IS_ERROR. The callback for this page then does:

$node = node_load((int)$node_id);
$node->field_completed[LANGUAGE_NONE][0]['value'] = ($error == 1) ? -1 : time();
node_save($node);

The problem with this is that sometimes the program errors out almost as soon as it's started. When this happens the callback is called before the request that created the node in the first place is completely finished, resulting in 'PDOException: SQLSTATE[HY000]: General error: 1205 Lock wait timeout exceeded' when node_save is called.

How can I get the callback to wait for the request that created the node to finish before trying to update it? sleep() doesn't seem to work.

Thanks.

Drupal provides a Lock API for this purpose - to handle when multiple processes are competing for a resource.

In your case, you need to acquire a lock and release it when finished, checking if that lock is available prior to processing from the other component.

i.e:

lock_acquire
lock_release
lock_wait

Although not directly related, you may also be interested in the Queue API for other queue based processing tasks.


Specify which Migrate entries need to be updated using prepareRow I have made a Migration that i run with Cron. My highwater field is the date changed, which is present in the XML (source) document. Then I do this in my cron function:

 $result = $migration->prepareUpdate();
 $result = $migration->processImport();

Problem is is this will update ALL nodes from the XML. I would like to only update those that have been changed, according to their modifiedAt date. If I just do:

 $result = $migration->processImport();

Then nothing at all updates. I think processImport() would work if it were just about importing new items, but I also need to update any existing items that have changed. The ones that don't need updating can be skipped, of course. Is there another method I could call here? Is there a way I need to set up some kind of prepareRow to mark items as needing updating?

The recommended way to do what you are trying to do is with drush. Is drush available to you? if so have cron execute a drush mi command. See https://drupal.org/node/1561820. Also make sure your highwater mark is set up correctly. See https://drupal.org/node/1223936.


Whats wrong with my drush script when using sql? Im running the following via drush scr

$query = db_query('select node.nid AS nid from {node} node where (type="feed_item") AND (status="0") limit 1');

i am getting this error:

  WD php: PDOException: SQLSTATE[42S22]: Column not found: 1054 Unknown
  column 'feed_item' in 'where clause': select node.nid AS nid from
  [error] {node} node where (type="feed_item") AND (status="0") limit 1;
  Array ( )  in include() (line 5 of
  /home/quickstart/websites/xc.dev/deleteme.php). [4.77 sec, 97.55 MB]
  PDOException: SQLSTATE[42S22]: Column not found: 1054 Unknown column
  'feed_item' in 'where clause': select node.nid AS
  nid from {node} node where (type="feed_item") AND (status="0") limit
  1; Array ( )  in include() (line 5 of
  /home/quickstart/websites/xc.dev/deleteme.php). Drush command
  terminated abnormally due to an unrecoverable error. [4.79 sec, 97.55
  MB]

Whats wrong?

i think the problem is in the " / ' , try it this way :

$q = db_query("
select node.nid AS nid from {node} node where (type='feed_item')
AND (status=0) limit 1");


Generate new password for users periodically and notify user of new password I am running a private Drupal 7 site where all user accounts are created by admins and managers. I need to ensure that all users have access to the email account that their accounts were created with.

What is the best way to do the following:

Create a user account with an automatically generated password, and notify the new user of their password via email.
After a 4 week period, a new password must be generated for the user and set as their active password automatically. The user needs to be notified of their newly updated password via email, and the newly generated password must be used to access the site until it is reset again.

Are there any Drupal 7 modules that can help achieve this?

Any suggestions on building a custom module that can help resolve this?

This issue was talked about during the great Drupalgeddon. Because no such bulk reset tool existed for a site.

Here is a recently created tool to perform this task. Other such tools have existed since Drupalgeddon.

Mass Password Reset Module

  This module allows users with "Administer users" permission to reset
  all user accounts and notify all users

  Details

  The module will reset the passwords of all users except the
  administrative superuser id 1. You can optionally reset the
  administrative superuser id 1. Once passwords have been reset, users
  will optionally receive emails using the Drupal password recovery
  email. The password recovery email content can be edited at the
  account settings configuration page.

  Use Cases

  You have a large number of user accounts pre-created and
  want to send password recovery emails to all users during a site
  launch. You need to quickly change all passwords on a site for
  security reasons.


Can't pass variable to views style plugin template How do I pass a variable to a twig template from a preprocess function of a views style plugin in a custom module?

In alpha.module, I have tried:

function alpha_preprocess_views_view(&$variables) {
  $variables["beta"] = "1";
}

and

function alpha_preprocess_page(&$variables) {
  $variables["beta"] = "1";
}

The template file is alpha-gamma.html.twig and the plugin is Gamma.php:

/**
* Style plugin.
*
* @ViewsStyle(
*   id = "gamma",
*   title = @Translation("Gamma"),
*   help = @Translation("Displays gamma."),
*   theme = "alpha_gamma",
*   display_types = {"normal"}
* )
*/
class Gamma extends StylePluginBase {
...
}

The template file is invoked and renders its output on the view's row results. However, {{ beta }} yields no result in the same file. I know I'm missing something important, but none of the examples I've found are specific to this type of row style template.

Guidance would be appreciated!

In below code you preprocess the variables for views-view.html.twig file

function alpha_preprocess_views_view(&$variables) {
  $variables["beta"] = "1";
}

and, function alpha_preprocess_page(&$variables) will preprocess the variables for page.html.twig

So, if you create a file views-view.html.twig then you will get your variable {{ beta }}


Drupal Commerce: Display Different Shipping Rate depening on taxonomy Term I would like to offer a different flat shipping to users depending on what taxonomy terms the product they have in their cart.  For example

If a product tagged with "postage rate 1"  I would like to display shipping rate 1. If they have a product tagged with shipping rate 2 I would like to display shipping rate 2.
I would also like to if possible make it so that if the cart has items with each of the tags then one item shipping rate would win through (the most expensive one to cover costs I would think)

I have had a go with rules but I cannot figure out how to get the different shipping rates to display on taxonomy terms.  I do have the commerce rules extra module installed if that will peform part of the solution

Thank you for looking

I needed the exact thing for my webshop. Couldn't find it anywhere so a friend of mine made this module which works great!
https://drupal.org/project/commerce_taxonomy_conditions

On my site every product has either the taxonomy term 'letter' or 'package'
And then with that module you can add an extra condition to your shippingmethods to only use the products which that specific term.

If you are still in need for it then try it out :)


Creating a basic trigger After installing Drupal 7, I created 2 files (beep.module and beep.info).

/**
 * @file
 * Provide a simulated beep.
 */
function beep_beep() {
  watchdog('beep', 'Beep!');
}

/*
 * Implementation of hook_action_info().
 */
function beep_action_info () {
  return array(
    'beep_beep_action' => array(
      'type' => 'system',
      'label' => t('Beep annoyingly'),
      'configurable' => FALSE,
      'triggers' => array('node_view', 'node_insert', 'node_update', 'node_delete'),
    ),
    'beep_multiple_beep_action' => array(
      'type' => 'system',
      'label' => t('Beep multiple times'),
      'configurable' => TRUE,
      'triggers' => array('node_view', 'node_insert', 'node_update', 'node_delete'),
    ),
  );
}

/**
 * Simulate a beep. A Drupal action.
 */
function beep_beep_action() {
  beep_beep();
}

name = Beep
description = Simulates a system beep.
package = Pro Drupal Development
core = 7.x
files[] = beep.module

In http://localhost/drupal/?q=admin/structure/trigger/node I see "Beep annoyingly," but not
"Beep multiple times."

Can anyone point out what I can doto see both?

I see youhave a callback function beep_beep_action() but no beep_multiple_beep_action() have you forgotten it ?


Override default table template In custom module How can I use a custom module to override views-view-table.tpl.php? I understand how to do it for a theme, but I want to provide the template using a custom module. I've already created my replacement table theme file. I've put it in a folder called "templates" inside my custom module. Now I just need to understand what hook(s) I should use to tell views to check my module for replacement templates.

Add a module path to the Drupal 7 theme registry by implementing hook_theme_registry_alter().

Here's an example - replace the usual with your own data :)

/**
 * Implements hook_theme_registry_alter().
 */

function MYMODULE_theme_registry_alter(&$theme_registry) {

  // Get module path
  $path = drupal_get_path('module', MYMODULE);

  // Find all .tpl.php files in this module's folder recursively.
  $template_files = drupal_find_theme_templates($theme_registry, '.tpl.php', $path);

  // Itterate through all found template file objects.
  foreach ($template_files as $key => $template_file) {
    // If the template has not already been overridden by a theme.
    if (!preg_match('#/themes/#', $theme_registry[$key]['theme path'])) {
      // Alter the theme path and template elements.
      $theme_registry[$key]['theme path'] = $path;
      $theme_registry[$key] = array_merge($theme_registry[$key], $template_file);
    }
  }
}


How to prevent term URL in webform email template (Webform References Module)? I've configured a webform to send a custom email after submit. One of the fields in the webform is a taxonomy select (via the Webform References module). So the value in the email template looks something like this:

[submission:values:vocabname]

When the email gets sent, the selected taxonomy term gets printed out along with a reference to its URL listed at the bottom... like this:

Term Name [1]

And then at the bottom of the email is the URL:

[1] http://www.example.com/vocab-name/term-name

How do I prevent the URL from being included automatically in the email? I just want term name alone.

When returning field value Webform References Module, add link to field output using theme function (theme_webform_display_term_reference_field()), which you can override in your theme's template.php and then clear Site Cache. Check sample code below, which you can write in your theme's template.php:

/**
 * Format the output of data for this component.
 */
function [THEME_NAME]_webform_display_term_reference_field($variables) {
  $values = (array) $variables['element']['#value'];
  $items = array();
  foreach (array_filter($values) as $value) {
    $tid = check_plain($value);
    if ($tid) {
      // Do not pass 2nd argument, keep it default i.e. FALSE.
      $items[] = _webform_references_get_term_name($tid);
    }
  }
  $output = count($items) > 1 ? theme('item_list', array('items' => $items)) : (isset($items[0]) ? $items[0] : '');
  return $output;
}

NOTE : This will also remove the Term field link on view submission page.


Filter on boolean with NULL (unset) value Client wants to hide some published content from specific Views displays.

Unpublishing the content is not an option: it needs to remain accessible.

I added a boolean exclude_from_view field to several content types.

I planned to add a boolean filter to exclude content from the necessary displays if this field's value was TRUE, but I was surprised to find that when I did so, Views returned no results at all. Setting the boolean filter to NOT FALSE had the same result.

This is happening because the field has been added to the existing content without a default value, so the field returns NULL, which is neither TRUE nor FALSE. (In PHP, NULL is a "falsy" value, but apparently not to Views.)

A little research reveals that a lot of other people have complained about this problem.

Some of them think that boolean fields not set on entities should be considered FALSE, not NULL.

Others wish that NULL fields could be treated as TRUE.

Still others think that Views UI should offer filtering options for "Treat NULL as FALSE" or "Treat NULL as TRUE." (This is a cool idea but it requires patching core, which I'm not necessarily opposed to if it is the best way forward.)

What should I do?

UPDATE 2019-11-13:

Kudos to @no-sssweat for coming up with a viable workaround, which I upvoted below.

I'm still hoping for a better answer because I'm not satisfied with the user experience of the "checkboxes/radio buttons" field widget.

If I just use one value, it shows up as two radio buttons, for N/A and Yes. Adding a No option doesn't make it much better:

I think the client would really prefer a boolean checkbox, so I'm holding out for an answer that will give me that.

Just for posterity, here's the approach I ended up using:

The Field Defaults contrib module allowed me to set all null values for the new field in pre-existing content, so I was able to use the boolean checkbox I wanted.

There's no need to patch core to deal with this, because it won't happen again with newly-created content. As soon as the node is saved, the field has a sensible default value.


Create this type of view in drupal7 I am using latest drupal 7 and views. I have created a vocabulary and i have created terms under it. Each term has 2 levels sub terms under it.  Using views i wanted to create a drop down of all the base level terms and when select the base level terms from drop down all the sub level terms must be listed .. is this possible in views??

I'm waiting for this one, too. Conditional Fields module.
But it's not yet available in D7.


Restoring views to their default state Views module comes with a few default views. I have enabled and modified the frontpage view, but I'd like to go back to its default state that originally came with the module on a fresh install (without my changes). Is this possible?

Thanks

Yes you can do that.

Go to the views listing page (admin/structure/views).
In the Operations column of the view you want to reset, click the Revert operation.
Confirm by clicking the Revert button.


printing an entity reference field in a special display mode I have an entity reference field. The referenced entity has multiple display modes.

I'd like to print this field 2 two times in a template, with 2 different display modes like so:

{{ content.field_ref_entity.display_mode_xy }}

and

{{ content.field_ref_entity.display_mode_yz }}

Is it possible to define the display mode of the referenced entity in field printing? If yes, how?

See my explanation in How can you render fields from an entity reference in node templates? [Drupal 8], which touches that topic as well.

In short, not with content, that can only contain a field once, at least without additional modules (not sure if display suite or so can do this). But you can call the view() mode on the field with either the of a view mode from where to pick the configuration or pass it the desired configuration directly. The structure is the same as what stored for the configuration in the entity view display config entities for a field.

Not sure about the exact twig syntax for the array, the view display would be like this: `{{ node.field_ref_entity.view('teaser') }}. You could also prepare it in preprocess and then just print a variable if building that configuration array is too tedious in twig.


How to debug custom node type I am following this guide to build a custom node type in Drupal 7:

http://www.sitepoint.com/creating-a-new-drupal-node-type/

Unfortunately, my code is not working and drupal is not outputting any error either. The module is there, is enabled, but the new custom type is not showing up. I have double checked the code several times and I'm sure I wrote it right, the same way of the guide.

How can I debug this kind of issue? I have installed the debug module, I am looking at the documentation here:

http://ratatosk.net/drupal/tutorials/debugging-drupal.html

but I'm a bit lost on where exactly should I up the debugging code to find the issue. I was hoping drupal has some kind of error log (like wordpress does) where I can see anything that goes wrong.

EDIT: I made the custom type work, now I can make a new custom type, but the code about the custom fields is ignored, like it's not there. Here the source of productcustomtype.install:

<?php
/**
 * Implements hook_install().
 */
function productcustomtype_install() {
    node_types_rebuild();
    $types = node_type_get_types();
    node_add_body_field($types['product']);
    productcustomtype_add_custom_fields();
}
/**
 * Implements hook_uninstall().
 */
function productcustomtype_uninstall() {
    $ournewtype = 'product';
    $sql = 'SELECT nid FROM {node} n WHERE n.type = :type';
    $result = db_query($sql, array(':type' => $ournewtype));
    $nodeids = array();
    foreach ($result as $row) {
        $nodeids[] = $row->nid;
    }
    node_delete_multiple($nodeids);
    productcustomtype_delete_custom_fields();
    node_type_delete($ournewtype);
    field_purge_batch(500);
}

function productcustomtype_delete_custom_fields() {
    foreach (array_keys(_productcustomtype_installed_fields()) as $field) {
        field_delete_field($field);
    }
    $instances = field_info_instances('node', 'product');
    foreach ($instances as $instance_name => $fieldinstance) {
        field_delete_instance($fieldinstance);
    }
}

function _productcustomtype_installed_fields() {
    $t = get_t();
    return array(
        'productcustomtype_price' => array(
            'field_name' => 'productcustomtype_price',
            'label' => $t('Price of the product'),
            'type' => 'text'
        ),
        'productcustomtype_quantity' => array(
            'field_name' => 'productcustomtype_quantity',
            'label' => $t('Quantity of the product'),
            'type' => 'text'
        )
    );
}

function _productcustomtype_installed_instances() {
    $t = get_t();
    return array(
        'productcustomtype_price' => array(
            'field_name' => 'productcustomtype_price',
            'type' => 'text',
            'label' => $t('Price of the product'),
            'widget' => array(
                'type' => 'text_textfield'
            ),
            'display' => array(
                'example_node_list' => array(
                    'label' => $t('Price of the product'),
                    'type' => 'text'
                )
            )
        ),
        'productcustomtype_quantity' => array(
            'field_name' => 'productcustomtype_quantity',
            'type' => 'text',
            'label' => $t('Quantity of the product'),
            'widget' => array(
                'type' => 'text_textfield'
            ),
            'display' => array(
                'example_node_list' => array(
                    'label' => $t('Quantity of the product'),
                    'type' => 'text'
                )
            )
        )
    );
}
function productcustomtype_add_custom_fields() {
    foreach (_productcustomtype_installed_fields() as $field) {
        field_create_field($field);
    }
    foreach (_productcustomtype_installed_instances() as $fieldinstance) {
        $fieldinstance['entity_type'] = 'node';
        $fieldinstance['bundle'] = 'product';
        print_r($fieldinstance);
        field_create_instance($fieldinstance);
    }
}

To make sure the changes apply and work, it is needed to disable the module and unistall it. This important step was missing on the guide.


How can I install Drush without Composer? I've been trying to install Drush for a while but have failed. I have no experience in command line applications.

I've seen quite a few tutorials:

https://www.drupal.org/node/594744
https://www.drupal.org/node/2405811
https://drupalize.me/videos/wonderful-world-composer
https://getcomposer.org/doc/00-intro.md#installation-windows

but each one says that Composer is required. The catch, I can't seem to get Composer to work either.

Would I ever be able to install Drush, but still work around installing Composer?

Specifications:

Windows 10
Drupal 8.1.8
Cpanel 56.0.33
Php 5.59 (or higher according to this)
Composer Manager 8x-10-rc

This is the simplest solution I have found.

If you don't want to use composer, follow the instructions here...

https://sharpi.sh/blog/web-development/install-drush-on-ubuntu-quickly-without-composer/

Download a Drush release from Github to user folder

wget https://github.com/drush-ops/drush/releases/download/8.1.17/drush.phar

Rename drush.phar to drush

mv drush.phar drush

Find the bin directory

echo $PATH

which shows something like.... /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games

I’ll go with /usr/local/bin

Move drush to the bin

mv drush /usr/local/bin/drush

Change permissions to

chmod +x /usr/local/bin/drush

Test with

drush version


How to update a feature I have a feature which contains fields for the user profile page. This is currently working in PROD.

In the dev site, I've updated the feature to include a new field, updated the version, and download a new TAR file.

In PROD, when I go to Update Module, and try to update the feature, an error message appears saying the feature is already installed.

Am I missing something here? Are features only expected to be installed once? Or do I need to manually remove the feature before updating?

Would it be better practice to create a brand new feature containing the one field?

when it's structure only, you will have to upload your dev feature, replace it with the production one and revert the production feature.


Taxonomy layout on node creation I have a content type with 5 taxonomies, each with 50 terms (checkbox). All of them are available for user to choose when creating node.

It looks really long and not quite user friendly.

So i am looking a module that can make this look nice. Table, inline, anything but default would look better.

For these situations I prefer to use the Chosen jQuery plugin, which makes  elements way more user-friendly. For easy intergration of this plugin with Drupal, see the Chosen module.


How to set a session variable when a link is clicked? I have created a search block. It outputs multiple results (names) as links.
User can follow the link. How can I pass the user name into $_SESSION variable?
I tried doing this, the result shows a page not found error.
'name' => l(t($n['name']), 'edit_details' ,array('query' => array('uid' => $n['uid'])))

In hook_menu() I set $items['edit_details/%'] to array(). I passed the value into the session with $_SESSION['id'] = $_GET['uid'];.

You can do like this.

Link URL :

 'name' => l(t($n['name']),'edit_details/@uid', array('@uid' => $n['uid']))

In hook_menu() :

$items['edit_details/%user'] = array(
    'title'          => 'Lets start',
    'page callback'   => '_get_user',
    'page arguments'  => array(1),
    'access callback' => TRUE,
    'type'            => MENU_CALLBACK,
  );

In callback :
In callback function you will get complete user object, as this wild card used for user core module.

function _get_user($user) {
  $_SESSION['user_name'] = $user->name;
  //Redirect to any other page you want.
}

Thanks!


How do I resolve a unresolved dependency error after using Composer to install modules? I'm going to pull my hair out if I stare at this problem any longer. I've seen the similar questions and tried everything but I can't fix this issue with module dependency versions.

I'm using Composer require drupal/<module_name> and I've tried including specific versions too but that hasn't worked. I see that the current version number isn't being displayed at the end of the error message which makes me wonder whether the system knows what version is even installed?

I also don't understand how so many modules can be asking for different versions of the same dependency. How can you possibly resolve that :|

I should also add that I was in the process of converting manually installed modules into Composer controlled dependencies. I'm not sure if that would make a difference.

It really seems to me that Drupal doesn't know what versions of Modifiers and Paragraphs are installed but I don't see how.

So, the system couldn't decide what version of the modules were installed. Here is a fix:

https://www.drupal.org/project/modifiers/issues/3052416

Basically, install Git Deploy module to add versioning details to modules .info files.


Instantiate Controller with Interface not concrete class As background, I am rebuilding some old code and want to wrap all the curl based requests in an interface (HttpRequestInterface) so I can swap that out later without having to write all the api calls right now.

I am trying to pass the HttpRequestInterface into controller, but it keeps saying `

  TypeError: Argument 1 passed to
  Drupal\my_api\Controller\MyController::__construct() must be
  an instance of Drupal\my_api\Controller\HttpRequestInterface,
  instance of Drupal\my_api\Services\HttpRequest\CurlRequest given

I am new to Drupal from the .Net world and love how this functionality is out of the box and it seems like I am following the examples and code I find in core, but obviously I am missing something.

***One thing that sticks out is that this error message has the wrong namespace for HttpRequestInterface.

Below are the relevant files, I have only included what I think is pertinent to the issue, more can be made available.

Controller:

<?php

namespace Drupal\my_api\Controller;

use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\Response;
use Drupal\my_api\Controller\BaseApiController;

/**
 * Controller routines for Api routes.
 */
class RallyBoundController extends BaseApiController {

`BaseController:

namespace Drupal\my_api\Controller;

use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\Controller\ControllerBase;
use Drupal\my_api\Services\HttpRequest\HttpRequestInterace;

/**
 * BaseApiController abstracts away common api concerns.
 */
abstract class BaseApiController extends ControllerBase {
  protected $httpService;

  /**
   * Contructor requires HttpRequest Service.
   *
   * @param HttpRequestInterface $httpService
   *   Implementation of HttpRequestInterface defined in services.yml.
   */
  public function __construct(HttpRequestInterface $httpService) {
    $this->httpService = $httpService;
  }

  /**
   * Get the HttpRequest implemention as interface so we can swap out as needed.
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('my_api.httprequest')
    );
  }

Service.yml:

services:
  my_api.httprequest:
    class: Drupal\my_api\Services\HttpRequest\CurlRequest

HttpRequestInterface:

namespace Drupal\my_api\Services\HttpRequest;

/**
 * HttpRequestInterace defines interface for making Http GET Requests.
 */
interface HttpRequestInterface {

CurlRequest:

namespace Drupal\my_api\Services\HttpRequest;

use Drupal\my_api\Services\HttpRequest\HttpRequestInterface;

/**
 * HttpRequest Implementation of HttpRequestInterface using CURL.
 */
class CurlRequest implements HttpRequestInterface {

Thanks for the help.

In the BaseController file, you have a typo in the interface classname. Fix that and clear the cache. Your module namespace seems to be inconsistent too. Your custom classes should be namespaces under the same module name they are defined in.

use Drupal\my_api\Services\HttpRequest\HttpRequestInterace;

to

use Drupal\my_api\Services\HttpRequest\HttpRequestInterface;

PHP can’t figure out where the class is due to the typo, and expects it to be defined locally in the Controller class file, hence why your error message lists an incorrect namespace to the interface.


Custom field type: make only one specific property translateable Is it possible to mark only a single property of a field as translateable?

E.g. I have a custom field type RoomRates with 2 properties uri and price_mode.

/**
 * Plugin implementation of the 'kognitiv_room_rate' field type.
 *
 * @FieldType(
 *   id = "kognitiv_room_rate",
 *   label = @Translation("Kognitiv room rate"),
 *   description = @Translation("Stores an URL to retrieve price and availability data for a room"),
 *   default_widget = "kognitiv_room_rate",
 *   default_formatter = "kognitiv_room_rate",
 *   cardinality = 1,
 *   column_groups = {
 *     "uri" = {
 *       "label" = @Translation("URI"),
 *       "translatable" = TRUE
 *     },
 *     "price_mode" = {
 *       "label" = @Translation("Show prices as")
 *     }
 *   }
 * )
 */
class RoomRate extends FieldItemBase implements LinkItemInterface {

  const PRICE_MODE_PERSON = 'PERSON';
  const PRICE_MODE_DAY = 'DAY';

  public static function propertyDefinitions(FieldStorageDefinitionInterface $field_definition) {
    $properties['uri'] = DataDefinition::create('uri')
      ->setLabel(t('URI'))
      ->setRequired(TRUE);

    $properties['price_mode'] = DataDefinition::create('string')
      ->setLabel(t('Show prices as'))
      ->setRequired(TRUE);

    return $properties;
  }

  /**
   * {@inheritdoc}
   */
  public static function schema(FieldStorageDefinitionInterface $field_definition) {
    return [
      'columns' => [
        'uri' => [
          'description' => 'The URI of the JSON API endpoint.',
          'type' => 'varchar',
          'length' => 2048,
        ],
        'price_mode' => [
          'description' => 'Show prices as price per day or price per person in std occupancy',
          'type' => 'varchar',
          'length' => 10,
        ],
      ],
      'indexes' => [],
      'foreign keys' => [],
    ];
  }

The uri property should be translateable (if the site builder enables translation for this field), while the price_mode property should never be translateable/always be the same accross all languages (no matter if the site builder enabled field translation or not).

content_translation has a feature that synchronizes certain property between translations, see how the \Drupal\image\Plugin\Field\FieldType\ImageItem field type uses that:

 *   column_groups = {
 *     "file" = {
 *       "label" = @Translation("File"),
 *       "columns" = {
 *         "target_id", "width", "height"
 *       },
 *       "require_all_groups_for_translation" = TRUE
 *     },
 *     "alt" = {
 *       "label" = @Translation("Alt"),
 *       "translatable" = TRUE
 *     },
 *     "title" = {
 *       "label" = @Translation("Title"),
 *       "translatable" = TRUE
 *     },
 *   },

By not setting translatable = TRUE, the UI by default suggests to keep that value across translations, although it can be configured differently.


Inline fields on node edit form I managed to get fields inline on node display, but cant find a module to help me do it on node input. I am mostly using DS, field collection and field group (field gruop has this option but only for display, not for edit.)

Display processors are not used when rendering the node form. It's a completely different process. I'm not aware of any contrib modules that will help you accomplish this. However you can write your own.

You need to start by creating a very simple custom module with just a .info, a .module and a .css file. You can find lots of tutorials online.

Then you want to write that CSS to make your particular form fields inline and attach the css to the form using hook_form_alter. If you named your module "hook" the code would look like this (This code goes in your hook.module file):

// Replace hook with name of module and yourcontenttype
// with machine name of your content type
hook_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'yourcontenttype_node_form') {
    $form['#attached']['css'][] = drupal_get_path('module', 'hook') . '/hook.css';
  }
}

After that enable the module, clear all caches and it should be including the new CSS in the admin form.


How can I remove some content types of the admin menu? I have drupal 6.x and I have installed the module "Admin menu".  I want to know how can I remove some content types of the menu?  I have looked that this menu loads all options of the website and  I only require to remove the some content types of the menu.

Thanks for your help.

While you can add/remove items from the admin menu from this menu
/admin/build/menu-customize/admin
you really shouldn't, that would be customizing what that module does and anytime they release a new version you would have to make your customization again.

The purpose of that module to to simplify, or make shortcuts to, all of the aspects of administering a Drupal site. If there are certain portions of the admin you don't want users to see, use roles to control which of the links are viewable.

Hope this helps!


How do I enable a module by exporting the configuration? I enabled these core modules: Language, Content translation, Config translation, and Interface translation. I exported the core.extensions.yml file, but when I placed the same file in the development environment, those modules weren't installed.

How can I install modules by exporting the configuration?

You need to import the configuration from the file, into the database. Configuration files are only a backup to configuration. The active configuration is in the database.

You can import configuration at /admin/config/development/configuration or run drush cim.


Add element to the beginning of form, via hook_form_alter() Using Drupal 7, I'm trying to utilize Drupal Form API in combination with hook_form_alter to place my added inputs at the beginning of the form.

I thought the best way to do this was to create a new form element like so:

$form['program_list'] = array(
    '#type' => 'select',
    '#title' => t('Select a preferred Program'),
    '#options' => $program_list,
    '#weight' => -1,
);

I read the documentation, and it looks like there is a #weight attribute. I tried setting the weight to either 0 and negative integers, but my added inputs are still at the bottom.

I then used var_dump() to check the weights of my Webform-generated inputs. They were as I expected: a 0-based, incremental weight index.

I also tried placing the elements in $newform then  using $form = $newform + $form, but that as well placed my new inputs at the bottom of the form.

What am I doing wrong?

I was facing the same problem but found the answer thanks to this post: http://drupal.org/node/235354

Problem was that the field I was adding to my web form was not in a group when all the already existing fields were part of the group 'submitted' maybe because this is a webform. So setting the weight to -1000 didn't change anything.

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

    $form['my_new_field_name'] = array (
      '#type' => 'checkbox',
      '#title' => t ('My new field is after the others'),
      '#weight' => -1000,
    );

}

To correctly make it work I just needed to create my new field inside the group 'submitted' like that :

$form['submitted']['my_new_field_name'] = array (...


How do I replace a module with a dev version through the UI? I copy the reference to the dev release for a module and paste it into the "Install module" form, but Drupal complains that the module is already installed. Is there a good way of doing this through the UI or drush or do I just have to uninstall and reinstall?

I just found that I can run drush dl <module_name>-8.x-1.x-dev and confirm that I was to override the old module.


user.routing.yml -- What is the significance of "_entity_form: user_role.default"? In user.routing.yml, I'm not able to understand the line 83.

user.role_add:
  path: '/admin/people/roles/add'
  defaults:
    _entity_form: user_role.default
    _title: 'Add role'
  requirements:
    _permission: 'administer permissions'

What does _entity_form: user_role.default mean?

In short, it means that route shows an entity form to edit the user role entity; in particular, it shows its default form.

In details, user_role is the ID for the Role class, which implements the user role entity.

@ConfigEntityType(
  id = "user_role",
  label = @Translation("Role"),
  handlers = {
    "storage" = "Drupal\user\RoleStorage",
    "access" = "Drupal\user\RoleAccessControlHandler",
    "list_builder" = "Drupal\user\RoleListBuilder",
    "form" = {
      "default" = "Drupal\user\RoleForm",
      "delete" = "Drupal\Core\Entity\EntityDeleteForm"
    }
  },
  admin_permission = "administer permissions",
  config_prefix = "role",
  static_cache = TRUE,
  entity_keys = {
    "id" = "id",
    "weight" = "weight",
    "label" = "label"
  },
  links = {
    "delete-form" = "/admin/people/roles/manage/{user_role}/delete",
    "edit-form" = "/admin/people/roles/manage/{user_role}",
    "edit-permissions-form" = "/admin/people/permissions/{user_role}",
    "collection" = "/admin/people/roles",
  },
  config_export = {
    "id",
    "label",
    "weight",
    "is_admin",
    "permissions",
  }
)

user_role.default is referring to the default form the annotation for that class describes.

"form" = {
  "default" = "Drupal\user\RoleForm",
  "delete" = "Drupal\Core\Entity\EntityDeleteForm"
}

In this case, it's the form implemented from the RoleForm class.

When you see _entity_form in a route, it always mean the route is showing a form implemented from an entity.


use URL with query as URL destination I mean can we have something like this? url with double ? in drupal?

http://drupal.org/?destination=xxx/yyy?token=zzz

Sort of, but you'll need to URL encode the second ? otherwise the URL will be invalid.

The best thing to do is use l() or url() which will do this for you:

$query_string = array('destination' => 'xxx/yyy?token=zzz');
$url = url('<front>', array('query' => $query_string));

That will produce the string:

/?destination=xxx/yyy%3Ftoken%3Dzzz

Which is the correctly encoded version of the URL in your question.

Drupal will also respect this method when auto-redirecting based on a form submission etc. So the page you get directed to will actually look like this:

/xxx/yyy?token=zzz