Feeds importer incremental URL parameter I am trying to achieve incremental URL changing to avoid creating thousands of importers. For example if the feed URL contains the param ID=1, i need to loop until ID=1000 and import the provided JSON with the same rules. For example..

https://domain.com/api/v2/bios.json?bio_id=15&with_faces=true
https://domain.com/api/v2/bios.json?bio_id=16&with_faces=true

...and so on...

Is there ANYTHING to allow me do that? Thanks in advance.

You want to take a look at the Web Scraper Example.

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

In Feeds Importer you want to look into the Robots spider setup, which will follow links and patterns, so a single importer can create 10's, 100's or even 1000's of new Nodes.

The example scrapes the Stanford Events website - spidering the page, following the links and creating a new node for each item. You can also run the importer on single event pages.


DB error after upgrade interrupted I'm in the process of upgrading from Drupal 6 to Drupal 7 and the upgrade process terminated due to disk usage error.

I found out that ibdata1 occupies 98% of /var. So I decided to empty this file so I can have the space again and re-run the update.php, but I got bunch of SQL PDO error.

  PDOException: SQLSTATE[42000]: Syntax error or access violation: 1286 Unknown table engine 'InnoDB': SELECT name, value FROM {variable}; Array ( ) in variable_initialize() (line 943 of /var/www/vhosts/drupal/includes/bootstrap.inc).

    mysql> show engines;
    ERROR 2006 (HY000): MySQL server has gone away
    No connection. Trying to reconnect...
    Connection id:    177
    Current database: drupal_drupal

    +------------+---------+----------------------------------------------------------------+--------------+------+------------+
    | Engine     | Support | Comment                                                        | Transactions | XA   | Savepoints |
    +------------+---------+----------------------------------------------------------------+--------------+------+------------+
    | MyISAM     | DEFAULT | Default engine as of MySQL 3.23 with great performance         | NO           | NO   | NO         |
    | MRG_MYISAM | YES     | Collection of identical MyISAM tables                          | NO           | NO   | NO         |
    | BLACKHOLE  | YES     | /dev/null storage engine (anything you write to it disappears) | NO           | NO   | NO         |
    | CSV        | YES     | CSV storage engine                                             | NO           | NO   | NO         |
    | MEMORY     | YES     | Hash based, stored in memory, useful for temporary tables      | NO           | NO   | NO         |
    | FEDERATED  | NO      | Federated MySQL storage engine                                 | NULL         | NULL | NULL       |
    | ARCHIVE    | YES     | Archive storage engine                                         | NO           | NO   | NO         |
    +------------+---------+----------------------------------------------------------------+--------------+------+------------+
    7 rows in set (0.06 sec)

Do you have any idea?

This solved my problem.

chmod 775 /var/lib/mysql


Create a menu tab of different views Having 3 different view , I'm going to show them in a page as different tabs.
All of these views have exposed filter and are not completely related (one view shows users , one shows content and the last one shows taxonomy terms).
I changed the menu types in these views to menu tab and their address to "seek/VIEWNAME".

now trying to browse seek I face 404 error and browsing "seek/users" I only get the "user" view without any tabs to other views.

How can create a tab consisting menus to different views?

Please follow the link about Creating Tabbed Views.

For quick reference, I am copying important steps here from above link.

Create a view.
Name the path (url) to be what you want the default tab to be, for example, 'document/all'.
Configure your view with sorting, filtering, etc.
Choose 'Default menu tab' in Menu option and name it.
Choose 'Normal menu item' to be the parent, since this tab is linked directly from a menu, i.e. 'document'
Finish this first tab.
Create another display.
Name the path of this one as a tab option, like 'document/homework'.
Configure it.
Choose 'Menu tab' for this one.
Finish this tab.
Repeat (8) - (11) for more tabs.

Note: If you want three tabs on same page with different/same view result, then please install Quick Tabs module.

  The Quick Tabs module allows you to create blocks of tabbed content,
  specifically views, blocks, nodes* and other quicktabs*. You can
  create a block on your site containing multiple tabs with
  corresponding content.


Print taxonomy term description onto product page I am currently running Drupal Commerce 7.

The products listed are all referenced to different designers through a "Designer" Taxonomy.
Within the Taxonomy, the individual terms, i.e. the different designers have an added description. I would like to know if there is any way to print on the product page the description for the particular designer referenced by the page.

For instance I have a shoe. I have it designed by Mary under "Designer". I have also attached an example description for Mary: "Mary is a great designer". I would like to print this somehow onto the product page.

It depends a lot on how you're showing this page/information, most probably you're using Views lo list these products, so you can add a Relationship from the Product entity to the Taxonomy (from product variation or display, doesn't matter) to show the fields coming from your categories.

If it's in the product page, it might get trickier, I'd use Display Suite to show fields from other entities, Dynamic fields is an option included in DS and alows you to explore more information that is available for display contextually on your current entity view mode.


How to modify default login page using theme? Version: Drupal 8.7.x

Currently, I am using a subtheme of the Bootstrap theme and I want to override the default login page because the interface doesn't look good. I was hoping to override the template file in Bootstrap theme responsible for login but there was no file with familiar name in the theme folder. Maybe Bootstrap inherited the login file as well? Then I created a file named page--user--login.html.twig and put that in my subtheme folder but there was no change in the login page. Maybe the file name is supposed to be different or it is something else entirely.

Go to

  web/sites/default/services.yml

and change the debug value from false to true

debug: true

You will get file name suggestions like shown in the image, u should use the same names.

Also, was your sub-theme succesfully installed?
Is the sub-theme under this path ? `

  themes/custom/myproject_bootstrap_subtheme

`


How to remove  tags when printing out Menu Is there any way to remove HTML list tags when this function is called to access Main Menu?

This code is used in page.tpl.php in for a theme:

print theme(
  'links__system_main_menu',
  array(
    'links' => $main_menu,
    'attributes' => array('class' => array('topNavItem')),
  )
);

Sure, it's pretty easy. But first I think you need to know what's going on here.

Drupal's theme() call above is going to look for a theme_links__system_main_menu() function/hook and failing that, will look for a theme_links() function/hook.

theme_links() is in drupal core in includes/theme.inc if you want to take a look at it, as that's "who" is putting the ULs and LIs in there.  DONT just edit that file/function/hook, but create your own in your theme.  So, to take them out, or to put whatever you want in, you just write your own theme function to do it, and then theme() above will call it for you.

Drupal's theme layer is described well here:  http://api.drupal.org/api/drupal/includes--theme.inc/function/theme/7 and here: http://drupal.org/theme-guide/6-7 and should put you on the path to doing all that.


unique user name but duplicate password I'm having a developer work on a site for me.  I'm being told that each user must have a unique username.  That makes sense.  I'm also told that they all need to have a unique password.  This doesn't make sense and is causing problems for me client.
Shouldn't a unique combination of username and password be what's required?
Can anyone help direct me to a solution?

Users can have the same password, but they cannot have the same username by default. Theoretically, users could have the same username with some customization, but they would need to log in with something else that makes them unique such as an e-mail address.


Force redirect in submit handler even though destination parameter set I add a custom submit handler and now I want Redirect to custom route after form submitted.

This is what I used

use Drupal\Core\Form\FormStateInterface;
use Symfony\Component\HttpFoundation\Request;
use \Drupal\Core\Url;

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

    if ($form_id == 'node_trends_form' || $form_id == 'node_trends_edit_form') {

        foreach (array_keys($form['actions']) as $action) {
            if ($action != 'preview' && isset($form['actions'][$action]['#type']) && $form['actions'][$action]['#type'] === 'submit') {
                $form['actions'][$action]['#submit'][] = 'zyetondev_sync_trends_submit';
            }
        }
    }
}

function zyetondev_sync_trends_submit(array $form, FormStateInterface $form_state) {
    $url = Url::fromRoute('view.trends.page_1');
//    die(Url::fromRoute('view.trends.page_1')->toString());
    drupal_set_message("Done");
    $form_state->setRedirect($url);
}

Submit Handler getting run and redirect redirection work correctly, Problem is when we have ?destination= on Url, How can I force redirect even though ?destination= is on Url?

The only correct way to do this is to alter the Request object and drop the destination.

In your submit callback:

\Drupal::request()->query->remove('destination');

Depending on the context, you might want to store it somewhere, for example pass it along to the URL you are redirecting to, so that it is respected again later.

See https://www.drupal.org/node/2325463 for a core issue that is doing exactly this to fix the preview button if a destination is given.


How to get the entity ID in a twig template I have a custom entity, with the template my-custom-entity--my-entity.html.twig.
How do I access the ID in the template? I can do this by implementing hook_preprocess_entity, but am wondering if the ID is already available in the template.

You can just add the full object to a twig variable, so
$vars['myentity'] = $my_entity;

and then access with
{{ myentity.id }}

A bit more elegant is to implement hook_theme:
/**
 * Implements hook_theme().
 */
function MODULENAME_theme() {
  return [
    'customentity' => [
      'render element' => 'elements',
    ],
  ];
}

and a preprocess function to expose it to twigs customentity and maybe content variables:
function template_preprocess_customentity(&$variables) {
  $variables['customentity'] = $variables['elements']['#node'];

  // Helpful $content variable for templates.
  $variables += ['content' => []];
  foreach (Element::children($variables['elements']) as $key) {
    $variables['content'][$key] = $variables['elements'][$key];
  }
}


How do I edit the template files for GLOBAL PHP? I have a global php field in a view and it has a output field. However, I want to add / edit the template file instead which looks like this:

<?php

/**
 * @file
 * This template is used to print a single field in a view.
 *
 * It is not actually used in default Views, as this is registered as a theme
 * function which has better performance. For single overrides, the template is
 * perfectly okay.
 *
 * Variables available:
 * - $view: The view object
 * - $field: The field handler object that can process the input
 * - $row: The raw SQL result that can be used
 * - $output: The processed output that will normally be used.
 *
 * When fetching output from the $row, this construct should be used:
 * $data = $row->{$field->field_alias}
 *
 * The above will guarantee that you'll always get the correct data,
 * regardless of any changes in the aliasing that might happen if
 * the view is modified.
 */
?>

<?php print $output; ?>

However, when I put anything here, like for example: echo "hello world"; nothing gets displayed.

