Can I use Plain PHP functions in tpl file?

For the first part of question:

You may output as form item the output of your custom function, where contain logic to get random image:

function MY_MODULE_form_alter(&$form, &$form_state, $form_id) {
    if ($form_id == 'user_login') {
        $form['img_item'] = array(
          '#type' => 'markup',
          '#markup' => my_random_image_output(),
          '#weight' => -50
        );
    }
}

function my_random_image_output() {
    $output = '';

    // your custom logic to output one image $output = '<img src=".... />'

    return $output;
}


Is there a nicer way of getting my nodes language and text direction?

If $node is the variable containing the node object, you can use code similar to the following one:

$languages = language_list();
if (isset($languages[$node->language])) {
  $rtl = $languages[$node->language]->direction == LANGUAGE_RTL;
  // $direction = $languages[$node->language]->direction ? 'rtl' : 'ltr';
}

If you need to use the string "rtl" or "ltr" basing on the direction associated with the language, then you can use $direction, instead of $rtl.


Does hitting 'recreate' recreate the feature from the site's elements, or vice versa?

When you recreate a feature via the UI (admin/config/development/features/) or even by using drush (drush fua -y or drush fu feature_name -y) all your configuration changes regarding nodes, modules, blocks, themes etc are being extracted to the corresponding feature directory. Configurations from different modules are saved to different files. In order to apply your changes to another Drupal instance you have to do it the other way around drush fra -y or drush fr feature_name -y and your changes will be stored to the database.

In case that you want to revert some settings back to their initial state, before you move them to another Drupal instance you can do the following: edit and save the appropriate file that you want to revert and then use drush to apply the changes from your files to the database. Thus you'll have your site back to its former state.


How to make block title words themable in D6

Quick and dirty in your block.tpl.php:

<?php
  if ($block->subject=='Sign up for mail') {
    $block->subject='Sign up for mail';
  }
?>

And in your .css file:

.blue {
   color: blue;
}

.red {
    color: red;
}


How to set multiple arguments for views contextual filters from twig

To pass contextual filters with OR logic, you can make use of the Views Contextual Filters OR module:

  The module provides a views plugin to modify query of contextual filters.
  The module can changes contextual filters condition to OR logic.

When you install and enable the module from Query settings in your display check Contextual filters OR option and save:

Than in your twig:

{{ drupal_view('our_services', 'services', countryTermId, globalId ) }}


How to set permissions of creating content only for referenced users

If you are using the Node Reference URL Widget to add the create link then you could use panels (with the built in context) to hide that link if the user is not referenced on that node. This would not stop people from going to the url directly but would keep the honest people from creating content on nodes that they are not referenced on.

If you need a more secure way to prevent the creation of the document nodes I assume you would need to write some code or do some rules magic.

Rules magic idea: Create a flag that is hidden like I mentioned above. When the node is flagged then if the user reference is the current user then create the node and go to the edit page(and unflag when done). If not then unflag and show a message.


How to import url of the nodes via feeds

IIRC because the link field is multiple fields (title, link, description, etc.) you need to map it to the correct one, from quick google searching it seems the Link module dev version has a migrate file in it for this.


Customise Title Mark Up from template.php

I found the solution to this

Create a field called Title
Your users use this new field to
    enter a title
Use Auto Node Title  to automatically title
    the node based on this field.

You can ow hide the original title in your theme and use the new title filed instead. The new title field can be customised like a regular field.


How to show message to user when page is in a filtered state?

In views, to remember the user entry, Views uses sessions. It uses different variables for each view. If you print the $_SESSION variable you can see that.

function MODULENAME_form_alter(&$form, &$form_state, $form_id) {
  if ($form['#id'] == 'views-exposed-form-test-page'){ //your exposed form's id

      print_r($_SESSION);
   }
}

Now you can see that a structure like below

[views] =&gt; Array
    (
        [test] =&gt; Array
            (
                [default] =&gt; Array
                    (
                        [title] =&gt; Page
                    )

            )

    )

So if you check value exists for this variable,  you can perform your task

ie:

if ($form['#id'] == 'views-exposed-form-test-page'){
//check is it exists, if so perform your task
 if($_SESSION['views']['test']['default']['title'] != ''){
    // "need to reset";
          //here using jquery or css, show or hide your message
        $script="(function ($) {
                //action to do here
        })(jQuery);";
        drupal_add_js($script,'inline');
 }
}

Hope this may helps you


First thing is that you should log out of your facebook account and then try the same.

It would surely work fine.


In general Drush can't corrupt your database, as it's a software which just sends the SQL queries.

However this error can be related to newer version of MySQL, as of 5.5.7, InnoDB always uses the fast truncation technique (which is equivalent to DROP TABLE and CREATE TABLE). So it no longer performs a row-by-row delete for tables with parent-child foreign key relationships, therefore TRUNCATE TABLE returns an error for such tables.

See: 2.11.1.1 Changes Affecting Upgrades to 5.5

This already has been reported in #2229013 for Drupal core.

So you should either:

consider using different data structures:

non-InnoDB,
use redis/memcached for your cache management (so this won't happen),

try clearing your caches in different way, e.g.

echo "SHOW TABLES LIKE 'cache%'" | drush sqlc --extra=--skip-column-names | xargs -L1 -I% echo "DELETE FROM %;" | drush sqlc --extra=-v

upgrade your Drupal to 8 and see if the same happens (drush cr),
use different database (maybe will work in MariaDB?),
downgrade your MySQL to <5.5.7,
patch the Drupal core by replacing TRUNCATE with DELETE statement,

You may also consider the condition like if ($mysqlversion > 5.57 AND $cache_table_type = 'innodb') { // DELETE } else { // TRUNCATE }.
or wait until the fix is provided for Drupal core (#2229013).


How do I get a contextual filter argument in a template file?

You can get the contextual filter argument from the route match:

  $variables['arg_0'] = \Drupal::routeMatch()->getParameter('arg_0');

Usually the route parameters of contextual filters are named arg_0, arg_1 etc. If it doesn't work, check the route definition of this View page with Devel (/devel/routes) or Drupal Console.

Dependent on the Twig template you might need to add a cache context as well:

  $variables['#cache']['contexts'][] = 'route';


Convert an exported rule to a programmatic rule

You can implement hook_default_rules_configuration()

  This hook is invoked when rules configurations are loaded. The implementation should be placed into the file MODULENAME.rules_defaults.inc, which gets automatically included when the hook is invoked.

and use entity_import() to convert the export string into something Rules will understand. e.g.

function MYMODULE_default_rules_configuration() {
  $items['my_rule'] = entity_import('rules_config', 'EXPORT STRING HERE');

  return $items;
}


Ok figured it out.

$options = [
    'dialogClass' => 'my-form',
    'buttons' => [
        'button1' => [
            'text' => 'Proceed',
            'id' => 'onClickDoSomething',
        ]
    ]
];

And then in the .js file just write a function which fires when clickcing on a selector with the id onClickDoSomething voila, it's working.


How to filter a View by Year and Month with Summaries for each one

You can override the parameters in each individual display.
I'm not sure about D8, but in D7, the "display order" of the displays was important as well, such that you'd get the behavior of the higher priority display (lower display order) as desired. In D7, I had to go into the database itself, and change the "position" of these pages in the "views_display" table. (I know of no way to do this in the UI.)


Drupal-git-sandbox project: commits are shown but no new revision

Sandboxes on Drupal.org can't have releases (tagged revisions).

For a full project, if you want to push a specific release/revision, rather than just a SHA-identified commit, you create a tag locally before you push a tagged release.

git commit -am "Revision 7.x-1.0"
git tag 7.x-1.0
git push origin tag 7.x-1.0


Drupal Calendar highlight all days in block with views

This is a theming issue.  Inspect the classes of the boxes in the calendar, you will probably find .current-month or something similar in there for the boxes in the month being shown.  Then edit your theme's CSS (or SASS) with:

.current-month{
  background-color: [color-you-desire];
}


Drupal 8 - "Level up" link in taxonomy term view

Personally I would just write a custom code:

You will need to define a custom block
And you will also need to get the parameter from the URL.
You will need the "database" service (select) in your code, to query the parent term (if there is any).


How to disable edit their own profile per role?

There is one module called "UserProtect" module. With this module you can hide edit account, edit password, email from based on user roles and for specific users too.

You can set permission by going /admin/people/permissions where you can see User protect and you can configure it /admin/config/people/userprotect here

Protected Roles

User Protect Module Permission

For example, I don't want to give permission to my Test One and Test Two Users for edit their profile. So, I wanted to hide it from "Test One" and "Test Two".

Hope this helps!


The Facebook Autopost module "user hasn't authorized the application"

This happens when you add any user to roles section and if the user haven't accepted the role and you are trying to post something on his behalf. first accept the role in developers page of Facebook.


Drupal commerce get quantity per sku in hook_commerce_checkout_complete

You need to wrap the $order object before looping over the line items. It also removes the need to wrap the line items explicitly.

$order_wrapper = entity_metadata_wrapper('commerce_order', $order);
foreach ( $order_wrapper->commerce_line_items as $line_item_wrapper ) {
  if ($line_item_wrapper->commerce_product->sku->value() == 'some-SKU') {
    // increment quantity counter, award points etc.
  }
}


Adding a Image Upload Button in CKEditor

Check out IMCE with IMCE WYSIWYG bridge.

Once you install and configure those two modules, select "IMCE" as a button in CKEditor and then you can upload and insert images in WYSIWYG.


How to get attributes of the form elements?

You can do it like this:

function my_form_validate(OR_SUBMIT)($form, &$form_state)
{
  $msg = '';
  foreach(element_children($form[FIELDSET_NAME]) as $key => $value) {
    $msg .= $form[FIELDSET_NAME][$value]['#title'] . ' ';
  }
}


After moving a new server, one of 2 Drupal sites, has no css loaded

This sometime happens if Apache server is not able to write files or directory.

Since you mentioned you moved using root user, Apache server may not be running on root user.

To further clarify this: If the inodes of both sites have the same permissions, ownership, grouping, but only one works, it's because it doesn't have CSS and JS aggregation on (a thing that requires an Apache user --- that is, www-data ownership and grouping, that you should apply).

You could either turn off CSS and JS aggregation for the non working site (and then it'll work), or make sure you give both sites such ownership and grouping if you want both of them to work properly with CSS JS aggeregation.

If at least for now you just want to turn off CSS JS aggregation, read here how to do so, but for troubleshooting this (and take care of the root cause), read the following (you might want to precede it with this piece of data on the aforementioned Apache user):

First check on which user apache server is running. Finding out what user Apache is running as?
Change your tmp folder and files folder ownership to that user so that it is writable by Apache.Giving ownership of the directory to the apache user?
Make sure you have tmp directory created in your files folder and is writable by Apache server. You can define it your Configuration > File System


Creating quicktabs prorgammatically: code worked in D6 not in d7

According to this comment on the hook_block() docs,

  Drupal 7 doesn't use anymore hook_block(), but it uses a set of new hooks; see Converting 6.x modules to 7.x for more details.


How can I create a block that shows the total items in my cart?

You can test this one -

Put below code in your page (create new page content) and select input format "php" and hit preview button you will get what you want (if cart is not empty).

<?php
        $items = uc_cart_get_contents();

        foreach($items as $item){
            while(list($key,$value) = each($item)){
                if($key == 'qty')$qty = $value;
                if($key == 'price')$price = $value;
            }
            $total_qty += $qty;
            $total_price += $qty*$price;
       }
       echo 'Total Quantity : '.$total_qty.' Total Price : '.uc_currency_format($total_price);
    ?>


Can you create a tpl based on view page url? (Drupal 7)

You can use Taxonomy Views Integrator module. Create separate views for this taxonomy term page and set it. And You can create separate template for this views.

Or You can use hook_preprocess_views_view for creating views template for custom view and custom view display. For ex.

     function THEMENAME_preprocess_views_view(&$variables) {
      $view = $variables['view'];
      if($view->name == 'your_view_name' && $view->current_display == 'main_page')
   {
        $variables['theme_hook_suggestions'][] = 'views_view__viewname';
      }

Your template will be views-view--viewname.tpl.php in this case


use devel module for better debugging option.Devel module provides dpm() which will make the array structure easy to see.When you know the exact array key where your content lies, its better to check the output with that key instead of dumping the complete vars.

so better you first do dpm(get_defined_vars());after installing devel module it will return the same what you are seeing now but in a well structure way, when you figure out the next better key of output holding the data,use dpm() on the returned array with useful key


Assigned block system to an invalid region

I can't explain why, but if somebody does the same by mistake and assigns a invalid region to the block. The following did the job for me.
Just delete the entire region and add the block to another region. Clearh the cache and afterwards setup the region you had before again and assign the block to it.


In Drupal 7 and 8 the add view row classes is check-marked by default.

The problem is that in Drupal 8, it does not work. (looks like this is a bug)

As you can see in the above picture, the number is missing on the div class.
Luckily, there is a workaround solution.
In FIELDS, add Global: View result counter and hide it from display
In FORMAT, click on Settings (the 1st one)
For row class, put for example: hello-{{ counter }} and uncheck-mark "add view row class", as you don't need it.

Result


First you need enable for create tpl name bean.tpl.php call for every bean type.

$conf['theme_debug'] = TRUE;

In this tpl you get $content variable . Please print_r($content) in tpl or install devel module to dmp($content). I suggested you install devel module. After that you can find your field collection

Load field collection like this

Thank you


I have deleted

"commerceguys/addressing": "1.x-dev",

and reran

composer update drupal/address --with-dependencies

and it works now. I had a unstable beta and commerceguys came out with a stable version that updated their code.


How do we replace the token  in a custom module?

As already mentioned, <front> is a route, not a token, so you can't use the token API to work with it.

You can resolve it using the Url class:

$path = \Drupal\Core\Url::fromRoute('<front>')->toString();

// $path is equal to '/'

But I'm not sure how useful that will be. Perhaps you want to get the front page that's set in config instead:

$path = \Drupal::config('system.site')->get('page.front');


The difference between hook_init() and hook_node_update()/hook_node_presave() is that the node is already in progress of being saved when either of the last hooks are invoked.

Notice how the argument to cust_node_update($node) in your non-working example is a $node object. In fact, it's a reference to the very node object about to be saved. This is important because only the data actually in that node object will be passed on to the database.

Your first line calls entity_metadata_wrapper() with the id of that node to create an object oriented wrapper around it. The problem here is that since you're only passing the id of the node, entity_metadata_wrapper() has no choice but to fetch a copy of that node from the database (or perhaps a cache, but that is irrelevant to the discussion). This newly fetched and wrapped node will be an entirely new object representing the same node, with no connection to the node reference passed to hook_node_update() or hook_node_presave(). Altering this new node object has no effect whatsoever on the node object already in progress of being saved. Both objects represent the same node data, but the one you fetched from the database and wrapped with an object oriented interface is a copy of the original node data.

Calling $node_wrapper->save(), node_save() or entity_save() inside hook_node_update() or hook_node_presave() is a bad idea because it tells Drupal to save the node already in progress of being saved, which would again invoke those hooks - but this time with a reference to the node object you fetched from the database. Your hook implementation will then again fetch a new object representing the same node from the database, before it has actually been updated, wrap it in an object and try to save it. Endless recursion is a fact and you're likely to suffer the White Screen of Death.

So, how do we fix this?

Jupiter's answer is on the right track, but it also works with hook_node_update() if that's what you want to use.
Calling entity_metadata_wrapper() and passing in the entire node to be wrapped will let the wrapper reference and alter the actual node object instance you pass in - containing all the latest information - instead of loading a copy from the database.

Calling $node_wrapper->save() would still trigger a recursion (this time without creating node copies), but you don't need to care about actually saving things because you're acting on the node reference passed to the hook implementation, which is the very same object Drupal will store in the database once the hook implementation has returned and a few extra tasks have been performed.

There's at least one gotcha when using entity_metadata_wrapper() in these hooks though, depending on whether other modules use the same hooks - or one invoked later than the one you implemented - to reorganize the node structure into a form that can be saved to the database more easily. The node may, in other words, be structured differently compared to when it's loaded using node_load() or entity_load(), depending on which modules you use. The easiest way to find out the structure of the node being saved is to use Devel module's dpm($node, 'node to be saved'); and inspect the structure before actually attempting to modify it.


How can I automatically assign users to a node based on a taxonomy?

I would do something like this:

RFP question is a custom content type.
RFP question includes a term reference/entity reference to a taxonomy vocabulary called Category.
Category has an entity reference field (to users) called SME.  This way, each term can be assigned to a user.  If you do it this way, you also don't need to worry about updating existing nodes when the SME changes; you can simply update the term entry in the vocabulary Category once, and all relevant nodes will be changed.
With this config, the SME won't be visible on the node, just the category.  You can fix this by creating a block in Views and adding it to the node page.
You can use Flag with Rules to automatically notify by email the user marked as SME when a node is flagged for updating.


Is there a way to load the current entity object?

I think menu_get_object() might be helpful:

  menu_get_object() provides access to objects loaded by the current router item. For example, on the page node/%node, the router loads the %node object, and calling menu_get_object() will return that. Normally, it is necessary to specify the type of object referenced, however node is the default. The following example tests to see whether the node being displayed is of the "story" content type:

<?php
$node = menu_get_object();
$story = $node->type == 'story';
?>

You can use this with any router-loaded object so it stands to reason that on entity pages (including taxonomy term pages) that this would get you the correct object:

$entity = menu_get_object($entity_type);

UPDATE

On further inspection you still have to pass the position of the ID in the URL as a parameter to menu_get_object() so it's pretty much the same as using arg(), but it's arguably a bit cleaner. For taxonomy terms the path is taxonomy/term/% so you would call:

$term = menu_get_object('taxonomy_term', 2);

It's worth bearing in mind that entity_load will only incur a database call if the entity hasn't previously been loaded in the current page request. If it's already been loaded, it will be served from the static cache.

UPDATE 2

Just to add an example of the static pattern to avoid reloading the entity over and over again if you're getting memory errors:

$loaded_entity = &drupal_static(__FUNCTION__, NULL);
if (!$loaded_entity) {
  $loaded_entity = menu_get_object();
}
return $loaded_entity;


Image files aren't recognized when changing a html file to page.tpl.php

If your images (ie. your img directory) are in your theme directory, use something like <img src="<?php print base_path() . path_to_theme(); ?>/img/works/works-full8.jpg" /> to include them.

If they are in your sites/default/files directory, use .

If they are in your site root, use


Limit a View with a relationship to show only the first (by sort) relationship of each of the original entities

I believe your issue is a good example of needing additional meta information on your Product (Node) to do (simple) views searches. The approach you've take, by embedding the information into a Field of the node is typically difficult to use. I recommend 2 possible solutions:

This may not have a solution for you but I suggest looking at https://www.drupal.org/project/views_aggregator for complicated aggregated views.
Another option is that instead of using the field with nested values. To use something like the Relation module to store your heuristics (sales data). Relations be linked together to get information like you requested from your products.


Uploading an image with JSON:API; getting "Access denied"

I wasn't able to get it working with Flow 2 in the docs; I kept getting a Needs "administer users" permission error (which is incorrect; users have permission to edit the field).
So instead, I used Flow 1:
POST /jsonapi/node/article/{uuid}/field_image HTTP/1.1
Content-Type: application/octet-stream
Accept: application/vnd.api+json
Content-Disposition: file; filename="filename.jpg"

[… binary file data …]

This requires the user to already be created, which is OK for my user case, but may not be the case for everyone.
Additional notes

I had to turn off the popular Filefield Paths module for my image field because it breaks JSON:API.

I had to uncheck Alt field required in the image field settings; if you leave the alt field required, you get this nasty error:
  "detail": "The controller result claims to be providing relevant cache metadata, but leaked metadata was detected. Please ensure you are not rendering content too early. Returned object class: Drupal\\Core\\Cache\\CacheableResponse.",


First refer to the bootstrap documentation on modals http://getbootstrap.com/javascript/ to construct a working modal with the content you want. Use bootply or whatever to get it working the way you want.

You then have two options that come to mind: You could just create a standard block using the Drupal UI, place the markup in the body of the block, and configure the block to "display on every page except" ... <front>. Then assign the block to a region.

Alternatively, you can override tpl files in your subtheme and place the modal markup in those. You do this by placing a copy of the Bootstrap theme's page.tpl.php in your subtheme. First create a copy of it called page--front.tpl.php then add your modal markup to page.tpl.php.


"list" plugin does not exist after upgrading from Drupal 8.3.x to 8.4.2

This is solved now. I think that there was a mismatch between the PHP/ Drush / Drupal 8.4.3 versions.

This confused me so I include a table below of what is now working for me. I used it as a checklist to ensure that I had both a dev Drupal 8.3.7 and a dev Drupal 8.4.3 running in parallel.

Despite what the documentation says I think Drush 8.1.15 is not suitable for Drupal 8.4.3 and yes, there are some Drush 9.0.0-rc1 commands that don't work as expected  - like dumping SQL and redirecting SQL files to drush sqlc -  but it is workable.

Bits and pieces in each of existing and future Drupal

               iMac               MacBook
PHP VM         7.1.12             7.1.12
PHP Host       7.1.12             7.1.12
Drush VM       8.1.16-dev         ~9.0
Drush Host     8.1.15             ~9.0
Drupal Core    8.3.7              8.4.3
MySQL          5.7.20             5.7.20   (Required MySQL 5.5.3/MariaDB 5.5.20)


How to Determine view type (content, user taxonomy, etc)

If you are already editing the view, it is also in the Title (so you don't have to navigate away from editing).


I was finally able to resolve the problem. Just posting the solution in case it comes useful to anyone else.

As it turned out, the problem with Facebook share was display suite. The nodes that it was not working for were, of course, not random as it initially looked. They were the nodes which were using display suite. I didn't manage to find a solution to it and therefore I used the service links module (proposed by @Kenny Wyland), which had an extra feature covering the case that display suite is being used.


How to disable "publish" content for a particular role?

Just unchecked publish checkbox on content type setting page and hide this field with CSS if user has writer role or remove it programmatically on the same condition with hook_form_alter


Acquia Dev Desktop MySQL database troubleshooting on Mac OSX 10.11

Manually starting the MySQL server:

/Applications/DevDesktop/mysql/bin/mysqld --defaults-file=/Applications/DevDesktop/mysql/my.cnf

Viewing the log:

tail -50 /Applications/DevDesktop/mysql/data/mysql.err

If everything went right you should see the MySQL green dot in the Acquia Dev Desktop GUI.


A way to put a unique ID on a node based on the taxonomy it has?

This looks very possible with the Serial Field module in combination with Rules and Token modules

Serial Field module page reads:

  This module provides an auto-increment (serial) field.

  Unlike Drupal's built-in auto-increment node ID, which is global and
  shared by nodes belonging to all content types, serial fields are
  managed per content type (D6) / entity (D7). For example, the serial
  field of an Invoice instance will generate a unique sequential number
  (starting at 1, then 2, etc.) exclusively for Invoice instances.

  The allocation of serial numbers by this module is atomic. In other
  words, the serial values are unique even when multiple instances of
  the same content type / entity are created simultaneously.


Starting new 8.5 site is it safe to delete and reuse field_image field

Any field could be deleted and re-created per your preferences and it won't cause any problems in the future as Drupal 8 does not require fields of certain machine names to be of certain types only.


Drupal 7 EVA fields not rendered on unpublished nodes

Solved using the View Unpublished module. This is not related to EVA module but it is related to the drupal unpublished nodes built in user permissions


How do I display two different views for a single content?

You will need a module for your form in this content type, there is no other way. (unless you want something complicated within an iFrame).

Either write a custom module yourself, or use the usual Webform module


How to properly declare module settings with options list

Config schema doesn't know about allowed values. It's a about the structure of the stored configuration, not how it is displayed to the user.

It's up to you to implement the form for that, using e.g. a #type selection and #options.

For the config schema, it's type: boolean, not type checkbox. And type: integer, what you tried to use there doesn't exist.


How to access User Picture field for a comment in Views?

Add a relationship- Comments: User
Add a field- User: Picture (assign Relationship: User)


I know this is old but maybe it will help someone. I have found two possibilities, both with certain downsides.

Views merge rows module
does exactly what you need in terms of displaying results, however it messes up views pagination because it only changes the display of the query. But if you don't need pagination it's the way to go. Edit: I wrote a patch for the Views merge rows module to address the pagination issue. It now works perfectly.
Views Aggregation with concat function patch - if patching is an option - do it, then enable aggregation under Advanced in the view. Next step is to click on aggregation settings under the right field (in your case the 'contact' field) and set it to 'group concat'. This will aggregate the company and contact field and summarize the contact data as you specified.

Whereas this should work for the majority of use cases both solutions don't work for mine, that's why I created a new question here. Kind regards.


How to add a new calculated field by using `hook_views_query_alter`?

Turns out that I didn't need the hook at all. I was able to achieve the result by using a Math Expression within the views module


How to change text on Drupal WorldPay button?

In this specific case, you can implement hook_commerce_payment_method_info_alter(&$payment_methods) in a custom module, and alter $payment_methods['commerce_worldpay_bg']['title'].

If you see other instances of the strings, which aren't changed, then you can use the String Overrides module, as already suggested, or use the $conf global variable in settings.php as follows.

$conf['locale_custom_strings_en'][''] = array(
  'Payment via Worldpay' => 'Your string',
);

Keep in mind that the latter two methods change the string wherever it is used; they don't provide a context to understand where the string is being used. This could be something you want, or not.


How to re-write/rename HTML output of a View Block wrapper ID?

Go to you view select block display "Do's" then Advanced -> OTHER -> Machine Name change this and it''ll change the id of your block.


How to populate a select list in my custom module with the content types of the site?

I found some code in another module that did the same thing. That module had this code before that form option in the form function

$select = array();
$select[0] = '<' . t('none') . '>';
$nodetypes = node_type_get_types();
foreach ($nodetypes as $ntype => $nname) {
  $select[$ntype] = $nname->name;
}


I had the same problem.
Instead of "#limit_validation_error", adding validation handler which simply omits all the error works fine.
function my_module_form_alter(&$form, $form_state, $form_id) {
  $form['actions']['save_as_draft'] = [
    '#type' => 'submit',
    '#value' => t('Save as Draft'),
    '#submit' => ['::submitForm', '::save',],
    '#validate' => ['_my_module_clear_errors'],
  ];

  // Add this to avoid 'Entity validation was skipped' error.
  $form_state->setTemporaryValue('entity_validated', TRUE);
}

// Remove all errors.
function _my_module_clear_errors(&$form,FormStateInterface $form_state) {
  $form_state->clearErrors();
}

This comment was really helpful
https://www.drupal.org/project/workflow/issues/2859053#comment-12140370


How to automatically create a node for each user and set the user as author of the node?

Step 1

Use the Rules module to create a Rules Component, which includes whatever Rules Conditions you might need (if any), and with a Rules Action to Create an entity (of type node). Make sure to use a parameter (of type "integer"), and which you use as the value to be assigned for the "author" of the node to be created. Here is an example of such Rules Component (in Rules export format, if you have the Rules UI enabled you should be able to import it in your own site):

{ "rules_create_a_new_node" : {
    "LABEL" : "Create a new node",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : { "uid_of_author" : { "label" : "Uid of the user to be used as author", "type" : "integer" } },
    "IF" : [
      { "user_has_role" : {
          "account" : [ "site:current-user" ],
          "roles" : { "value" : { "3" : "3" } }
        }
      }
    ],
    "DO" : [
      { "entity_fetch" : {
          "USING" : { "type" : "user", "id" : [ "uid-of-author" ] },
          "PROVIDE" : { "entity_fetched" : { "user_fetched" : "Fetched user" } }
        }
      },
      { "entity_create" : {
          "USING" : {
            "type" : "node",
            "param_type" : "page",
            "param_title" : "Node created for user [user-fetched:name]",
            "param_author" : [ "user-fetched" ]
          },
          "PROVIDE" : { "entity_created" : { "node_created" : "Created node" } }
        }
      },
      { "drupal_message" : { "message" : "Node creation completed for user with name \u0022[user-fetched:name]\u0022." } }
    ]
  }
}

Some details about the above Rules Component:

It checks if the user using it, has role "admin" (just to be secure it a bit, feel free to omit that if you don't want that).
It fetched the info about the user for which the uid was entered as a parameter.
It creates a node of type (machine name) page (adapt that to whatever machine name fits for you).
It shows a Drupal message to confirm the node got created (just for testing, remove it if you don't need it anymore).

After you imported the above Rules component, use the "execute" link in front of this Rules Component to QA-test your component (for which you'll need to enter an appropriate uid value for the author you want). After it completes, it'll show an informational Drupal message similar to this one (with Demo.User = the name of the user for which I entered the uid):

  Node creation completed for user with name "Demo.User".

Step 2

Create a view of the group of users for which those nodes should be created. Then transform that view into a view that uses Views Bulk Operations, and use the technique documented in "How to use Rules to create a custom bulk operation for a VBO view?". In doing so, you'll then be able to use the Rules Component from Step 1. Make sure one of the fields (columns) in your VBO view is the uid for each of the (50) users for which you want to create such node.

Tutorial

To get the idea, have a look at the video about Using Rules components with VBO" which uses a Rules Component with (only) 1 parameter. If you want even more, then also watch the subsequent "Using Rules components with more than one parameter" video.

Attention: to process like 100.000 entities at once is quite a challenge (memory requirements, etc). Therefor you might want to also watch the video about "More details about VBO settings" ... Before you are tempted to use VBO for processing them all at once ...

PS: no need for custom code ...


How to change the referenced entity field value?

You have to add a Condition to the rule of the class:
"Entity has field", and then a whole bunch of the referenced fields of the entity will appear.


Can custom module function names contain characters between 7F and FF?

That's a bad idea. Please refer to Drupals Coding Standards under the section Naming Conventions.

In my opinion function/class/var names shouldn't contain anything else than A-Za-z0-9_.

If you don't want isys_helper_form_alter to be picked up by Drupal, you can always prefix it with an underscore: _isys_helper_form_alter.

Update

Here's another topic on why other characters are bad: https://stackoverflow.com/questions/6362241/php-variable-function-class-names-using-special-characters. And even if you remember to save it in the right encoding, other people who needs to maintain your code later on might not do that.


How to change a CCK value from a custom module

With the nid stored in $nid and changing FIELD_NAME to your specific field name, once you have your new field info back from your form nicely stored in $new_info all you need to do is:

$node=node_load($nid);

$node->FIELD_NAME[0]['value']=$new_info;

node_save($node);

This is assuming a couple things, one that it's the first value in a field, the [0] up there, and that the field is one that has a ['value'] component.  Other types of fields have different things here, the most common that immediately comes to mind is ['nid'] if it's a reference field.


Does [Cache blocks] in Performance means that blocks generated by Views are also cached?

In D6 views caching you have two kinds of options

Cache your query results -- Length of time your raw query results should be cached
Rendered Output -- Rendered HTML Output to be cached

In Block Cache in Performance settings

Block Rendered HTML Output to be cached which will be same as view setting.

For best performance you should use Views Caching option since it provides query level caching as well as rendered output caching.


Display Suite Extra Fields not showing in content page

I would try adding a class key, for example:

class: '\Drupal\ds\Plugin\DsLayout'

Also, I think you should update the template line, replace the underscore with a hyphen (and do the same for the actual twig file), for example:

template: templates/custom-article


Warning: array_flip(): Can only flip STRING and INTEGER values!

I had a similar issue, you just have to be sure it is an integer and not a string, also you can use entity_load_single:

if (!empty($item_id)){
$item_id = (int) $item_id;
  $split_pay = commerce_funds_object_to_array(entity_load_single('field_collection_item', $item_id));
}


How do I get inline tags to wrap nicely?

Try using display: inline-block instead. It gives you the functionality of an inline element, but you can apply margins and padding to it just like a block-level element.


It turns out the problem was that the views were content panes and I hadn't enabled content panes in the CTools module. As soon as I turned that on they worked fine again.


custom form module not showing upload functionality

Try to clear all cache of your Drupal website and try to access your url: http://wwww.your_domain.com/formtest


how to assign first img linked on a node to image field

I would write a module that read the field_data_body table in database. This table contains a field called body_value where the values are stored. If the module find a  mark, you can get the "src" attributte.

You don't forget to make a comparison in field_revision_body table to avoid problems.

Once you have the path of the file, you must save it as managed file in database. For this, take a look to "file.inc".

Here a little summary for last changes in D7.

I think it's important that you understand the difference between managed files and unmanaged files. Once you have saved the file, you could load the node, and assign to the field_image field, then node_save().


Allow Role to change only Moderation State of Content Type without possibility to edit content fields

how do I allow a user in a role to edit only 1 field and block the rest?

The standard solution is the Field Permissions module:

  The Field Permissions module allows site administrators to set field-level permissions to edit, view and create fields on any entity.

It provides you with a role-based UI like so:


Views Filters: find nodes that have more than one term in taxonomy vocabulary

In order to list down only those nodes of a specific content type that has more than one taxonomy term, I did the following and could only see nodes with more than one taxonomy term:

Create content type with taxonomy term field
Create views with following filter criterias

A. Published=Yes

B. Content Type={Your Content type}

C. taxonomy term field:delta (= 1)

For "C" I have clicked on Add filter criteria, then searched for the (content type's) field that contains taxonomy term and selected the one that has :delta (i.e. my field name is field_taxonomy_term and I choose field_taxonomy_term:delta), Once you selected the delta of your taxonomy term field then choose the operator as is equal to and provide the value as 1 and save.

If a content type has exactly one taxonomy term then the delta field will never have index 1 but, will always have index 0. If a node has more than one taxonomy term (i.e. 2) then there is index 1 (Index 1 is always present for content types with more than one taxonomy term), that is why the filtering works.

See the screenshots for more info:

The page is configured to show only nodes with more than one taxonomy temr

The following attachment is configured to show all nodes (it is then attached to the page)

The result of the above page and attachment is as follow

In case you are interested in the view, here is the export code:

$view = new view();
$view->name = 'viewfornodewithtaxonomy';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'node';
$view->human_name = 'ViewForNodeWithTaxonomy';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'Attachment display all nodes with any taxonomy terms';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '20';
$handler->display->display_options['pager']['options']['offset'] = '0';
$handler->display->display_options['pager']['options']['id'] = '0';
$handler->display->display_options['pager']['options']['quantity'] = '9';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'fields';
/* Field: Content: Title */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'node';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['label'] = '';
$handler->display->display_options['fields']['title']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['title']['alter']['ellipsis'] = FALSE;
/* Field: Content: taxonomy terms */
$handler->display->display_options['fields']['field_taxonomy_terms']['id'] = 'field_taxonomy_terms';
$handler->display->display_options['fields']['field_taxonomy_terms']['table'] = 'field_data_field_taxonomy_terms';
$handler->display->display_options['fields']['field_taxonomy_terms']['field'] = 'field_taxonomy_terms';
$handler->display->display_options['fields']['field_taxonomy_terms']['delta_offset'] = '0';
/* Sort criterion: Content: Post date */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'node';
$handler->display->display_options['sorts']['created']['field'] = 'created';
$handler->display->display_options['sorts']['created']['order'] = 'DESC';
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'node';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = 1;
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;
/* Filter criterion: Content: Type */
$handler->display->display_options['filters']['type']['id'] = 'type';
$handler->display->display_options['filters']['type']['table'] = 'node';
$handler->display->display_options['filters']['type']['field'] = 'type';
$handler->display->display_options['filters']['type']['value'] = array(
  'nodewithtaxonomy' => 'nodewithtaxonomy',
);
$handler->display->display_options['filters']['type']['group'] = 1;
/* Filter criterion: Content: taxonomy terms (field_taxonomy_terms:delta) */
$handler->display->display_options['filters']['delta']['id'] = 'delta';
$handler->display->display_options['filters']['delta']['table'] = 'field_data_field_taxonomy_terms';
$handler->display->display_options['filters']['delta']['field'] = 'delta';
$handler->display->display_options['filters']['delta']['value']['value'] = '1';

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['defaults']['title'] = FALSE;
$handler->display->display_options['title'] = 'page display node with at least one taxonomy term';
$handler->display->display_options['path'] = 'viewfornodewithtaxonomy';

/* Display: Attachment */
$handler = $view->new_display('attachment', 'Attachment', 'attachment_1');
$handler->display->display_options['pager']['type'] = 'some';
$handler->display->display_options['defaults']['filter_groups'] = FALSE;
$handler->display->display_options['defaults']['filters'] = FALSE;
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'node';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = 1;
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;
/* Filter criterion: Content: Type */
$handler->display->display_options['filters']['type']['id'] = 'type';
$handler->display->display_options['filters']['type']['table'] = 'node';
$handler->display->display_options['filters']['type']['field'] = 'type';
$handler->display->display_options['filters']['type']['value'] = array(
  'nodewithtaxonomy' => 'nodewithtaxonomy',
);
$handler->display->display_options['filters']['type']['group'] = 1;
$handler->display->display_options['displays'] = array(
  'page' => 'page',
  'default' => 0,
);
$handler->display->display_options['attachment_position'] = 'after';

Don't forget to mark your question as resolved if the answer helped you.


Migrating dates in the same timezone: convert arguments to subfields?

You can use it like:

$this->addFieldMapping('dest_date:timezone')
->defaultValue('America/Chicago');


How do I append a unique menu ID to the menu?

You can use the menu attributes module to add custom classes, id's, names etc... to any menu item in Drupal. Very handy module when you are looking to alter Drupal's menu system to create a custom look.


Why do site visitors end up with two sessions after logging in?

User always have one session at a time. Every time he logs in or out, new session is created.

Drupal 6 does not clean session table. I don't know if it is supposed to or not, but both my experience and simple Google search reveals it fails to do it.

So you have current session of an logged-in user, and outdated session data he left behind when he stopped to be anonymous.

If this really bothers you, consider moving sessions to APC or Memcached, it's much faster than database way, and unused data will be purged by the storage system even if Drupal will not trigger cleanup.

  The user is redirected back to the homepage and is presented the login form again and is not logged in. Ironically, the user's name appears in the footer of the homepage as a logged in user.

This behaviour I experienced only once - when database was misconfigured, and it reported inserts to session table as successful, but next request failed to read freshly inserted data. Apparently it was database caching, but unable to fix it, we ended up with sessions in RAM, as noted above.


Weird permissions problems for sites/default/files

I managed to figure this out with the help of the company providing the hosting. So, I'm sharing the solution, in case others have similar issues.

The solution is to make PHP run as a "FastCGI application", instead of an "Apache module". This way, Drupal uses the same user I use to upload files via FTP, when it creates files, etc.

The new website worked fine because I used the one-click installer offered by the hosting provider, which ran everything using the apache user. The old website did not do this.

This solution & problem should apply to all hosting providers using Plesk.


Change authoring information on multiple nodes

You may be able to use Views Bulk Operations (VBO).

  This module augments Views by allowing bulk operations to be executed on the displayed rows. It does so by showing a checkbox in front of each node, and adding a select box containing operations that can be applied. Drupal Core or Rules actions can be used.


Migration from a remote database PDOException

The problem with the code is the connection to the database. There aren't fields in the select.

SELECT FROM {Content} ct

To solve that one of the solutions is adding ->fields('ct'); to the database connection. This will select all the fields from the table ct:

SELECT ct.* FROM {Content} ct


How to automate the transfer of a registered user from Drupal to LimeSurvey?

I think you are looking for Rules. There you can check events like "After saving a new user account". And your action would be "Page redirect".


How to restrict file access based on file path under private directory?

Requests to files in the private file directory are routed through Drupal and access logic for these requests can be added by implementing hook_file_download.
The only argument to that hook implementation is $uri, which is the URI to the file. Using string comparison to see if you want to act upon this request should get you what you need.

Quoting the docs:

  If the user does not have permission to access the file, return -1. If the user has permission, return an array with the appropriate headers. If the file is not controlled by the current module, the return value should be NULL.


How to create an EMPTY anchor-only link with l()?

PHP typecasting pop quiz time! (Full disclosure: I didn't win in our office).

As pointed out already, this is the code in l() that we're concerned with:

if (isset($options['fragment']) && $options['fragment'] !== '') {
  $options['fragment'] = '#' . $options['fragment'];
}

So here's the question: What value casts to an empty string but passes the following?

(isset($var) && $var !== '')

The answer is: FALSE!

So, we could try this:

l(t('My link'), NULL, array('fragment' => FALSE));

Which gives us:

My link

Thankfully we can strip that leading slash by passing along external => TRUE:

l(t('My link'), NULL, array('external' => TRUE, 'fragment' => FALSE));

Which gives us:

My link

Boom. The things we do to avoid concatenating html strings manually, eh?

Postscript:

I'm not sure I'd actually recommend printing a link like this from php under normal circumstances. Without your javascript, all that link is going to do it jump your user to the top of the page (which, to my slight surprise, is specced behaviour). It should probably point somewhere that works without javascript.

If the link really only makes sense with javascript around (like the controls for a js-only slideshow or something), I think it's better to add the link to the page with javascript. Alternatively, if you really want to put it in your source, make sure it's display:none'd by default. Drupal has the .js class on the html for then showing it when javascript is around.


hook_theme_registry_alter() allows a module to step in to override registered theme callback functions. In your case, you're looking to override the menu_tree__main_menu entry and replace its callback function:

/**
 * Implements hook_theme_registry_alter().
 */
function MYMODULE_theme_registry_alter(&$theme_registry) {
  if ($theme_registry['menu_tree__main_menu']) {
    // @TODO: override
    // $theme_registry['menu_tree__main_menu']['function']
    // $theme_registry['menu_tree__main_menu']['type']
    // $theme_registry['menu_tree__main_menu']['theme path']
    // for your new module theme function
  }
}

See the Return Value section of hook_theme() for more information on what a theme registry entry contains.


Output block in particular region from custom module drupal 7

Why aren't you creating a standard block which returns your form? Currently you have a page callback (http://yoursite.com/campaign), and you are injecting this into a block ...

Here is some sample code that could help you further:

function client_block_info()
{
    $blocks = array();

    $blocks['client_campaign'] = array(
        'info' => t('Area for clients to manage their campaigns'),
        'title' => t('Campaign Manager'),
        'region' => 'content', // Your desired region, can be edited in administration screen
        'status' => 1,
    );

    return $blocks;
}

function client_block_view($delta = '')
{
    $block = array();

    switch ($delta) {
        case 'client_campaign' :
            $block['content'] = client_block_content();
            break;
    }

    return $block;
}

function client_block_content()
{
    return drupal_get_form('client_campaign');
}

function client_campaign($form, &$form_state)
{
    // Build your form

    return $form
}


How to theme the page template for search results

You can use a template, eg, page--search.tpl.php which would match the path to search and anything under it, eg, search/node/term, or you could create one called page--search-node.tpl.php which wouldn't match just the search page itself, but only search results from nodes, or you could use a template suggestion inside a preprocess_page() hook, eg, something like

mymoduleortheme_preprocess_page(&vars) {

  if (arg(0)=='search' && arg(1) && arg(2)) { // we are somewhere down in search/node/term or similar
    $vars['theme_hook_suggestions'][] = 'page_my_template_for_search_results';
  }
}

and then create a template file page-my-template-for-search-results.tpl.php.

In any case, http://drupal.org/node/1089656 has some great documentation on template suggestions in D7.


How do I programmatically update an existing submitted webform submission in Drupal?

Here's how to do that:

// Load the webform submissions file. The webform_get_submission() and
// webform_submission_update() functions are located here.
module_load_include('inc', 'webform', 'includes/webform.submissions');

// Load the node and submission.
$node = node_load(YOUR_NODE_ID);
$submission = webform_get_submission($node->nid, YOUR_SUBMISSION_ID);

// Change submission data.
//
// To see what's available, install Devel and run dpm($submission);
$submission->data[YOUR_FORM_ELEMENT_ID][0] = 'Update';

// Finally, update the submission.
webform_submission_update($node, $submission);

Documentation:

webform_get_submission()
webform_submission_update()


I got this to work like this:

function mymodule_process(&$variables, $hook) {
  if($hook == 'comment_wrapper') {
    $variables['content']['comment_form']['comment_body'][LANGUAGE_NONE][0]['format']['#post_render'][] = '_mymodule_post_render_fieldset';
  }
}

function _mymodule_post_render_fieldset($content, $element) {
  $your_legend = '$0<legend>Your comment legend</legend>'; // $0 is the full matched string
  return preg_replace('/<fieldset[^>]*>/', $your_legend, $content);
}

Care to give this a try?


Remove a contextual filter programmatically

To remove a contextual filters just set the $args to empty array or unset the desired arguments unset($args[0]) to remove the first argument an so on:
Here is an example to remove all contextual filters:

/**
 * Implements hook_views_pre_view().
 */
function MYMODULE_views_pre_view(&$view, &$display_id, &$args) {
  if ($view->name == 'some_view') {
    // Remove all filters.
    $args = [];
  }


Create a small custom module that implements hook_menu() and a custom callback that determines the latest poll and redirects the user.  Something like this perhaps (for D6, D7 will be similar):

Drupal 7

MYMODULE.info

name = "MYMODULE"
description = "Adds a menu item for the most recent poll"
core = 7.x

MYMODULE.module

<?php
/**
 * Implementation of hook_menu()
 */
function MYMODULE_menu() {
  $items = array();

  $items['poll/latest'] = array(
    'title' => 'Latest Poll',
    'page callback' => 'MYMODULE_find_poll',
    'access callback' => TRUE,
    'type' => MENU_NORMAL_ITEM,
  );

  return $items;
}

/**
 * Find latest poll and redirect user
 */
function MYMODULE_find_poll() {
  $nid = db_query('SELECT MAX(nid) AS nid FROM {node} WHERE type = :type', array(':type' => 'poll'))->fetchField();
  $latest = is_numeric($nid) ? 'node/' . $nid : '<front>';
  drupal_goto($latest);
}

Drupal 6

MYMODULE.info

name = "MYMODULE"
description = "Adds a menu item for the most recent poll"
core = 6.x

MYMODULE.module

<?php
/**
 * Implementation of hook_menu()
 */
function MYMODULE_menu() {
  $items = array();

  $items['poll/latest'] = array(
    'title' => 'Latest Poll',
    'page callback' => 'MYMODULE_find_poll',
    'access callback' => TRUE,
    'type' => MENU_NORMAL_ITEM,
  );

  return $items;
}

/**
 * Find latest poll and redirect user
 */
function MYMODULE_find_poll() {
  $nid = db_result(db_query('SELECT MAX(nid) AS nid FROM {node} WHERE type = "poll"'));
  $latest = is_numeric($nid) ? 'node/' . $nid : '<front>';
  drupal_goto($latest);
}

Replacing "MYMODULE" with the name of your custom module and placing those files in your site's modules directory in a folder named MYMODULE (replace of course).


How do I create a grouped exposed filter on a block?

In your view, make sure your exposed filter is not the gallery type field itself, but 'Has taxonomy term' filter with the taxonomy group vocabulary selected and then set the exposed grouped filters the same way.


This issue in pathauto Replacing node/XXX/edit to mypage/edit lead to this module: Sub-path URL Aliases give it a shot.

  The Drupal Path module matches only full URLs when creating SEO-friendly aliases. This module extends that behavior by also matching known sub-paths and replacing them with their respective alias. For example, if node/1 is aliased to content/alias, this module rewrites the link to the node edit page node/1/edit to use the aliased URL content/alias/edit instead. This also includes Views URLs taking a node as argument (node/%/yourview), in short, every URL that is based on, or extends, an existing alias. In combination with the Pathauto module it is possible to get rid of all remaining exposed internal URLs.


Render add node form within module output

You will have to use drupal_render() on node_add() result.

module_load_include('inc', 'node', 'node.pages');
$content = node_add('osago');
print drupal_render($content);


I have similar setup where i use drupal as back-end and connect to services with Angular app (Ionic App) and i am describing the sequence below; however, you need to consider the below reference if you are doing cross domain
https://stackoverflow.com/questions/35007572/angular2-xhrfields-withcredentials-true/
And you have to setup CORS (This is my config for reference)
API/*||POST,GET|Content-Type,x-csrf-token,Authorization|true

Login to your drupal service
End Point: /user/login
Payload:{"username":"username","password":"userpass"}
Content-Type: application/json
Method:Post
Result: User information & Token

Request

Get the Token and use it in subsequent requests by setting the header to X-CSRF-Token
End Point: /node/100
Payload:Empty
Content-Type: application/json
Method:Get
Result: Node information

Request With X-CSRF-Token header

Logout from drupal service (Token must be set as well)
End Point: /user/logout
Payload:Empty
Content-Type: application/json
Method:Post
Result: [true]


How to format Start + End Dates without using PHP

You can coax something out of Views without PHP (see Partial Solution below) but not, I think, quite what you want. A module or - against your team policy Views PHP - may be required.

Discussion

Part of why some of the usual Views workarounds won't solve this problem is the edge cases. If we knew that ranges of dates would always be within the very same month, then this could be done in Views without PHP using the approach outlined below. But that seems unlikely! You need to consider what you want to do when you get cases such as 31 May 2013 to 2 Jun 2013 or 28 Dec 2012 to 4 Jan 2013. What do you want displayed? If you want '31 May - 2 Jun 2013' and '28 Dec 2012 - 4 Jan 2013' respectively, but in non month-crossing cases '2 - 3 May 2012', then some code is going to need to be involved somewhere.

Partial Solution

A partial solution can be massaged out of Views. It will avoid repeating the year but not the month. So you get, e.g. '2 May to 3 May 2012', '28 Dec to 4 Jan 2013', '31 May to 2 Jun 2013' from it. Just possibly this might be close enough for some use cases.

The strategy is to add the date field twice (excluding it from display) and apply different formats / configurations. You can then use Global: Custom text fields to join the results together.

Create two date formatters. One to give '12 Mar' when given 12th March 2012 (j M) and one to give '2012' when give 12th March 2012 (Y).
Add the date field (and exclude from display). Set it to show both the START and END dates using the '12 Mar' format. When both START and END are present this will yield '3 Mar to 6 Mar' etc. When only START is present, it will yield '3 Mar'. Recommendation use the 'Administrative title' in the 'More' section to document this, e.g. 'Date or range without year'. This helps at the final step.
Add the date field (and exclude from display). Set it to show just the END date. Use the '2013' format. When an END date isn't present, Views will fall back to using the start date. Recommendation use the 'Administrative title' in the 'More' section to document this, e.g. 'Year'. This helps at the final step.
Add a Global: Custom text field and use 'Replacement Patterns' to output the 'Date or range without year' followed by the 'Year'. (Easy if you've documented with the 'Administrative title' - trial and error if not.)

Note: If you want to detect the absence of an end date at step (3), Views will do this if you make use of the No Results area. It only defaults to the Start Date if the No Results area is not used. That gives some, albeit, limited scope to vary formatting depending on the presence of absence of an end date.


Disallow purchase if coupon code is not entered?

There is no easy way to do this sadly, your best bet would be to try and play around with hook_form_validate or hook_form_submit on the ubercart form submit and see if you can find the field values in one of the submitted panes.

If that doesn't work then your best bet would be to try and code your own "pre review order" coupon box, that hooks into the cart view page. So what I am thinking is

Users goes to /cart
Has the listing of the items in the cart
Has the "coupon stuff" at the buttom, but part of the "Checkout" form (use
form_alter for example)
And use the hook_form_validate hook to verify it has data, and the coupon is good, then proceed


How do I access the database from a stand-alone PHP script?

Check the first line (where you have ..testdrupal\');

The \ before the ' is escaping the ' so it's as if it's not there (sorry, it's tricky to explain without my morning coffee).

With the character escaped, the line is being read as follows:

chdir('C:\xampp\htdocs\testdrupal'./includes/bootstrap.inc');

Which is where your error is most likely coming from.

Try changing the first line to the following:

chdir('C:\xampp\htdocs\testdrupal\\');

The extra \ means that you are escaping the following character so the line will be read the way you want it to be.

There's a quick explanation of escape characters here.


How to return all the tags from a specific vocabulary for the current node

arg() returns a string so $nid is not an object. You're currently adding your :node_nid database condition with a value of $nid->nid, when you should just be using $nid:

$vid = 1;
$nid = arg(1);

// Updated as per comments below
$sql = 'SELECT t.name FROM {taxonomy_term_data} t INNER JOIN {taxonomy_index} r ON r.tid = t.tid WHERE t.vid = :vid AND r.nid = :node_nid ORDER BY weight';
$args = array(':vid' => $vid, ':node_nid' => $nid);

$terms = db_query($sql, $args)->fetchCol();
$comma_separated = implode(', ', $terms);

If you want to load the node object related to the current path then you can use menu_get_object(); then you can access the nid as part of the object:

$node = menu_get_object();
$nid = $node->nid;

But I suspect that will be overkill as you only really need the $nid, and not the full node object for your query.


How to override a module theme function in a custom module but still allow themes to override the template file?

Think what you describe could work without falling back to the field module's function:

Add <?php function MODULENAME_preprocess_field($variables) ?> and set a $colon variable with either ':' or ''
Copy the theme_field function in your module and rename it <?php MODULENAME_field(&$variables) ?>
Replace the code that renders the label with: <?php $output .= '
' . $variables['label'] . $variables['colon'] . '&nbsp;
';?>

Might also just document for themers that in the template file they should use $colon for the module to work.


You can use hook_apachesolr_query_alter($query) to alter your results variable, if you're using Apache solr views and this error

Notice: Undefined property: apachesolr_views_query::$group_operator in apachesolr_views_query->build() (line 80 of /var/www/html/root/sites/all/modules/apachesolr_views/apachesolr_views_query.inc).

this means that you didn't use filters in your view.


Using only node_load() you cannot get a list of the most recent nodes, as node_load() returns a single node object for the node that matches some criteria; it's not a function that returns a list of nodes.

The faster, but a little inefficient, way to get a list of more recent nodes is to:

Get the list of node IDs associated with the most recent nodes
Call node_load() for each of the node IDs obtained from the first step

You could use code similar to the following one.

   $nodes = array();
   $result = db_query_range("SELECT n.nid FROM {node} n ORDER BY n.created DESC", array(), 0, $number_of_posts);

   while ($nid = db_result($result)) {
     $nodes[] = node_load($nid);
   }

After that code is executes, $nodes will contains the $number_of_poststh recent nodes.


To create a form on a page you need to use Drupal's Form API. It seems a bit complex at the first sight, but it isn't as it seems.

The steps you need to follow:

Create a custom module
Implement hook_menu() in your module and set a path for your page which should render the form.
A form builder function that builds a form using the Form API.

An Example for hook_menu() implementation:

function YOURMODULE_menu() {
  $items['some/path'] = array(
    'title' => 'My page title',
    'description' => 'An example page',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('YOURMODULE_example_form'),
  );
  return $items;
}

This code registers a paths as http://example.com/some/path and calls drupal_get_form() function, which gets a form with the given id, which in this example is YOURMODULE_example_form.

An example for the form builder function:

function YOURMODULE_example_form($form, &$form_state) {
  $form['some_text_field'] = array(
    '#title' => t('Enter some text'),
    '#type' => 'textfield',
    '#required' => TRUE,
  );

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

  return $form;
}


How can I fix site UUID does not match error during config import?

Site UUID in source storage does not match the target storage.

Make sure you've system.site.yml on your staging site, see: Site UUID in source storage does not match the target storage.

To check the current UUID, run:

drush config-get "system.site" uuid

to change it, run:

drush config-set "system.site" uuid "xyz"

See: How can I import the configuration on a different site?

  Entities exist of type Shortcut link and Shortcut set Default. These entities need to be deleted before importing.

Try removing these entities manually before the import as it says.

  The core.extension configuration does not exist.

Make sure you've core.extension.yml file in your config folder, otherwise generate one via config-export.

  Can not uninstall the Configuration module as part of a configuration synchronization through the user interface.

Most likely it's related to the missing core.extension.yml.

Few hints:

You can also try to import the config using Drupal Console using config:import.
For debugging purposes, try to import one file at a time. See: Import a single yml configuration file. For example:

drupal config:import:single --directory=$PWD/config/sync --file=file.yml

If you're using different config dirs per environment, consider using Config Split.


Add an image to a line item in drupal commerce

It's easier to start with kickstart, but there are alot of things in there you might not need and confuse you in the process of setting up your store.

I would suggest just going as minimal as possible and add in what you need for the site as needed. I'd say just go with the core Commerce module and work your way up and add in the things as you need it to reduce all the bloat. Then you will have nice clean installation and also know where everything is as you will be done building it up from the ground up.

I was attempting to go the kickstarter route in the beginning just as you would because I saw that it was easier, but its really not i feel as there are certain modules you just dont need.


If I understood you correctly, you want to display nodes that have a term, but not the nodes that have a child term.

You also want to display the child terms.

There are some different ways of handling this, since you are using the default view, you should get a View already that displays the correct nodes - so all you are missing is the terms.

The best way to deal with this, is not through Views, but a module called Taxonomy menu. It will create a menu with the same structure of a vocabulary which can expend, to show child menus. As with menus you get use the block system to add them on the term pages. Beware of a bug with the menu system though see the issue.

A quick fix is to add this in your settings file:

$conf['menu_default_active_menus'] = array(
  'navigation',
  'management',
  'user-menu',
  'main-menu',
  'your-menu-here',
);


How to add css class to a field from a select list before rendering?

I have used the Field Formatter CSS class module for the same task. The client wanted to have predefined colors for heading elements in paragraph bundles. I have to admit this seems like an amendable approach, but it worked.

I had set up a vocabulary for the color names list and referenced this in the paragraph bundle as a select list (taxonomy term reference). In the display settings for the field is css-class selected. The format settings are set to target tag = entity.

This results basically in following markup:

This is a headline

CSS:

.h1-colorclass-red .field-name-field-heading {
    color: red;
}


Your sitemap seems to work. When viewing the source of your sitemap, the XML needed for crawlers is displayed.

If you're talking about the blank page you get to see when viewing it in your browser: see if you've enabled the "include stylesheet for humans" option in the configuration of the module.


user_login_block doesn't display message

I successfully managed and fix it.
The code i was using to display the login block was as below
print drupal_render(drupal_get_form('user_login_block'));

This block used to generate the login block for the login functionality.
Now i tried to render the messages using theme_status_messages() function.
To fix the issue i created a function in my template.php file named THEMENAME_get_login_block().
In this function i added the theme_status_messages() function for the displaying the messages. So my function looked like given below.
function THEMENAME_get_login_block() {
    $form = drupal_render(drupal_get_form('user_login_block'));
    $messages = theme_status_messages();
    return $form.$messages;
}

And to render the block i used print THEMENAME_get_login_block();
This solved my problem. But still i am curious to know the root cause of such kind of events.
Any suggestions are welcomed....


render() builds are renderable array for a table:

  public function build() {
    return \Drupal::entityTypeManager()->getListBuilder('entity_type')->render();
  }

Reference: https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Entity%21EntityListBuilder.php/function/EntityListBuilder%3A%3Arender/8.5.x


I ended up using the built in drupal comment system as the feedback and just hid the comments from everyone but admins. I used fivestar for the star rating system attached to comments.


Third party library added via composer.json but how can I load it in a module now?

You don't need to use require_once for autoload. It handles by the composer automatically. You should create a use statement in your php file.

As an example if you want to use a class s3 module of aws;

use Aws\S3\SomeClassName;


Custom Twig template for confirmation webform page being cached too hard

Seems like there are two different issues here:

(a) Loading a twig template from an arbitrary folder.

Could you try setting the path theme property and see if that allows your twig template to be loaded? For example:

'webform_confirmation__application_form' => [
  'template' => 'application-form-confirmation',
  'base hook' => 'webform_confirmation'
  'path' => \Drupal::moduleHandler()->getModule('application')->getPath() . '/templates',
],

(b) Modifying the cache settings for a part of your render variables.

You should check that the cache tags bubble all the way up from the message array. Apparently:

  You have to render the content variable to ensure that its cache tags
  bubble up and end up in the page cache.

as mentioned here => (https://www.previousnext.com.au/blog/ensuring-drupal-8-block-cache-tags-bubble-up-page)

So, one place to start would be trying to render the whole content variable in your twig template, provided you got past (a)

Update: You could also try calling \Drupal::service(''page_cache_kill_switch'')->trigger(); in order to avoid Internal Page Cache to interfere with the request and page loading.

A simple way to do this inside a twig template would be using an approach similar to this module => https://github.com/stefanospetrakis/twig_killswitch_trigger

Good luck!

P.S.: Sample code is also available here => https://www.drupal.org/sandbox/stefanospetrakis/3011610, I may promote this to a full project if there is any potential interest.


How can I rewrite a date field "End Date" to be "present" if no value is entered?

When there is no end date specified for a node it takes both the dates same. The module consider it a one day event.

However, in your case you are making it ongoing by not mentioning the end_date so no results behavior is not going to work. I would suggest to use some global php like this

<?php
if($row->field_date == $row->field_date_1) {
   echo "Present";
} else {
  echo $row->field_date_1;
}
?>

Make sure to include this php field after both start and end date fields, and make the end date fields hidden.


How can you add a node dropdown list to choose from when adding a link inside ckeditor?

You are looking for CKEditor Link - A plugin to easily create links to Drupal internal paths.


How to implement a button with different redirections?

Point the button to a custom controller:

namespace Drupal\mymodule\Controller;

use Drupal\Core\Controller\ControllerBase;

class ExampleController extends ControllerBase {

  /**
   * Controller for action button.
   */
  public function action() {

    // if user is not logged in, redirect to create a new account
    if ($this->currentUser()->isAnonymous()) {
      return $this->redirect('user.register');
    }

    // else return content or redirect to content
    return ...;
  }

}


How to assign a content type to a workflow programmatically?

I found a way, I would like to know your opinion about how to do it.

No doubt you have to take into account additional validations, but basically to save a type of content to a workflow would be something like this:

/** @var \Drupal\workflows\WorkflowInterface $workflow */
$workflow = $this->entityTypeManager->getStorage("workflow")->loadByProperties(["id" => "editorial"])["editorial"];
$config = $workflow->getTypePlugin()->getConfiguration();
$config["entity_types"]["node"][] = "article";
$workflow->getTypePlugin()->setConfiguration($config);
$workflow->save();

At the moment I'm just setting contents types, for blocks it's something similar.
Greetings.


How to alter views exposed form and add ajax to filters

This patch is related to this issue https://www.drupal.org/files/issues/2019-08-01/2842525-56.patch. See the section core/modules/views/src/ViewExecutable.php especially, the FormBuilder part is already committed but the rest is waiting.


I figured it out. I needed to pass a string not an object, the lack of documentation confused me.
    let args = 'antelope valley';
    args = args + '/207'

    $.ajax({
      url: '/views/ajax',
      type: 'post',
      data: {
        view_args: args,
 ...


How to grant access on some functionnalities in system dashboard to a given role

By default, when a user logs in on Drupal, they are redirected to /user (the user page). If you want to change that behavior (so they are redirected to a custom dashboard page that you create (ie: /admin/dashboard) you might be able to use Rules (assuming you are on D7 - Rules is not ready for D8 yet as far as I know). You would create a Rule that triggers when a user logs in, add a condition to check there role, and an action to redirect them to another page.

You may also want to read this, because there may be more conditions you want to include, so that they are NOT redirected when they are resetting their password, for example: https://www.drupal.org/node/480584

As for hiding Configuration menu and other things, that is accomplished by assigning (or not assigning) permissions to the user roles. So your admin role should include access to Configuration, but your other roles should not.


Views with exposed filters sound like a great way to add a Search page to Vocabulary configuration tabs.

You can add your Views page to Vocabulary pages through Views configuration. Since the List already exists as the default tab, simply configure your Views page Menu option as a normal Menu tab and set the page path to the [path-to-default-vocabulary-page]/search.

The tab will appear as one of the tabs you see when you visit the Vocabulary configuration page.


how to open custom form in popup onclick in menu link drupal

There are many ways to do this.
You can use  Popup forms module. Its configuration is in documentation of module
or Modal Frame API module.


Use built-in Drupal Ajax framework.. Steps:

implement hook_menu
build ajax callback
render links (titles) like /[menu callback menu item]/nojs/arguments and add class use-ajax

Here is a good tutorial: A little Ajax-driven article reader built with the Drupal Ajax framework


Yes; See the handbook page on drupal.org: Installing virtual hosts for Drupal sites and subsites.


You must create form with FormAPI, then the form is avalable for Captcha as you say "contact-form" -> "contact_form". If the form is embeded whatever other method like iframe, then the form must already contain integrated own captcha. This also applies when form is build without FormAPI - using  in client's site.


How to include CSS3 Pie in my Drupal site?

There is a module for that:
http://drupal.org/project/css3pie

The instruction on the project page are better than what I could explain it as having to be done.


With every Nodeaccess permission change, Permissions need to be rebuilt every time, for some reason I am not getting the warning message on save, run it at /admin/reports/status/rebuild


How to prevent multiple logins for administrator?

Session Limit allows to put restriction on session based on user role, it could be admin role also, with an exception that it does not restrict user with uid 1 which is kind of rescue point in case you misconfigure the module.

I would say instead of finding any module or building any custom solution which can put restriction on uid 1, you use different account with admin role which this/any module can handle gracefully.

As a thumb rule I don't put any restriction on uid 1.

If you see the code of session_limit.module line 248

function session_limit_init() {
  global $user;
  if ($user->uid > 1 && !isset($_SESSION['session_limit'])) {

    if (_session_limit_bypass()) {
      // Bypass the session limitation on this page callback.
      return;
    }
    ..

It clearly shows uid 1 is left intentionally.


Drupal Rest services "access denied user anonymous"

Here is running code with access callback function:

function mymodule_services_resources() {
 $api = array(
  'blog' => array(
    'actions' => array(
     'math' => array(
      'help' => 'Retrieves posted blogs',
      'file' => array('type' => 'inc', 'module' => 'MYMODULE', 'name' => 'mymodule'),
      'callback' => 'mymodule_blog_retrieve',
      'access arguments' => array('views'),
      'access callback' => '_blog_access_provide_access',
      'access arguments append' => TRUE,
      'args' => array(
        array(
          'name' => 'var1',
          'type' => 'string',
          'description' => 'variable 1',
          'source' => array('data' => 'var1'),
          'default' => '0',
        ),
        array(
          'name' => 'var2',
          'type' => 'string',
          'description' => 'variable 2',
          'source' => array('data' => 'var2'),
          'default' => '0',
        ),
      ),
    ),
  ),
),

 );
  return $api;
}

/** * Access callback */
function _blog_access_provide_access() {
  return TRUE;
}

I hope this would help you.


You could wrap it in PHP's htmlspecialchars and strip_tags functions:

$body_trimmed = render(field_view_field("node", $node, "body", array(
  "label"=>"hidden",
  "type" => "text_summary_or_trimmed",
  "settings"=>array("trim_length" => 150),
)));
print htmlspecialchars(strip_tags($body_trimmed));

This would give you plain text with special characters encoded.

Alternately, if all you want to do is escape the quote characters and leave the divs in place, you could do a search/replace using str_replace for each, adding the backslash to escape them:

$body_trimmed = render(field_view_field("node", $node, "body", array(
  "label"=>"hidden",
  "type" => "text_summary_or_trimmed",
  "settings"=>array("trim_length" => 150),
)));
$body_trimmed = str_replace("'","\'",$body_trimmed);
$body_trimmed = str_replace('"','\"',$body_trimmed);
print $body_trimmed;


What are my pages called for adding blocks?

Assuming that you want to show your block on your 'Contact' page.Now, have a look at your 'Contact' page URL, for example it can be http://example.com/?q=node/2 without pathauto module.
Now, lets create a block under that choose Only the listed pages then write node/2 in the field!

Now, save block and it should work.


Did you tried dump-autoload command too -

composer dump-autoload

Ref: https://getcomposer.org/doc/03-cli.md#dump-autoload-dumpautoload-


Show custom query page based on user logged in

If your page is being created via code, then you can check the role of the user via code and not display the filters you want.

Otherwise, you may want to create different query pages for different roles and enable the right page for the right role using a module that restricts access such as the 'node access' module.


D7 Views: content associated with a user via tags

Maybe these links could be a good starting point, as they provide a step by step guide of how to configure views with a relationship to the current user:

http://blog.hsl.virginia.edu/drupalpress/show-users-any-content-that-matches-any-taxonomy-term-in-views/

http://blog.ampli.fi/filtering-a-drupal-7-view-based-on-a-user-profile-field/


If you are insisting on a function then you are looking for arg function.

arg(0) will return 'node' and arg(1) will return node nid.

Provided you must be inside a node.

[Updated Answer]

if (arg(0) == 'node' && is_numeric(arg(1))) {
  $nid = arg(1);
  if ($nid) {
    $node = node_load($nid);
    /** do something **/
  }
}

Alternately

you can get nid from node object $node->nid


this is some sort of a bug / incosistency of how the boolean field is made. if you leave it in default, without any 0 / 1 values, it wont show them in places like this filter.
But : the values are there :) under "Select all" you have 2 rows that just dont have captions. When you pick one of them, you can see that the SQL for your view is changed.
The workaround would be to add some captions to the values in the field defintion.


One thing that helps immensely is to enable Twig debugging in your services.yml (not recommended for production environment).

parameters:
  twig.config:
    debug: true
    auto_reload: true
    cache: false

The auto_reload and cache settings can also be set to their development settings so you do not need to rebuild cache (remove compiled twig templates manually).

This will enable HTML comments that show what template is being used for various components in markup. Bartik and Classy, by default, displays this as block.html.twig. The template suggestions for a block is block--PLUGINID.html.twig where the PLUGINID is the the block's plugin id with underscores replaced by dashes.

Example debug output from my local development environment using a sub-theme of Classy:

<!-- THEME DEBUG -->
<!-- THEME HOOK: 'block' -->
<!-- FILE NAME SUGGESTIONS:
   * block--userlogin.html.twig
   x block--user-login-block.html.twig
   * block--user.html.twig
   * block.html.twig
-->
<!-- BEGIN OUTPUT from 'themes/custom/blah8/templates/block--user-login-block.html.twig' -->
<div id="block-userlogin" class="contextual-region block block-user block-user-login-block" role="form">

templates/block--user-login-block.html.twig


Take a look at Workbench Scheduler. you could make changes as a draft(or any other workbench moderation state) and let Scheduler publish it.


How to add contents through block after enabling the blog module in drupal 7

Based on your comment above, you want to display blog entries in a block on your website.

I haven't used the Blog module in a long while (it's functionality can be duplicated easily without enabling it), but I think the easiest way for you to do this is to use Views.

Add a few blog entries
Create a new View that displays Content of type Blog Entry in a Block.
Views creates a new block, which you can place anywhere you'd like via the Block Admin page.

If you are unfamiliar with Views, you should watch or read some video tutorials. This one is recent and seems to be up your alley.


Generally Clive is right. Don't touch core. But sometimes you are forced to do a core patch or it's just much easier to solve your requirements.

If you must: I'd recommend to put your whole project into git. This gives you the possibility to have a clean core version in one branch and the patched one in an other. Everytime a new core version is published you can merge it in a clean way.


Editting field collections with service api

You must send acceptable field structure in order to create or edit the node

try to understand the field structure through Implementing hook_node_insert in custom module and  watchdog the inserted node via watchdog and you will have the structure drupal uses to insert then build it when you create/edit node through services

function hook_node_insert($node){
  watchdog('node', json_encode($node));
}

after adding a node of the same type open dblog in your project and see that log, you could use pro.jsonlint  to understand it well

Hope that helps


You can look at LanguageTestServiceProvider to see how alterations are made. Or I can offer my class:

<?php
namespace Drupal\mongodb;

use Drupal\Core\DependencyInjection\ServiceModifierInterface;
use Drupal\Core\DependencyInjection\ServiceProviderInterface;
use Drupal\Core\DependencyInjection\ContainerBuilder;

/**
 * MongoDB service provider. Registers Mongo-related services.
 */
class MongodbServiceProvider implements ServiceProviderInterface, ServiceModifierInterface {

  /**
   * {@inheritdoc}
   */
  public function register(ContainerBuilder $container) {
  }

  /**
   * {@inheritdoc}
   */
  public function alter(ContainerBuilder $container) {
    foreach ($container->findTaggedServiceIds('mongodb.override') as $id => $attribute) {
      $container->setDefinition(substr($id, 8), $container->getDefinition($id));
    }
  }

}

Basically, in alter you need to use the getDefinition method, do something with the definition and then use the setDefinition method to put it back.

and then here's the relevant parts of mongodb.services.yml:

services:
  mongodb.flood:
    class: Drupal\mongodb\Flood\MongoDBBackend
    arguments: ['@mongo', '@request']
    tags:
      - { name: mongodb.override }


Add link gone from main menu and getting errors when trying to add new menu item

Ok, found the answer, eventually another error popped up when trying usermenu:

Warning: Illegal string offset '#value' in
content_menu_form_menu_item_delete_form_alter() (line 270 of
C:\aquiasites\redoII\sites\all\modules\content_menu
\content_menu.module)

I disabled all possible menu plugins...the offending module didn't create any errors on main menu and other, ONLY on usermenu...

Disabled this module https://www.drupal.org/project/content_menu

Now works fine


Yes. Sort of.

The ?page=X query parameter in views pages is the offset from the SQL results (if you have the views admin section displaying generated SQL you can see this by the OFFSET X clause).

Hence, if you adjust your Pager options such that the Offset (normally 0) is set to opposite (e.g. -5) of the number in the Items per Page (e.g. 5) it will produce the effect of /my-views-page?page=1 containing the first results of your query.

However, it will also produce the side effect of the first offset page (i.e. /my-views-page and /my-views-page?page=0) of having no results. You could probably mitigate this through some URL rewriting, but it's a bit of work for something that has very little value (how many people browse the web thinking about numbered results vs. index offsetting?).


There is a block version of print links Printer, email and PDF versions. goto admin/structure/block and enable it. next you should goto admin/config/user-interface/print and change Printer-friendly page link setting to Block.


Loading nodes that are only available to the current user

You need to use the EntityFieldQuery class. The following is example code to load all the published nodes whose content type is Article.
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'article')
  ->propertyCondition('status', NODE_PUBLISHED);

$result = $query->execute();
if (isset($result['node'])) {
  $nids = array_keys($result['node']);
  $nodes = entity_load('node', $nids);
}

EntityFieldQuery returns only the nodes to which the currently logged-in user has access. In the case you would get all the nodes for which you know the author user ID, you should use the following code.
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'article')
  ->propertyCondition('status', NODE_PUBLISHED)
  ->propertyCondition('uid', $uid);

$result = $query->execute();
if (isset($result['node'])) {
  $nids = array_keys($result['node']);
  $nodes = entity_load('node', $nids);
}

That code returns all the nodes created in the site. To get only 10 nodes, it sufficient to add a call to $query->range(0, 10) before calling $query->execute().


Typical approach

The previous answer quite often resolves various situations where some variables appear to not be available in Rules Actions, etc. For example, before using a Rules Action like "Set a data value" for your a field, you have to make sure to add a Rules condition Entity has field (related to the  field for which you want to set a value). And make sure to add that Entity has field condition BEFORE other Rules Conditions in which you might want to refer to this field.

That's also what is mentioned in the Rules UI, e.g. when you're adding a "data comparison" condition: somewhere it says "The data selector helps you drill down into the data available to Rules. To make entity fields appear in the data selector, you may have to use the condition 'entity has field' (or 'content is of type')".

For a video tutorial that illustrates the importance of this Entity has field condition, refer to Data types and data selection, especially what is shown between about 13:30 and 17:30 in it.

Webform requires another approach

However, for this specific question, which is about using Rules in combination with Webform, things are a very little bit more complicated, as further explained below.

Let's assume I have a webform created with some of its fields with machine names like so:

contact_us_first_name.
contact_us_last_name.
contact_us_subject.

After you add these fields (with identical machine names) to any of your own forms, you should be able to import the prototype-rule below (using the Rules UI) in your own environment (without running into an integrity constraint):

{ "rules_create_a_node_from_a_submitted_webform" : {
    "LABEL" : "Create a node from a submitted webform",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "webform_rules" ],
    "ON" : { "webform_rules_submit" : [] },
    "IF" : [
      { "user_has_role" : { "account" : [ "user" ], "roles" : { "value" : { "2" : "2" } } } }
    ],
    "DO" : [
      { "drupal_message" : { "message" : "The webform component submitted by [data:contact_us_first_name-value] (= [data:contact_us_first_name-title]) [data:contact_us_last_name-value] (= [data:contact_us_last_name-title]) contains a field labeled \u0022[data:contact_us_subject-title]\u0022 which has value \u0022[data:contact_us_subject-value]\u0022." } }
    ]
  }
}

In the above rule I included an extra Rules Condition to prevent the Rules Action from being executed for anonymous users (feel free to adapt the role id of it, or just remove that Rules Condition). And the rule is triggered via Rules Event "After a webform has been submitted".

The Rules Action only displays an (informational) message on the site (my recommended way of writing and debugging Rules ...) after a webform gets submitted. Here is what I specified (in the Rules UI) as the message to be shown:

  The webform component submitted by [data:contact_us_first_name-value] (= [data:contact_us_first_name-title]) [data:contact_us_last_name-value] (= [data:contact_us_last_name-title]) contains a field labeled "[data:contact_us_subject-title]" which has value "[data:contact_us_subject-value]".

Here is a sample of the message shown in my own setup:

  The webform component submitted by Dries (= First name:) Buytaert (= Last name:) contains a field labeled "Subject:" which has value " Rumour goes that the Rules module for D8 is making progress! ".

What the above prototype-rule shows is that the "clue" to answer your question is that you have access to all labels and all values of any field of a webform available, ie:

[data:MachineFieldName-title] contains the Label of a field with machine name MachineFieldName.
[data:MachineFieldName-value] contains the Value of a field with machine name MachineFieldName

All that's left to fully answer your question now is to correct your Rule using similar tokens.


D7 Rules - Unable to get data value & Unable to evaluate action in custom module

For any future readers who encounter this issue:

It turns out the answer all along was using the hook_commerce_checkout_complete in my module, rather than trying to insert an action with rules.

Here is an example I used for debugging:

function MYMODULE_commerce_checkout_complete($order){
  $file = fopen("checkout_debug.json", "w") or die("Unable to open file!");
  fwrite($file, json_encode($order, JSON_PRETTY_PRINT));
}

of course the reason I used json_encode is because $order is not a string and I could pretty print it.

Hope it helps someone, eventually. Thanks again.


How do I get the video media path in a theme?

It's unclear whether you want to get one or multiple videos:
// get one video media entity
$video = $row->_entity->get('field_pvideo')->entity;
// get multiple video media entities
$videos = $row->_entity->get('field_pvideo')->referencedEntities();

Then in Twig for one video:
{{ programme.video.field_media_video_embed_field.value }}

or multiple videos:
{% for video in programme.videos %}
  {{ video.field_media_video_embed_field.value }}
{% endfor %}