If I put this php code in the output field on the view, it works just fine, but I am tasked with removing php from fields and putting them in either modules or template files so they do not risk exposure.

How come my template file will not display whatever php code I insert, but it will on the field itself? I'm confused.

1) Remove Global PHP field from the view

2) Add a new field of type "Global: Custom text"

3) Click on Theme: Information. You will be able to see the suggestion for template file

4)Create the template file with the required name.

5)Invoke the function which was being invoked from your Global: PHP field.


Why is hook_update not fully taken into account? I have a custom content entity created with
public static function baseFieldDefinitions(EntityTypeInterface $entity_type).
I just added a field to that entity with
- adding a new $fields['courriel'] = BaseFieldDefinition::create('email')
- creating hook.install file with

function association_update_8101()
{
  \Drupal::entityDefinitionUpdateManager()->applyUpdates();
}

Running update.php has indeed added the field to the corresponding database table and I can access it with my code (for example, I store in that field a copy of user->mail.
But when I use CRUD forms for my Entity (i.e. canonical, add-form, edit-form or collection), I don't see the new field.
What did I miss?

[Edit] my hook.install is now:

function association_update_8101()
{
  $storage_definition = BaseFieldDefinition::create('email')
    ->setLabel(t('Courriel'))
    ->setDescription(t('The email address of the Personne entity.'))
    ->setDefaultValue('')
    ->setReadOnly(TRUE);
  \Drupal::entityDefinitionUpdateManager()
    ->installFieldStorageDefinition('courriel', 'association_personne', 'association_personne', $storage_definition);
}

I managed to run again update.php with success (at least with no errors): the table has now the new column (Courriel) but I still don't have my CRUD forms showing 'Courriel'.
Is there anything else I need to add to hook_update_8101 to have that done?

It seems I was looking at the wrong place.
Once hook_update_8101 executed, I should have updated myEntityListBuilder.php to be consistent.
The other forms (canonical, add-form, edit-form) were effectively updated.


How to translate 'ago' in interval time formatter in views? Googling the only thing I've managed to find is: https://www.drupal.org/node/2800563

What can I do to translate 'ago' or omit it from printing?

can't we do like this?

  //Get today's date.
  $today = getdate();
  //Calculate the date "1 week ago".
  $start_time = mktime(0, 0, 0,$today['mon'],($today['mday'] - 7), $today['year']);

Also, you can change those zeroes to make 'n' hours/ minutes/ seconds ago.


Updated taxonomy terms do not save I am using the taxonomy module (D7) to list Continents, Countries, and Cities. Continents is the 1st level, Countries is the second level, Cities is the third. Or, in other words, Countries and Cities are children to Continents.

That's quite a number of terms.

All has been going well for a while but it seems I have reached some kind of a limit. Indeed, I can save new terms on the root level but when I move them to be children (at the 3rd level) the update no longer saves. There is no error message and no confirmation that the new configuration was saved. Indeed, the new terms are back to the root level after that.

I have added "max_input_vars = 1500" to my php.ini file but it didn't help.

The server generates no error.

Any idea or suggestion on how to fix this?

Thanks. :)

Update: If I move a term from the root directory to become the child of another term, the (new) automatic URL is not written in the database. I have to delete some existing terms to be able to save new terms (by the same number.) This tells me there is an imposed limit somewhere.

The fix is as follows:

In your php.ini file, increase the max_input_vars to 2000. That should fix the issue with taxonomy terms and blocks too.


Extremely large Permissions table Does anyone know if there's an inherent problem with an extremely large permissions table? I'm dealing with a Drupal install with about 50 roles (permissions were set up using taxonomy terms), and there look to be about 800 permissions. So, quick estimates suggests approximately 40000 checkboxes on the permission table. Now, out of all of these, probably only about .1% are actually checked; I know that the role_permissions table only stores the enabled permissions. I don't know how Drupal is checking the permissions though as it goes; obviously, if it were making DB calls for each checkbox to check its status, that would be horrible.

Obviously, this can't be a good thing, but can someone tell me if it's necessarily a bad thing? The connection seems to be timing out before table gets loaded (or at least I think it's timing out; this is my first time using IIS with Drupal, and it's error message is vague, to say the least.) Does anyone have any suggestions beyond "remove unnecessary roles"? (Not that it's a bad suggestion, and I'll probably end up having to recommend it anyway, I'm just looking for additional options.)

No, Drupal isn't making a single DB call per checkbox - that would be suicide :)

Looking at user_role_permissions() should de-mystify the whole thing...all enabled permissions for the given roles (or all roles if none are provided), are lazy-loaded into memory when they're needed, and statically cached for the same request.

It's about as efficient as it can possibly be when you consider how Drupal's permission system works - I doubt you'll be able to squeeze anything more out of it that wouldn't be considered pointless micro-optimising.

As an aside 50 roles is a lot. I've never seen a site with anywhere near that many; if you can reduce the number of those, you'll be doing yourself a great service.


How to put two blocks inline in menu bar In every theme I tested so far, when a block is added to Menu bar area, each block is always shown stacked in pile, my question is:

  There is a way to to make two or more blocks showing inline in menu bar area?

Please don't say that the question is "too generic", since I tested a plenty of template and they all stack blocks in pile!

Tpl modifications &/or css solutions are both welcome.
No scripting please.

This is really a question on how to align blocks horizontally in a region, which calls for a CSS solution.

There are a few things to consider before you start:

Blocks have no defined width. Normally the outer wrapper is just a
div, as determined by the block.tpl file, and it is precisely because of
this that they take up all the horizontal space given to them. That
is why they stack vertically.
Each theme might be slightly different in handling floats. Some
themes are fixed width, some are fluid, some have a built in
framework for handling layout, most don't.

For a theme that has a fluid layout without a built-in layout framework, and showing two blocks inline, you can do this:

@media screen and (min-width:761px) {
    .region-featured:before,
    .region-featured:after {
        content: " "; /* 1 */
        display: table; /* 2 */
    }

    .region-featured:after {
        clear: both;
    }

    /**
     * For IE 6/7 only
     * Include this rule to trigger hasLayout and contain floats.
     */
    .region-featured {
        *zoom: 1;
    }
    .region-featured .block {
        width:50%;
        float:left;
    }
}

This will float two blocks side by side when the overall width is greater than 760px. If you have a fixed width site, then remove the media query. Also note the clearfix styling (when using a layout manager it will just be a class) which ensures that the region wrapper grows vertically to enclose the blocks.

The width of the block was set to 50% because there are two blocks that I wanted to float next to each other (100% / 2 = 50%). For three blocks you will set a width of 33.333333% etc.

When using a layout framework (recommended, and mostly baked into the theme), then it will all just be a matter of assigning proper classes, so you would then need to assign a region-class in the page template to the region, and assign classes to the blocks, perhaps using a module like Block Class, or also inside the block or region template file.

For a theme with a baked-in layout framework, look at Bootstrap, amongst numerous others. It is extremely easy to use, but you must familiarise yourself with the official bootstrap documentation. Bootstrap is not Drupal specific. It is just a framework that the Drupal Bootstrap theme developers adopted.

For more CSS solutions on aligning Divs horizontally, How to Align Divs Horizontally in CSS


How to create a rule to conditionally send a notification email, based on field value? In the Article content type, I have a field called "Assign to" which is a reference to a User entity. So that the users (editors) can know witch articles are assigned to them by the administrators.

How should I configure the Rules module to send an email to editor when article is assigned to an editor, telling editors witch article is assigned to them, and who assigned this article?

Here is a sample of a rule (in Rules export format), which will send an eMail to the userid selected via the field field_article_reviewer (= a field I added to my "Article" content type that is defined as an entity reference to a 'user'), and this whenever content of content type "Article" is saved:

{ "rules_notify_editor_about_outstanding_review" : {
    "LABEL" : "Notify editor about outstanding review",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_presave--article" : { "bundle" : "article" } },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_article_reviewer" } }
    ],
    "DO" : [
      { "mail" : {
          "to" : "[node:field-article-reviewer]",
          "subject" : "Article waiting your review",
          "message" : "[node:author] has submitted a new Article post waiting your review.\r\n\r\nYou can review it at: [node:edit-url].",
          "from" : "[site:current-user:mail]",
          "language" : [ "" ]
        }
      }
    ]
  }
}

If (before importing this rule in your environment) in the above exported rule you'd change the field field_article_reviewer to match with your field name of the editor, you should be pretty close to getting it to work.

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


How to save file as a settings How can i use settings form http://api.drupal.org/api/drupal/modules%21system%21system.module/function/system_settings_form/7 to make a file saved and retrieved using variable_get() ?

I am using Drupal 7.

The settings form does not save entries to a file, but stores the value in the database. It can only be called from a custom module you will have to build.

Below you will find a link to Drupal's own module tutorial. Follow the steps and you will come across the usage of the settings page. (configuration form)

http://drupal.org/node/361112


How to hide clientside validation error message Right now, I am using Clientside Validation. Everything works perfectly. But I would like to remove the error message which I set it showed at the top of the form. In the meantime, I would like to keep the error class which is added to my field input.

I have searched a lot about this but didn't get lucky. I know I might need to modify some code in sites/all/modules/clientside_validation/clientside_validation.js file, but I don't know which part I should touch.

Here is a sample screenshot:

Does anyone have any idea about this?

You can hide error message using CSS or you can use Inline Form Errors which allow you to hide the error message.


How can I restrict changes to certain fields in a view for a user? I have a view with a few fields and a few filters. I was wondering if there is a way to restrict a certain role from being able to change the fields/filters but only change one filter?

I know I can restrict access to the whole views from certain roles that's not what i'm trying to accomplish.

Example:

Edit:
Sorry, should have been more clear.

I have a client who has a service being featured on the front page of the site.

I have a view which shows fields from the featured service content type.

I need the owner of the site to be able to filter which piece of content to be show on the front of the site with the filter that should be editable but not mess up the view by accidentally changing other fields or filters. I do not need the filter exposed to visitors.

You can expose only the Title filter to the user. They will be able to see all of the content, but only specify the exposed filter.

You can expose a filter while editing it by checking the box that says "Expose this filter to visitors, to allow them to change it".


How to get a Drupal 7 Services 3 custom resource to fire I have a service endpoint defined in a custom module, as well as a custom resource. They both appear in the Services admin pages, with the resource and its operation checked.

When I hit http://localhost/myservice/myresource?myparm=1, I do not make it to the callback for the resource, but do not receive an error message. The log output shows:

Location    http://localhost/myservice/myresource?myparam=1
Message
Server info main object:

stdClass Object
(
    [module] => rest_server
    [endpoint] => myservice
    [endpoint_path] => myservice
    [debug] => 1
    [settings] => Array
    (
    )

)

Which seems to indicate that it is only recognizing the endpoint and not the resource portion of the path.

The defining code is as follows:

function my_feed_ctools_plugin_api($owner, $api) {
  if ($owner == 'services' && $api == 'services') {
    return array(
      'version' => 3,
      'file' => 'my_feed.services.inc', // Optional parameter to indicate the file name to load.
      'path' => drupal_get_path('module', 'my_feed'),
    );
  }
}

function my_feed_services_resources() {
  $my_resource = array(
    'myresource' => array(
      'retrieve' => array(
        'file' => array('type' => 'inc', 'module' => 'my_feed', 'name' => 'my_feed.services'),
        'callback' => '_myresource_retrieve',
        'help' => 'Lorem ipsum.',
        'args' => array(
          array(
            'name' => 'myparm',
            'optional' => TRUE,
            'source' => array('param'),
            'type' => 'string',
            'description' => 'Lorem ipsum',
          ),
        ),
      ),
    ),
  );

  return $my_resource;
}

function my_feed_default_services_endpoint() {
    $endpoint = new stdClass();
    $endpoint->disabled = FALSE;
    $endpoint->api_version = 3;
    $endpoint->name = 'myservice';
    $endpoint->server = 'rest_server';
    $endpoint->path = 'myservice';
    $endpoint->authentication = array();
    $endpoint->server_settings = array();
    $endpoint->resources = array(
      'myresource' => array(
        'operations' => array(
          'retrieve' => array(
            'enabled' => '1',
          ),
        ),
      ),
    );
    $endpoint->debug = 1;

    return array($endpoint);
  }

and in my_feed.services.inc

function _myresource_retrieve($args) {
  print "args=" . print_r($args,1);
}

You need to wrap your retrieve resource in an actions array:

function my_feed_services_resources() {

  $my_resource = array(
    'myresource' => array(
      'actions' => array(
        'retrieve' => array(
          'file' => array('type' => 'inc', 'module' => 'my_feed', 'name' => 'my_feed.services'),
          'callback' => '_myresource_retrieve',
          'help' => 'Lorem ipsum.',
          'args' => array(
            array(
              'name' => 'myparm',
              'optional' => TRUE,
              'source' => array('param'),
              'type' => 'string',
              'description' => 'Lorem ipsum',
            ),
          ),
        ),
      ),
    ),
  );

  return $my_resource;
}

You can then "fire" it by doing a POST to: ?q=[my-endpoint]/myresource/retrieve.json

Don't forget to attach the X-CSRF-Token header to your POST calls. Its value can be retrieved here: ?q=services/session/token


How do I pass JavaScript variables back to PHP? I'm trying to build a Drupal 8 module with a jQuery plugin. I wanted to pass some of the JavaScript variables to PHP so that I can save the variables into database.

This question asked about the way to do it in Drupal 7. Since hook_menu() is gone in Drupal 8, how can I accomplish this task?

Where you implemented hook_menu(), in Drupal 8 you need:

A .routing.yml file containing the routing definition

example.name:
  path: '/example/{variable}'
  defaults:
    _controller: '\Drupal\example\Controller\ExampleController::content'
  requirements:
    _permission: 'access content'

A controller class for the page callback

class ExampleController {
  // ...
  public function content($variable) {
    // Do something with $variable.
  }
}

What is important is the file structure, which should be as follows, assuming that example is the machine name of the module.

example
The directory containing the module

example.routing.yml
src
The directory containing all the classes

Controller (directory)

ExampleController.php
The file containing the controller

Keep in mind that you can change the machine name of the module, the route name (example.name), and the name of the class implementing the controller (ExampleController); the ones I used are only examples.


Add background image to block from view I created a view that list items from a content type. I have a block display for this view. I want to be able to put a different background image on each instances of this block.

Ideally, it could show up as an option in Block Settings > Allowed settings so this way every instance would have its own background image.

A second option would be that there is an other option in Block Settings below Block Name, something like Block Bakgorund. This time the same background image would be use as every instance of the block.

An other option would be to create a custom block that has 2 fields, a background image and a entity reference field on the content type my view was listing. Two problems with this, first this come to the same as re-write the functionality of Views, and second I am not sure if I would be able to create a field that is an entity reference on a block created programmatically (module plugin)

Any solution to this or thoughts?

I finally had time to make a custom module for that: ctool_views_extender

In your MODULE.module:

<?php

use Drupal\views\Plugin\views\display\Block as CoreBlock;
use Drupal\MODULE\Plugin\Display\Block;

/**
 * Implements hook_views_plugins_display_alter().
 */
function MODULE_views_plugins_display_alter(&$displays) {
  if (!empty($displays['block']['class'])) {
    $displays['block']['class'] = Block::class;
  }
}

In src/Plugin/Display/Block.php:

<?php
/**
 * @file
 * Contains \Drupal\MODULE\Plugin\Display\Block.
 */

namespace Drupal\MODULE\Plugin\Display;

use Drupal\Core\Form\FormStateInterface;
use Drupal\views\Plugin\Block\ViewsBlock;
use Drupal\ctools_views\Plugin\Display\Block as CtoolsBlock;

/**
 * Provides a Block display plugin that allows for greater control over Views
 * block settings.
 */
class Block extends CtoolsBlock {

  /**
   * {@inheritdoc}
   */
  public function optionsSummary(&$categories, &$options) {
    parent::optionsSummary($categories, $options);
    $filtered_allow = array_filter($this->getOption('allow'));
    $filter_options = [
      'background' => $this->t('Background')
    ];
    $filter_intersect = array_intersect_key($filter_options, $filtered_allow);

    $options['allow'] = array(
      'category' => 'block',
      'title' => $this->t('Allow settings'),
      'value' => empty($filtered_allow) ? $this->t('None') : implode(', ', $filter_intersect),
    );
  }

  /**
   * {@inheritdoc}
   */
  public function buildOptionsForm(&$form, FormStateInterface $form_state) {
    parent::buildOptionsForm($form, $form_state);
    $options = $form['allow']['#options'];
    $options['background'] = $this->t('Background');
    $form['allow']['#options'] = $options;
  }

  /**
   * {@inheritdoc}
   */
  public function blockForm(ViewsBlock $block, array &$form, FormStateInterface $form_state) {
    $form = parent::blockForm($block, $form, $form_state);

    $allow_settings = array_filter($this->getOption('allow'));
    $block_configuration = $block->getConfiguration();

    if(!empty($allow_settings['background'])){
      $form['override']['background'] = array(
        '#type' => 'managed_file',
        '#title' => $this->t('Background'),
        '#description' => $this->t('Enter background image'),
        '#default_value' => isset($block_configuration['background'])?$block_configuration['background']:'',
        '#upload_location' => 'public://backgrounds'
      );
    }

    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function blockSubmit(ViewsBlock $block, $form, FormStateInterface $form_state) {
    // Set default value for items_per_page if left blank.
    if (empty($form_state->getValue(array('override', 'items_per_page')))) {
      $form_state->setValue(array('override', 'items_per_page'), "none");
    }

    parent::blockSubmit($block, $form, $form_state);
    $configuration = $block->getConfiguration();
    $allow_settings = array_filter($this->getOption('allow'));

    if (!empty($allow_settings['background'])) {
        $background = $form_state->getValue(['override', 'background']);
        $configuration['background'] = $background;
        // fix bug in Drupal which does not put the image as permanent
        $fid = $form_state->getValue(['override', 'background'])[0];
        /** @var \Drupal\file\Entity\File $file */
        $file = \Drupal\file\Entity\File::load($fid);
        /** @var \Drupal\file\FileUsage\DatabaseFileUsageBackend $file_usage */
        $file_usage = \Drupal::service('file.usage');
        $file_usage->add($file, 'ctools_views', 'image', 1);
    }

    $block->setConfiguration($configuration);
  }
}

Then all you need to do is output it in a twig template. I use another module that I made to simplify things (get_url_from_fid on github or How to get path of image from file id on SE)

{% set background = '' %}
{% if configuration.background.0 %}
  {% set background = 'background-image: url(' ~     get_url_from_fid(configuration.background.0) ~ ')' %}
{% endif %}

<div{{ attributes.addClass(classes) }} style="{{ background }}">

Cheers!


Why are the images missing in newsletter emails created using Simplenews? I have created newsletter using the Simplenews module. I have inserted images using the WYSIWYG editor. The mail received is missing those images. There is no indication of images in the newsletter. How to make the images appears in the newsletter email?

mailsystem: SMTP

For Sending newsletter with image you have to send mail in HTML format not in text format. One more thing for Html mail format you have to use Mimemail or Html mail.

Mail content images have absolute src path. So that image will be accessible by email.


How to change url webform entry textfiled to link in views? I have url data (for example http://testtt.infoo) submitted from webform (component textfield).

When I display by using Views, this looks like text. I hope I can click it and open the url site.

What should I do to make that url data displayed as clickable link.

Add the component value which stores the URL to your View. Configure the field and choose to 'exclude from display'. Add a new custom Global: custom text field to your view. Choose Rewrite results -> output this field as link. In the link path field choose the URL component value from the replacements values list.


How to use a variable in script tag of template file? I want to use $node->title in the script tag so that I can get data dynamically for particular titles. So I am not getting how can I achieve this. I tried like below, but not worked.

 <script type="text/javascript">
     var job_title = $node->title;
     var container_id = "#footer";
     Springest.getTrainings(job_title, container_id);
  </script>

Thanks for any suggestions.

You can simply embed php in javascript, however the way you are adding your js is not recommended, please look around drupal way of adding js and sending values from php to javascript.

Having said that, the following code might help you-

<script type="text/javascript">
     var job_title = <?php echo $node->title; ?>;
     var container_id = "#footer";
     Springest.getTrainings(job_title, container_id);
  </script>


How to show two dropdown select lists using a single ajax call in form api .? I have a form in which user needs to input his height. I have two radio buttons to select the format in which the user wishes to input his height. one is  "feet-inch" and  another is "centimeters". I want to show a dropdown if "feet-inch" is selected, or else a textfield if "centimeters"is selected using ajax.

Am being able to show the textfield and a single dropdown successfully with ajax call triggered from the selection of the radio buttons, But I need to have two dropdowns, one to select "feet" and another to select "inches" right..?

So my problem is that am not being able to show two dropdowns with one single ajax call.
How can I achieve it...?? Or in other words, how can I replace two separate divs (both containing a dropdown select) with one single ajax call..?

Alseo do let me know, if there are  any other better ways to achieve this kind of height selection form..?

Please provide, codes for both form elements and the ajax call if possible.

Thanks in advance.

////  EDIT   /////

I put both select fields inside a fieldset and wrapped that fieldset with the wrapper to be replaced. and put it inside the something_form() function with an if statement. I dont know where am going wrong... Below is my code, please show me wats wrong....

<?php
function my_form($form,&form_state)
{
$form['health_set']['height_set'] = array(
        '#title'=>t('Input your height'),
        '#type'=>'fieldset',
            '#tree'=>TRUE,
            );

$form['health_set']['height_set']['height_radio'] = array(
    '#title' => t("Height input format"),
    '#type' => 'radios',
    '#options' => array(
      1 => t('feet'),
      2 => t('centimeters'),
      ),

    '#required'=>TRUE,
    '#ajax' => array(
       'callback' => 'health_height_callback',
       'wrapper' => 'health_height-wrapper',
      'effect'=>'slide',
     ),
    );

if($form_state['values']['health_set']['height_set']['height_radio']==1)
{

$form['health_set']['height_set']['feet-inch'] = array(
   '#type'=>'fieldset',
   '#tree'=>TRUE,
    '#prefix'=>'
',
    '#suffix'=>'
',
  );

      $options1 = array(
    1=>t('1 ft'),
        2=>t('2 ft'),
        3=>t('3 ft'),
        4=>t('4 ft'),
        5=>t('5 ft'),
    6=>t('6 ft'),
    7=>t('7 ft'),
     );

$form['health_my_bmi']['height_set']['feet-inch']['feet'] = array(
        '#type'=>'select',
        '#options'=>$options1,
        '#required'=>TRUE,
        '#description'=>t('Whats your height in feet?'),
      );

$options2 = array(
    1=>t('1 inch'),
        2=>t('2 inch'),
        3=>t('3 inch'),
        4=>t('4 inch'),
        5=>t('5 inch'),
    6=>t('6 inch'),
    7=>t('7 inch'),
        8=>t('8 inch'),
        9=>t('9 inch'),
        10=>t('10 inch'),
        11=>t('11 inch'),
     );

$form['health_set']['height_set']['feet-inch']['inch'] = array(
       '#type'=>'select',
        '#options'=>$options2,
        '#title'=>t('Inches'),
        '#description'=>t('how many inches ?'),
        '#required'=>TRUE,

      );

}

else if($form_state['values']['health_set']['height_set']['height_radio']==2)
{

   $form['health_set']['height_set']['centi'] = array(
        '#type'=>'textfield',
        '#title'=>'Height in centimeters',
        '#prefix'=>'
',
        '#suffix'=>'
',
         '#maxlength'=>3,
         '#size'=>6,
        '#required'=>TRUE,
      );

}

  return $form;

}
?>

below is the code of the callback function,

<?php
function health_height_callback($form, $form_state)
{
       if($form_state['values']['health_set']['height_set']['height_radio']==1)
           return $form['health_set']['height_set']['feet-inch'];

      else if($form_state['values']['health_set']['height_set']['height_radio']==2)
           return $form['health_set']['height_set']['centi'];

}
?>

I'm not sure exactly. But if you just want to show some FAPI elements based on the condition that radio is X or Y .... I would just use #states in the D7 FAPI api.


Page rendered correctly but display errors Page was rendered correctly but it display the following error message:

Strict warning: Only variables should be passed by reference in include() (line 31 of C:\xampp\htdocs\mysite\sites\all\themes\mytheme\templates\page.tpl.php).

I have a image field name field_header_image and I want to used the image as the header background image in my page.tpl.php. here is my code

<div id="hero-container" class="hero-container" style="background:linear-gradient(rgba(0, 0, 0, 0.35), rgba(0, 0, 0, 0.35)), url('<?php echo render(file_create_url($node->field_header_image['und'][0]['uri'])); ?>');">

It display correctly and I can use the field image as my header background but it display the above error. Is there a better way to get rid of this error without using a module.

First of all, the 'und' is not prefered, you should use LANGUAGE_NONE constant instead. This is not part of the sollution, but part of the Drupal coding standards.

This is a tricky one. The function render() expects a string, but you give a part of an object with some deeper array keys.
The simplest way to get around the strict warning is to use the following code:

<?php $uri = file_create_url($node->field_header_image[LANGUAGE_NONE][0]['uri']); ?>
<div id="hero-container" class="hero-container" style="background:linear-gradient(rgba(0, 0, 0, 0.35), rgba(0, 0, 0, 0.35)), url('<?php print render($uri); ?>');">


How to programmatically translate/localize taxonomy terms? I want to use Google Translate for translating taxonomy terms. I have the "Talking to Google" part done, but I can't find much documentation on translating terms & their descriptions programmatically.

Please help!

I was able to do it using the following code:

<?php
    $enabled_languages = array_shift(language_list('enabled'));
    foreach ($enabled_languages as $language => $object) {
        if ($language != 'en') {
            //Translate description
            i18n_string_translation_update(
                array('taxonomy', 'term', 12, 'description'), // Path where to store source and translation.
                autotranslate_translate($term->description, 'en', substr($language, 0, 2)),
                $language
            );
            //Translate name
            i18n_string_translation_update(
                array('taxonomy', 'term', 12, 'name'), // Path where to store source and translation.
                autotranslate_translate($term->name, 'en', substr($language, 0, 2)),
                $language
            );
        }
    }

?>


pass result of Rules loop to variable to use outside loop In Drupal Commerce, i have created a rule that calculates the price by adding some fields (custom line items), and then sets a result.

Now i want to make a loop (to pass over fields of a Field Collection with unlimited fields, so for each field collection set), and then set a result.

The question is: how can i get the result available to use outside the loop? (as a Data Selector value for a normal action)

You may have success there using the "provides" key in hook_rules_action_info to provide a variable.

more info: http://drupal.org/node/878972


Multiple Relationships in CiviCRM Views Integration I have been trying to set up a Drupal View of a a 3-way relationship in CiviCRM.

The view I wanted was that showed a list of contacts that are provided services from the current user's employer, as below

(current user) contact a => (is employed by) => organisation => (is a provider of) => contact c

I created a view of CiviCRM Contacts, and could not see a way of getting this relationship to display what I wanted without building a custom module, which is explained below.

You can do this with a custom module and using the preprocess views hook to pass in the contextual filter. The filters are passed into the $args[] variable.

You also may need to enable multiple values in a contextual filter, if you have more than one relationship from Contact A to Contact B, in this case this is multiple employers. This is under Contextual Filters > Advanced > Allow multiple values.

You do not add % to the path as you would normally do with a contextual filter as we are programmatically inserting it.

Create a custom Drupal module with the following code

/**
* @implements hook_views_pre_view().
*/
function HOOK_views_pre_view(&$view, &$display_id, &$args){

if($view->name == "my_view") {
      // Check that we are altering the correct view based on and $view->name
      civicrm_initialize();
      require_once 'api/api.php';
      //get the matching civi id for the current user
      //This is using Civicrm version 4.4.6

      global $user;
      //first get the current user's Civicrm record
      $params = array(
         'version' => 3,
         'sequential' => 1,
         'uf_id' => $user->uid,
      );
      /*The contact ID is in $result['values'][0]['contact_id']*/
      $result = civicrm_api('UFMatch', 'get', $params);

      $params = array(
          'version' => 3,
          'sequential' => 1,
          'relationship_type_id' => 5, /*get your relationship ID from /civicrm/admin*/
          'contact_id_a' => $result['values'][0]['contact_id'],
      );
      $result = civicrm_api('Relationship', 'get', $params);

      //temp stores the string which will be passed to the $args[] array
      $temp = "";

      //loop through the a => b relationships, and append all the ids of contact b
      foreach ($result[values] as $key => $value ) {
         if ($key > 0)
            $temp .= "+";
         $temp .= $value['contact_id_b'];
      }
      // populate the $args contextual filters array with the ids.
      $args[] = $temp;
   }
}


How to access the node title within a field template? I'd like to know the node title within the file link template. How can I get it?

For the current example I use the bootstrap file-link.html.twig template. In it, I have the following variables:

{#
/**
 * @file
 * Theme override for a link to a file.
 *
 * Available variables:
 * - attributes: The HTML attributes for the containing element.
 * - link: A link to the file.
 * - icon: An icon.
 * - icon_only: Flag to display only the icon and not the label.
 * - icon_position: Where an icon should be displayed.
 *
 * @see \Drupal\bootstrap\Plugin\Preprocess\FileLink::preprocessVariables
 */
#}

I dont know if a preprocess function is the correct way to go. I didnt even found a respective hook for drupal 8 for that. I dont even know if this is a field template. But still, the question would also be interesting for other templates than file-link.

He wants to get the node title in the file link template (I assume that is file-link.html.twig).
You can implement the hook template_preprocess_file_link() in your mytheme.theme file, get the current node and pass its title to twig, something like:

function mytheme_preprocess_file_link(&$variables) {
   $node = \Drupal::request()->attributes->get('node');
   $variables['node_title'] = $node->getTitle();
}

Then, in file-link.html.twig:

{{ node_title }}


How to change the image style used in a field in specific view results? In Drupal 7 I used hook_views_pre_render() to update the image style for specific results. I'm trying to do the same for a view in Drupal 8 but I don't have the same options available in the field.

An example of the code I used before:
$view->result[4]->field_field_image[0]['rendered']['#image_style'] = 'image_style_name';

There's no longer a 'rendered' array, just an ImageItem object with the target_id, title, width and height.

The bad news is that you can't use that approach anymore. Due to the performance improvements like this one, fields are all rendered via #pre_render callbacks, and run through the same build process as normal entity rendering.

The good news is that hook_entity_display_build_alter() will run, the very same hook that runs for displaying an entity.

Views doesn't pass any additional context to this hook. Depending on how you were deciding which one to alter, you may still be able to accomplish this.


How to add .current class into menu link when page is being viewed I have a custom menu - its a module with html links in the .tpl file, set on the website as a block. I wanted to know is it possible to configure drupal so it dynamically add .current class to those links so I can style it when particular page is being viewed. Thanks for help.

If you create a new menu and make it a block then it will set a class called "active" when you are on the current page. You will also get a class called "active-trail" for each parent item. If you want to create something more custom then you can check and see if the url matches the link you are building.

You can see here how the menu is being built to get some ideas:

https://api.drupal.org/api/drupal/includes%21menu.inc/function/menu_tree_output/7

If you want to do something custom then you will need to compare $_GET['q'] to the link that you are building in order to set an active class.

I am pretty sure you can also use theme_item list and the active class will be set:

https://api.drupal.org/api/drupal/includes%21theme.inc/function/theme_item_list/7


Create a subtype of Panel & style it with a template So I'm trying to build a independent Landing Page for an event on our drupal 7 site. I would like to have the page contain a different main navigation menu then our site and also has the functionality of the content type "Panel".

I was Thinking to create a Content Type "Event" but how can I assign the Panel layout to it and how should I Assign that content type a specific menu?

The best solution would be to have a content type with the Fields:

Event Name
Panel Layout
Top Navigation Menu
...

after creating that content type I would create a theme template for that type. The template would modify the top and bottom of the page but the center should still be modified as the same as a traditional panel.

Atm I don't know how to accomplish that :(

Would love to hear some feedback guys!

when I have to create this type of "landing pages" I m usually following these steps.
1/ The Layout.
Create a Panel Page. Admin > Structure > Panel > New panel page
1A/ If you want to get ride of header/footer region > there is an option for that.
1B/ If you want to keep these regions, but diplay other blocks, go to Admin > Block > your block > Configure > Visibility settings > and setup the thing whith the page settings.
2/ Then your content.
What I'm usually doing here is depending on what you try to achieve, but if you are displaying only 1 event content, create a content type event is probably not the right approach.
But my point is, now you can create a page with what you want. So think about what you want to display (do you need a view of items ? do I need a block ? some blocks? do I need some beans ?) and architecture it as it was a standard page. Just prefix all you items type with one commun name, so you will be able to retrieve them later.
I hope it helps
Cheers


How to block permissions tab for certain users? Is there a way to block users who are allowed to edit users roles from seeing the "permissions" tab?

Can this be done without code?

This cannot be done without code.  If you take a look at user_menu() you'll see that access to both of those pages is determined by the administer permissions permission.

To block access to one but not the other will require you to implement hook_menu_alter() and change which permission is checked for one of those pages.


What approach for Commerce products, attributes and product displays? I am building a site, based on Commerce Kickstart. At this moment the site will not have a store, but it's on the horizon and I am trying to prepare the site beforehand for a store launch with as little developer hassle as possible.

My concern is now to wisely design the products and their attributes.

First off, I have two taxonomies. One is obviously a Product tree. A Commerce Product will have only one term reference value possible.
Then I have a Usage tree (or call it Applications), which describes how and where a product can be used. A Product Display will have multiple possible term references from that tree.

Now let's say, I have a brand of nails in different sizes: 1,2,3,4. The sizes 1 thru 3 would be tagged as "Home Use" and the size #4 - only as "Construction Use". All sizes would share some fields, such as main description, PDF attachments, images. And these could be fields on the Product level.

For sizes 1 thru 3, I would basically need one product display, speaking in terms of the page contents. And the Add to Cart button would have a list of models next to it: 1 thru 3. I would expect the button to add to cart SKUs mapped for each size.

For model #4 I would like to have perhaps additional set of images and a slightly different description, and the Add to Cart button would not need any select.

This is one possible approach. Another that comes to mind would be to treat all sizes as separate 4 product displays. Then, the Add to Cart buttons would have no attribute selector. This scenario could seem quite simple and obvious - a typical one-to-one relationship. However I am allergic to solutions that are not scalable, I hate cloning data as a slightest text correction would later require N edits on each product display.

So, which way would you go based on your experience? I don't know Commerce well enough but still want to be prepared for it beforehand.

I assume that SKU is something crucial for a successful and non-ambiguous order. But maybe my assumption is wrong.

I'm open for your insights.

When thinking about how to handle products and product displays, I prefer to model it after how Commerce Kickstart handles it's data organization:

Product displays are used to organize and present products to the customer and product entities are used to store product-specific information.

  First off, I have two taxonomies. One is obviously a Product tree. A Commerce Product will have only one term reference value possible. Then I have a Usage tree (or call it Applications), which describes how and where a product can be used. A Product Display will have multiple possible term references from that tree.

Product catalog taxonomies influence how products are organized and subsequently found on your site. This would mean this information would go into the Product Display.

  Now let's say, I have a brand of nails in different sizes: 1,2,3,4. The sizes 1 thru 3 would be tagged as "Home Use" and the size #4 - only as "Construction Use". All sizes would share some fields, such as main description, PDF attachments, images. And these could be fields on the Product level.

The "Use" field is a little tougher but I think you're on the right track. Anything that is specific to the individual SKU (product images, PDFs, diagrams, descriptions, sizes, etc.) would be on the product entity. You can still provide filtering using these attributes via Faceted search, but you end up not duplicating information across multiple entities.

I'm not sure how big your product catalog is, but there are some modules you can explore to ease your data management pain:

Inline Entity Forms: With IEF, you can create and manage product SKUs within your Product Displays. It makes 1:1 product relationships much easier to manage. It can also do 1:N relationships, but sharing those across multiple products can be painful with this.
The opposite of this is Commerce Auto Display, which allows you to create a Product display from within the Product entity form.

If you want to go down this road, IEF is preferred, since it tends to want you to keep only the SKU, price, and other bare minimum fields on the product entity.


Custom e-mail translation in Drupal 8 I need to send some e-mails depending on some actions. These e-mails should be translated depending on the target user's preferred language. I've seen that the mail function has a language parameter, but for me, it's not really do anything.

  $renderArray = [
    '#theme' => 'email_notification_content_update',
    '#name' => $node->getOwner()->getDisplayName(),
    '#content_title' => $node->getTitle(),
    '#content_url' => $node->toUrl('canonical', ['absolute' => TRUE])
      ->toString(),
    '#unfollow_url' => Url::fromRoute('flag.field_entry.delete', [
      'flag' => 'flag_name',
      'entity_id' => $node->id(),
    ])->setAbsolute()->toString(),
  ];

  $this->mailManager->mail(
    'my_module',
    'email_notification_content_update',
    $follower->getEmail(),
    $follower->language()->getId(),
    [
      'body' => $this->renderer->renderRoot($renderArray),
      'subject' => $this->t('An update of the content @title has been updated.', ['@title' => $node->getTitle()]),
    ]
  );

Currently, the e-mail text is in twig file (with links) and the parameters are passed to it at render. Now I can put the whole twig file in {% trans %} tags, but is there a better way? Like using the mail function's language parameter? Is there a better way to make a custom e-mail sending and have translations to them?

Be aware that the rendering (and therefore the translation) happens at $this->renderer->renderRoot(). I'd create a mail key handler, and build the body inside that handler. I'm not sure, but it may be that drupal switches to the given language at the ->mail function before processing the custom hook.

  $this->mailManager->mail(
    'mymodule',
    'content_update',
    $follower->getEmail(),
    $follower->language()->getId(),
    [
      'node' => $node,
    ]
  );

/mymodule.module

<?php

use Drupal\Core\Url;

/**
 * Implements hook_mail().
 */
function mymodule_mail($key, &$message, $params) {
  $renderer = Drupal::service('renderer');

  if ($key === 'content_update') {
    $node = $params['node'];
    $renderArray = [
      '#theme' => 'email_notification_content_update',
      '#name' => $node->getOwner()->getDisplayName(),
      '#content_title' => $node->getTitle(),
      '#content_url' => $node->toUrl('canonical', ['absolute' => TRUE])
        ->toString(),
      '#unfollow_url' => Url::fromRoute('flag.field_entry.delete', [
        'flag' => 'flag_name',
        'entity_id' => $node->id(),
      ])->setAbsolute()->toString(),
    ];
    $message['body'] = $renderer->renderRoot($renderArray);
    $message['subject'] = t("Content :title has been updated", [':title' => $node->label()]),
  }
}


How can I cascade field display formatters? I need to display a thumbnail of my images and the count of its downloads below the thumbnail.

I am using these modules:

CCK
FileField
ImageField
ImageCache
DownloadCount

and I think I need something like cascading these two formatter:

Generic files with download count (comes from DownloadCount)
examination_question_image image linked to image (comes from imagecache where examination_question_image is my "Preset Name")

Is there any module or anything else for this?

You should try the Media module. I think it will solve your problems.


Create a view to list all contents that uses media through any entity reference field I know it is possible to create view to list all content that is using media through a particular entity reference field.

Is it possible to create a view to to list all content that is using media thought any entity reference field?

Mostly yes, by adding relationships to a view. The drawback is that is not done automatically: you manually have to add all entities/fields that possibly can refenrence a media entity. Create a view showing media entities. Then add the related tables and filter criterias "related/foreign field referencing media -- is not empty"

I'd not recommend the "File usage" relation and its "Use count" field. It doesn't seem to count correctly in my projects.


One menu, many levels, few editors How can I have 1 menu (site map), hierarchical structure like:

Dept 1

Abc
Def
Ghi

Dept 4

AAA
BBB

ffe
ffg
ffx

CCC

With possibility to delegate editing permission of subtrees to some users?
I.e. : main admin edits the whole menu, admin A edits only submenu in Dept1, admin B edits only submenu BBB in submenu Dept 4 ...

Is there any module which can be used to do that? I know that Organic Groups has possibility of creating menus for every group with feature of editing permission to group members. But I'd rather have 1 big menu for the whole site...

You haven't specified which Drupal version you are using, but check out Menu Subtree Permissions for D6.


Attach shipping courier selection at drupal cart commerce line item Anyone have Idea how to attach shipping courier selection at drupal commerce cart? As seen at capture bellow, I want to attach shipping courier selection at cart, so I can pick shipping courier for each order line item. Anyone have Idea?

https://lh3.googleusercontent.com/-OMoDWmIZcyo/VFkLxBQGcWI/AAAAAAAACtc/lCidjfXgeSI/w1043-h396-no/Capture.PNG

I think Commerce Delivery module solved your problem.

Or you need to add Shipping plugin.

Please check this two links. I think this may help you.

Link 1

Link 2


How do I make a submit through AJAX? I created a webform in Drupal 8. While submitting the form, it reloads the whole page, even I had selected inline submission in confirmation message.

Just checked your issue by upgrading Webform to version 8.x-5.0-beta15. After enabling AJAX on the form and setting the confirmation to either inline or message the confirmation worked as expected. I did needed to clear my cache though.

So try upgrading the Webform module and clear your cache.


Theming a node edit Form - Move Author Information to another positon I am theming the DRUPAL 7 NODE EDIT FORM following the instructions in the post.

Everything is working fine.

However, I want to move the "Authoring Information" from the bottom of the page to another position on my node. How do I do that?

I thought I would be able to use this:

<?php print drupal_render($form['author']); ?>

But it does not seem to work.

You can use the Display Suite module.

  Display Suite allows you to take full control over how your content is displayed using a drag and drop interface. Arrange your nodes, views, comments, user data etc. the way you want without having to work your way through dozens of template files. A predefined list of layouts (Drupal 7 only) is available for even more drag and drop fun!


How to make a case sensitive entity query? My custom entity type comes with a string field for which I would prefer case sensitive queries. When I use
$query = \Drupal::entityQuery('my_entity_type')
 ->condition('my_token_field', 'SomeSortofTokenString')
 ->execute();

the result will include all entities no matter if the string in my_token_field is written the same way or for example with lowercases only. my_token_field is set a base field of type string - maybe this is the problem?

Like you already said, I think you should set case_sensitive to true in the field settings, like here. This can also be set in the config.
When digging in the code, I found that the condition function at some point leads to translateCondition which checks if a field is case sensitive and automatically applies the binary option to the sql query.


Drupal Views: Add Views signature to all SQL queries adding view name to Inner Join When I preview my view, I get an error and notice that the view signature in the query was added twice. The one that's an issue is:

':default' AS view_name

Here is the full query.

SELECT DISTINCT taxonomy_term_data.tid AS tid, taxonomy_term_data.name AS taxonomy_term_data_name, taxonomy_term_data.vid AS taxonomy_term_data_vid, taxonomy_vocabulary.machine_name AS taxonomy_vocabulary_machine_name, 'video_categories:block' AS view_name
FROM {taxonomy_term_data} taxonomy_term_data
INNER JOIN {node} node_taxonomy_term_data ON (SELECT nodeINNER.nid AS nidINNER, ':default' AS view_name
FROM {node} nodeINNER
LEFT JOIN {taxonomy_index} taxonomy_indexINNER ON nodeINNER.nid = taxonomy_indexINNER.nid
LEFT JOIN {taxonomy_term_data} taxonomy_term_data_nodeINNER ON taxonomy_indexINNER.tid = taxonomy_term_data_nodeINNER.tid
WHERE (( (taxonomy_term_data_nodeINNER.tid = taxonomy_term_data.tid ) ))
ORDER BY nodeINNER.nid DESC
LIMIT 1 OFFSET 0) = node_taxonomy_term_data.nid
LEFT JOIN {taxonomy_vocabulary} taxonomy_vocabulary ON taxonomy_term_data.vid = taxonomy_vocabulary.vid
WHERE (( (taxonomy_vocabulary.machine_name IN  ('video_category')) ))

The error I get is:

SQLSTATE[21000]: Cardinality violation: 1241 Operand should contain 2 column(s)

Which makes sense since I am not expecting the second parameter to be in there for view_name. Why does it do this and how do I stop this feature from adding the view_name to the inner join on my query?

When I uncheck this box, the query works as expected, however, I use the signature in my reporting to quickly identify issues, slow queries etc.

The issue was the relationship added to the view. I removed the relationship and this fixed my issue.


content access alternative for drupal 7 I need exactly this module: http://drupal.org/project/content_access which unfortunatly does not work anymore with drupal 7.18 and i dont want to search for the problem right now...

so is there any alternative? I need it to restrict users which are not in the role x to view certain sites.

Simple Access module may come to your rescue. Do check it out.


query has no result for anonymous I have below query , when it run with non-registered user return null but with any register used with any role has result .
also non-registered user has permission to view any product

$result = db_query("SELECT * FROM {node} node
LEFT JOIN {field_data_field_course_ref} field_data_field_course_ref ON node.nid = field_data_field_course_ref.entity_id AND (field_data_field_course_ref.entity_type = 'node' AND field_data_field_course_ref.deleted = '0')
LEFT JOIN {commerce_product} commerce_product_field_data_field_course_ref ON field_data_field_course_ref.field_course_ref_product_id = commerce_product_field_data_field_course_ref.product_id
WHERE (( (node.nid = :nid ) )AND(( (node.status = '1') AND (node.type IN  ('course_display')) )))
", array(':nid' => $nid));
      $coursePIDs = array();

      //get node product variation

      foreach ($result as $record) {
        $coursePIDs[$record->field_course_ref_product_id] = $record->field_course_ref_product_id;
      }

 ym($coursePIDs);

any idea?

My usual answer for this is product access permissions haven't been set that would allow anonymous users to view all products, but since you're creating this query directly it isn't clear to me that that would be getting in the way. I suppose Drupal is still running query altering on this and somehow alerting the product module that it's involved?

A simple way to rule that out would be to grant anonymous users permission to view any product of any type and see i they get results. But really seeing the query actually run by Drupal would be useful.


What is the difference between using theme_table() and theme('table', array())? I am using following code for theming..

theme('table', array('header' => $header, 'rows' => $rows, 'attributes' => array('class' => 'view-all-frame')));

is the above format right?
Can 'attributes' be written above inside array?
Can I use theme_table() instead of theme()?

theme_table(array('header' => $header, 'rows' => $rows, 'attributes' => array('class' => 'view-all-frame')));

If they are same then does it affect the execution or anything related to it?

Similarly for theme('item_list', array()) and theme_item_list();

It's not the same.

theme() function is some kind of wrapper for specified theme functions.

It's recommended to use theme() function instead of direct calls, so theme('item_list', array()) is the right way.


What Commcerce event is fired when a payment is made? There seem to be a few bugs in Commerce (8.x-2.17) related to admins making payments against a Cart. I am trying to fix some of these in my own custom module (rather than wait for people to agree these are bugs). Some, but not all, include:

payments made are not reflected anywhere.
when paid in full the order is not "completed" (not sure if this is correct term, in D7 i think the term was "checked out").
payments can be made beyond the full amount of the order (or the balance)

I think it should be possible to address some of these by subscribing to a Payment event and going in and cleaning things up (not sure where or how to clean up; but baby steps).

I have seen a post listing: commerce_order.order.paid as an event that is fired when the order is paid in full; but this is not fired (as far as i can tell) when a payment is made which completes the order (neither from admin paying or standard checkout flow).

I have also seen commerce_payment.commerce_payment.insert,  which is also not fired during payment or checkout flow. To be honest i don't understand the naming related to payments: add payment, insert, update? Why is this not "make" a payment as this is more grammatically correct.

Does anyone know what event is triggered when a payment is made (or ideally when a payment covers the balance owing on an order)?

You seem to misunderstand the term payment here. It should not be seen in the context of a regular payment that you make or complete in a store. In this context payments are entities and the events match those of database transactions (insert, update, delete, etc.).

Theoretically the combination of these 3 events should allow you to determine if a payment has been made or altered or deleted, but you need to subscribe to all of them to be updated on all changes. (If you only subscribe to inserts (new payments) but not to deletes (removed payments) you might miss data.)

The commerce_order.order.paid or the safer \Drupal\commerce_order\Event\OrderEvents::ORDER_PAID event has the following documentation:

/**
 * Name of the event fired after the order has been fully paid.
 *
 * Guaranteed to only fire once, when the order balance reaches zero.
 * Subsequent changes to the balance won't redispatch the event (e.g. in case
 * of a refund followed by an additional payment).
 *
 * Fired before the order is saved.
 *
 * @Event
 *
 * @see \Drupal\commerce_order\OrderInterface::getBalance()
 * @see \Drupal\commerce_order\Event\OrderEvent
 */
const ORDER_PAID = 'commerce_order.order.paid';

It is called from doOrderPreSave() in OrderStorage.php, but only if the event has not dispatched before:

  if ($order->getData('paid_event_dispatched') === FALSE) {
    $event = new OrderEvent($order);
    $this->eventDispatcher->dispatch(OrderEvents::ORDER_PAID, $event);
    $order->setData('paid_event_dispatched', TRUE);
  }

When a payment is made, the order is listed in the commerce_payment.order_updater service which during its destruct will update and save all listed orders. Those in turn will determine if the total order balance has been reduced to zero and emit the event. It looks sensible to me.

Could it be that you have been testing with the same order over and over and that event already fired once?


How to update MariaDB? I was following Set up Demo Site for Theming Practice; then, I realized that, since Drupal 9 is out, by default Drupal 9 is installed instead of Drupa 8.x is installed when running composer create-project drupal/recommended-project $SITE_NAME.

So I continued along. I was fine, until I came to the install local site. I got this error:

  The database server version 10.2.31-MariaDB-1:10.2.31+maria~bionic-log is less than the minimum required version 10.3.7.

Since I'm using ddev and docker, does this mean I need to upgrade my MariaDB version used inside of my image? if so, how do I do that?

A step by step solution explaining each step would be really helpful.

Yes, you need to update MariaDB. Just "cd" to your ddev project directory in the terminal and issue the following commands:

ddev config --mariadb-version=10.4

and then

ddev restart

That's it! Good luck:)


Uncaught exception 'PDOException' with message 'SQLSTATE[HY000]: General error: 2006 MySQL server has gone away' My website was working till a few days ago. It suddenly stopped working and showing white screen on every page only when some users including administrator are logging in to it. I added the following line at the top of the index.php

error_reporting(E_ALL); ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);

The following error is displaying

  Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[HY000]: General error: 2006 MySQL server has gone away' in /home/******/public_html/includes/database/database.inc:2204 Stack trace: #0 /home/******/public_html/includes/database/database.inc(2204): PDOStatement->execute(Array) #1 /home/******/public_html/includes/database/database.inc(683): DatabaseStatementBase->execute(Array, Array) #2 /home/******/public_html/includes/database/database.inc(2383): DatabaseConnection->query('SELECT expire, ...', Array, Array) #3 /home/******/public_html/includes/lock.inc(167): db_query('SELECT expire, ...', Array) #4 /home/******/public_html/includes/lock.inc(146): lock_may_be_available('theme_registry:...') #5 /home/******/public_html/includes/theme.inc(449): lock_acquire('theme_registry:...') #6 /home/******/public_html/includes/bootstrap.inc(455): ThemeRegistry->set(Array) #7 [internal function]: DrupalCacheArray->__destruct() #8 {main} thrown in /home/******/public_html/includes/database/database.inc on line 2204

I really have no idea what to do.
thanks in advance

99% of the times I've seen that error it is because the website is trying to save more data than the amount expected by MySQL.

It is fixed increasing the value of the mysql variable max_allowed_packet

The value of this variable is given in bytes, and by default it is set to 1048576 (1 Mb).

You can try to modify it to something bigger, like 4194304 (4 Mb) and keep increasing it to a value that do not give you this error.


Fatal error: Cannot redeclare MYTHEME_preprocess_page() I'm new at Drupal, so please help to solve the problem. :)
I've found an article: Change templates based on path alias

It describes my situation. But when I include described code or just this line:

function lm_sr4_preprocess_page(&$vars) {}

In mywebsite.com/sites/default/themes/lm_sr4/template.php it just causes this error:

Fatal error: Cannot redeclare lm_sr4_preprocess_page() (previously declared in /var/www/sites/lmsr2.video-site.ru/sites/default/themes/lm_sr4/template.php:11) in /var/www/sites/lmsr2.video-site.ru/sites/default/themes/lm_sr4/preprocess/page.preprocess.inc on line 10

Here's all template.php code:

<?php

/**
 * @file
 * Template overrides as well as (pre-)process and alter hooks for the
 * lm_sr4 theme.
 */

function lm_sr4_preprocess_page(&$vars) {
  $alias_parts = explode('/', drupal_get_path_alias());

  if (count($alias_parts) && $alias_parts[0] == 'ep') {
    $vars['theme_hook_suggestions'][] = 'page__epcustomtemplate';
  }
}

function lm_sr4_views_tree_inner($variables) {

  $view = $variables['view'];
  $options = $variables['options'];
  $rows = $variables['rows'];
  $title = $variables['title'];
  $result = $variables['result'];
  $parent = $variables['parent'];

  $items = array();
  foreach ($result as $i => $record) {
    if ($record->views_tree_parent == $parent) {
      $variables['parent'] = $record->views_tree_main;
      $items[] = $rows[$i] . call_user_func(__FUNCTION__, $variables);
    }
  }
  return count($items) ? theme('item_list', array(
    'items' => $items,
    'type' => $options['type'],
    'attributes' => array(
      'class' => array(
        'menu',
      )
    )
  )) : '';
}

function lm_sr4_omega_layout_alter(&$layout) {
  if (arg(0) == 'eparchies') {
    $layout = 'eparchy';
  }
}

error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);

You have the function lm_sr4_preprocess_page() declared twice; once in template.php (line 11) and once in preprocess/page.preprocess.inc (line 10).

You need to merge those two functions together, you can only declare a function once in PHP.


webform 5 access other webform tokens Is there a way to access tokens of another webform ? I have users of one role who need to evaluate in a webform files uploaded by users with another webform

This is not supported and could be a security issue because it would allow people to use tokens to pry into information available in other entities.


How to programatically add block to Drupal 7 page tpl AND respect visibility rules? I want to add a block programatically to a page.tpl.php file in my Drupal 7 theme BUT I want it to respect the block's visibility rules.

I'm open to defining new visibility rules in PHP too but it seems whenever I manually invoke a module via code without assigning the block in a region it does not adhere to the block's visibility rules.

Turns out the solution was in how I was rendering the blocks.

Using this code to render my block added the block to Drupal's "knowledge" of the block being on the page.

$block = block_load($module, $bid);
$blockStuff = _block_get_renderable_array(_block_render_blocks(array($block)));
$output = drupal_render($blockStuff);
print $output;


Panels "custom content" argument formatting I'm using Drupal 7.4 with Panels 7.x-3.0-alpha3.  When creating a "New custom content" and using context keywords (eg %node:field-integer), the numeric integer field I'm adding gets pulled through with a comma (eg 7,234 instead of 7234).  This also happens when adding Node (tokens) items.

The field in question does not have it's display formatted like that in Content Types > Manage Display either.

I believe that Tokens and Panels Context/Arguments is pulling this from the same location, but I'm not sure where it is configured like that.

I've also tried %node:field-integer-raw and -unformatted, as well as %node:field-integer:raw and :unformatted, but neither of those worked.

Just in case someone came here through a Google search, there is an answer to the specific question.

You can specify the default formatting of tokens by going in the Content Type in question, then in "Manage Display" tab, at the bottom of the page under "Custom Display Settings" you will have to enable the "Tokens" display.

The formatting that you choose for each field in this display will be used whenever you print the field through a token.

You could also use the Advanced Entity Tokens module, which allows you to specify a different view as an "extraction base" for your field formatters.

Edit:

Note that you can also create specific token formatters for profile2 entities by following the exact same method explained above. By default profile2 creates a single Display but there is still a Custom Display Settings option at the bottom of the page where you can enable the Tokens display and specify the formatters that you want to use for your Profile2 tokens wherever you use them (including Panels).


Bulk registration or disallow registering of certain usernames I need to register 1000+ usernames at once.
How to do it?

Or is there any way to disallow from registering 1000+ usernames? People could not register certain usernames.

I need to reserve these usernames for payed registration.

You can do this by code, alter the registration form (hook_form_user_register_form_alter), in a custom module like:

function MY_MODULE_form_user_register_form_alter(&$form, &$form_state, $form_id) {
    $form['validate'][] = 'reserved_usernames';
}

And then implement the validation (in the same MY_MODULE.module file) method like:

function reserved_usernames ($form, &$form_state) {
  $reserved = array();
  $reserved[] = 'reserved_name';
  $reserved[] = 'reserved_name_1';
  $reserved[] = 'reserved_name_2';
  $reserved[] = 'reserved_name_3';
  $reserved[] = 'reserved_name_4';
  $reserved[] = 'reserved_name_5';

  if (in_array($form_state['values']['name'], $reserved)) {
    form_set_error('name', t('The name %name cannot be taken.', array('%name' => $form_state['values']['name'])));
  }
}


How do I programmatically store a file reference in a node? We have content type Image and it have image_data field for Image reference. So, how we could use static image path for node creation as well as for updating the image reference in the node.

Assume, we have content type : Image

It have following fields in the content type.

title
field_imagedata for Image field

Now, we want to create custom node.

Step : 1  We need to get static image path which we would like to attach in the node. We have in "sites\default\files\2017-01\source.png"

So, In drupal, we could access this image uri by "public://2017-01/source.png".

Step : 2 We need to create file reference in our Drupal database. Se we need to use "File::Create" method.

Step : 3 After that, we could generate node using "entity_create".

Please look at the whole code.

    $uri  = file_unmanaged_copy("public://2017-01/source.png", "public://2017-01/destinatio.jpg", FILE_EXISTS_REPLACE);
    $file = File::Create([
      'uri' => $uri,
    ]);
    $file->save();

    $new_page_values = array();
    $new_page_values['type'] = 'image';
    $new_page_values['title'] = "PARAG";
    $new_page_values['field_imageda'] = array('target_id' => $file->id());
    $new_page = entity_create('node', $new_page_values);
    $new_page->save();

Also, you could update the node, by using the following code.

    // Load existing node and attach file.
    $node = Node::load(1);
    $node->field_imageda->setValue([
      'target_id' => $file->id(),
    ]);
    $node->save();

Using this code, you could create new node with the static file.


Openlayers Scalability suggestions So, like everyone, when I came accross the requirement to incorportate maps into my Drupal site, I googled for solutions and that pretty much led me straight to the Openlayers/Geofield solution. Not even sure there is another acceptable out-of-the-box module out there.

Anyway, the module works wonders, it delivers perfectly but I have some questions/issues regarding performance.

What I need to represent in my map, are user entities. The users have a "Location" field, which is a geofield autocomplete. The site (largely due to migrationg) numbers 10.000 users currently. Granted, not all of them will actually be active, but in the worse case scenario, trying to load all 10k users results in very high waiting time in the Data Overlay step meaning the production of 10k projection items for the map to display.

Since the location field was not migrated, I initially filtered by having the field NOT NULL. This will skip querying for useless entities. But as I said, having 10.000 "active" users, who have edited their data and filled in that field might cause a system overhaul when people try to view the map.

Question 1: Could the fact that I was querying for users with Location values of NULL have resulted in higher waiting time? I mean, 10.000 users with actual data may get processed faster than 9.000 users with NULL set as location?

Question 2: Are there any general suggestions to somehow improve the map's performance? Reminding that the delay occurs in the projections' production process.

I haven't used mapping yet because of the performance contraints of showing more than a few hundred points on an openlayer map.

Leaflet Marketcluster promises to solve this problem:

  All Leaflet maps will now be using clustering out of the box.


How to make an "Add more logins" similar to Stackoverflow? I am using OpenID Selector module to integrate OpenID logins to my website; the same service used by Stackoverflow for login/registration. However, how can I add an option to "Add more logins" like Stackoverflow? I am open to suggestions also.

The idea is to prevent duplicate users. I am using D7.

See attached image.

Also kind of tweaks are welcome.

So the default assumption most Drupal modules make with authentication is that they will replace the current login setup with their own.

This approach is described well in http://drupal.org/node/114774#dist-auth and can be seen in how the current openid module provided in Drupal core works.

If I understand your question correctly you want to provide a way for people to authenticate from multiple different sources and have those enabled sources show up under their user profile. I don't think there is a module that does this yet, as most of the auth modules operate in their own little bubble as described above.

After a quick look at OpenID Selector you aren't going to get a lot of mileage from there, its mainly implementing and configuring the jquery library. You are going to need to write this from scratch.

The main pieces of your module will be:

A database table that maintains the logins associated to a given
user.
Some kind of form_alter scheme for the login page to show
all of the available login options the site owner has specified
(this will replace what the individual modules currently do)
An admin page for the site owner to select from available options.

Each one of those login options will probably be provided by a separate contrib module, so you might have to alter your logic for the specifics you find in the implementation from those modules.

To me its an ambitious undertaking for a configurable module that you plan to release, but if you go the quick and dirty highly customized / hard coded route for a single site it shouldn't take you too long.

Other places to look for inspiration on how auth modules operate in Drupal and possible sources you might want to include are FBOauth and Twitter.


Custom submit button callback overrides default callback? I am trying to accomplish the following functionality:

I have a profile2 registration form to which I have added a custom form element (just a submit button) using hook_form_alter().

The submit button has a #submit property set to a custom_callback function.

For debugging purposes, the callback function just displays a

drupal_set_message('hello world');

The general idea is that the button is used to gather information from a webservice (in the callback function) and then fill the form with the returned values.

The user can then check the values and submit the user registration form.

When I click the custom submit button, it fires the custom callback. But when I click the user register form submit button, it also fires the custom callback?

I have checked the dpm of $form and the #submit properties are as follows:

$form['#submit'][0] == de default (correct) user registration callback
$form['custom']['#submit'][0] == de custom submit handler

So, any clues on why the default submit handler no longer works?

EDIT:

My form alter implementation looks like this (just add an image button)

   $form['custom'] = array(
    '#name' => 'custom',
    '#type' => 'image_button',
    '#src' => drupal_get_path('module', 'custom') . '/logo.png',
    '#value' => t('get data'),
    '#prefix' => '
',
    '#attributes' => array('alt' => t('get data')),
    '#suffix' => '
',
    //'#weight' => -99,
    '#submit' => array('custom_callback'),
  );

Thanks in advance!

Problem seems to be custom form element. Change it to :

$form['custom'] = array(
    '#name' => 'custom',
    '#type' => 'submit',
    '#value' => t('get data'),
    '#prefix' => '
',
    '#attributes' => array('alt' => t('get data')),
    '#suffix' => '
',
    '#submit' => array('custom_callback'),
  );


How do I disable a module for the First Sidebar? I enabled the captcha when someone wants to post a comment, but it's also there when you try to connect to the site...

I don't know how to keep the module enable for the comments but not for the sign-in area.

Thank you for the help !!

On the Captcha configuration page (admin/config/people/captcha) you can set which forms should display a Captcha.

By default, all user forms get a Captcha challenge. Set them to "No challenge", add the form ID of your comment form to the list and choose the challenge you want.


Getting a translated country name from an address field I have an address field from which I'm getting a country code and then, using the address.country_repository service, checking the country's name.

$full_country_list = \Drupal::service('address.country_repository')->getList();
$country_code = $user->field_nationality->first()->get("country_code")->getValue();
$result['nationality'] = t($full_country_list[$country_code], [], ['langcode'=>$user->get('langcode')->value]);

This repository returns a list with the country names translated in Drupal's default language (in my case, portuguese), but I'm trying to t()-function it to translate the string into other languages.

The t() function doesn't cut it, even if I pass the langcode option.

How can I get a translated version of the list so that I don't have to translate the string with t()?

The country name in the country list is already a translatable markup object. It's not possible to add new options to it. So your idea to translate the country name again, this time with a specific langcode in options, is right. But you have to get the untranslated string if you want to translate it again

t($full_country_list[$country_code]->getUntranslatedString(), [], ['langcode' => 'de'])

because how you do it you get the translated string when running the code in a non english language context and translating from a non english language is not supported.

Edit: this answer is valid for the core country list

$full_country_list = \Drupal::service('country_manager')->getList();

there are probably other versions in contrib, see comment from @Berdir.


Render node author profile image in node template I am working on customization Node template file in Drupal 8, I added another field to user in admin/config/people/accounts/fields ( my field is field_bio). Now I want to render author image( with specified image style) and field_bio in node template`.

How can I achieve this?

If you like to do this in ui with one line of code:

1) add a view mode for user and name it "nodeview":

  /admin/structure/display-modes/view/add/user

2) activate the new view mode "nodeview" at the bottom of this page in "Custom Display Settings", then you get a new tab for the view mode "nodeview". Configure which fields are displayed and how they are formatted:

  /admin/config/people/accounts/display

3) Use the new view mode to render the author of the node in node preprocess:

$variables['author'] = \Drupal::entityTypeManager()->getViewBuilder('user')->view($variables['node']->getOwner(), 'nodeview');

4) Put the variable in twig

{{ author }}

This method allows full customization in ui and it is fast, because the rendered author gets cached and will be reused in every node referenced.


Creating node and user with one form I have a content type, 'A'.
Now I need a form with the user registration form fields plus the 'A' creation form fields.
So when the user (annonymous) submits this form, a user and a node of type 'A' with the filled information would be created.

I have this for now:

function my_module_menu() {
  $items['create_node_and_user'] = array(
    'page callback' => 'user_and_node_creation_form',
    'type' => MENU_CALLBACK,
    'access callback' => TRUE,
  );

  return $items;
}

function user_and_node_creation_form() {
  module_load_include('inc', 'node', 'node.pages');
  $output = array();
  $output['user'] = drupal_get_form('user_register_form');
  $output['node_type_a'] = node_add('node_type_a');

  return $output;
}

The form is displayed fine, but How can I add a submit handler to manage the node creation after register the user?

The Create & Register module does this for you if you don't mind using a contrib module. From the project page...

  This module creates a "lazy registration" which means that the user
  creates the content first and after this logs in or registers to the
  site.

  Process

  anonymous user creates a content
  the user will be redirected to the login page (if you set it on the settings form) after he finished the node creation
  the user registers or logs in
  the created node(s) will be assigned to the user after logging in


Dynamic view filter value I'd like the ability to change a View's filter value prior to rendering, specifically add a taxonomy filter to certain pages. The reason I need this, is to have one Views block, and the ability to filter based off the URI, without adding a contextual taxonomy id to the URI. I haven't been able to find a way to handle this in any hook, but I think that's where I should be looking. I've been using the MODULE_views_pre_view hook without any luck.

Right now, the only way I've gotten around this is to duplicate the Block over and over again, and it's starting to get messy.

I've found several articles, but they're all for Drupal 7.

I've figured out the problem after lots of guessing. You'll need to use a contextual filter and use the hook_views_pre_view hook in a custom module to alter the $args variable.

function MODULENAME_views_pre_view($view, $display_id, &$args) {
    if ($view->id() === 'view_machine_name') {
        $args[0] = 'your value';
    }
}


Multi stock locaton data storage I am working on a new module that will store stock levels in multiple inventory locations. What is the "best" way to store the data? I am slow to just attach and array of key/values to the product object and think I should use an entity instance for each warehouse. A few things that might effect what "best" is:

need to be conflict free with existing commerce simple stock module
need to be able to show individual stock locations via Field UI using conditional fields or Rules.
need to be able to iterate through all of the stock location
Each stock will have name, stock value, and a few other properties such as geo location
List item would like to use field group to displace the multiple values with existing formatters and widgets.
Commerce uses inline entity fields that might be good pattern to use
I intend to be a Commerce Stock submodule and would like to leverage as much Commerce Stock functionality as possible.

I am dealing with the same question here for a 2 location store, one in the US and the other in EU.
Because i also don't want to interfere with functionalities and UX of present stock validation and control modules, my thought went also to manage inventory levels in separate entities.
I have this workflow/checkout in mind :
- product nodes show the availibity of a product(variation) based on total stock of all inventories
- after entering delivery address in checkout, shipping rates will be calculated from both inventory locations
- customer will be presented a default inventory based on rate, estimated delivery time and last but not least stock level for the chosen products in that inventory.

The matter of splitting up the order comes in mind with this solution if product a is only available in EU inventory and product b only in US inventory, or when ordered quantity of product c needs to be shipped from 2 inventories.

So before thinking about setting up a multiple stock location solution, you should think about it's consequences to the workflow, especially in checkout and feasible splitting of shipping arrangements and related dues.

If you came up with something already, let me know.
Hope my feedback helped you making the right choices.


where does the drupal6 cck field default value stored in database? Is there a way to get the default value in a cck field (in drupal 6)?When I set the default value,the nodes created after that, are having this default value.(in database also ,table name is content_type_contenttypemachine).

Initially I set the default value as '1000' and later changed it to "4000" but when am trying to get the value from the content type table its retrieving the first value as "1000" and not the recent value "4000".

Is fetching the last record is the only way to get the latest default value I have set?

Thanks in advance,
cheers.

No need to go directly into the database for that, you can use the content_field_instance_read() function:

module_load_include('inc', 'content', 'includes/content.crud');
$definition = content_field_instance_read(array('field_name' => 'field_foo'));

// Your mileage may vary here, inspect $definition[0]['widget'] to see what you've got available.
$default = $definition[0]['widget']['default_value'][0]['value'];

If you're dead set on going into the database, the info is stored as a serialised PHP string in the widget_settings column of the content_node_field_instance table.


How to configure fivestar's star set in Drupal 7? The FiveStar module says the star set is configurable, but where can one select the star set in Drupal 7? I have searched, but could not find the proper page. (I am still new to Drupal).

Having used FiveStar with Drupal 6 and knowing where the configuration is I've had a look at FiveStar on D7 and I would suggest that because it is still Alpha the team hasn't got to moving the new features across yet as I could not find the required config either.

EDIT: I tell a lie. You can configure the star set, and as an improvement you can do it per fivestar field (i.e. you could have two ratings against a node that have different star sets). To do this go to "Manage Display" of the content type that contains your fivestar field. At the right of the field there will be a "gear" icon. Clicking on this will bring up options including the star set to use.


Formatting numbers in D7 I have a serialized object in a field. I now need to output a float-value. Since the site has 2 languages (german/english) I now need to format the float-number based on the current language.

$value = 123456789.01;
// Language = english
print the_format_function($value); # => 123456789.01

// Lanuage = german
print the_format_function($value); # => 123.345.789,01

I'm lookin for the_format_funtion();.

There is a format_number API module, which may eventually handle this for you. And possibly will make it into D8.

For the moment I think the function you are looking for is number_format()