Update programmatically Group Audience I have made a hook_node_insert which when I create a group content of type A, it create a node group. I want to associate my type A with the created group with the field audience.
I have changed the field group audience like that

$nodeA->group_audience = array(
    LANGUAGE_NONE => array(
        '0' => array(
            'gid' => $group->gid,
        ),
    ),
);

But it doesn't save the data into the database. I have tested with node_save but I have the error that primary key nid is duplicated.

Thank

Unless you're changing the $node inside a node_save() or something, your changes won't make it into the database unless you add a node_save() after the change to $node.


Is it possible to trigger an Ajax CallBack Function After a Link is Click I have a simple link in my form.

$form['myid_print']['myid_print_search_idnumber_wrapper'] = array(
  '#type' => 'item',
  '#markup' => 'Im a link....',
);

Is it possible to trigger an ajax callback function after a link is click? If yes, how?

Yeah you just need to use use-ajax class for this.

$form['myid_print']['myid_print_search_idnumber_wrapper'] = array(
  '#type' => 'item',
  '#markup' => l(t('Test Ajax'), 'admin/ajax-url/nojs', array('attributes' => array('class' => 'use-ajax'))),
);

Checkout this blog : http://www.computerminds.co.uk/drupal-code/make-link-use-ajax-drupal-7-its-easy.


Editors choose layout I want to give editors the ability to take advantage of a grid system we have on our site.  I can easily jump into a node and add this to the Body

one column

content on the left

content on the right

one column

...

Editors aren't savvy enough with HTML and CSS to do this themselves, and that's fine, that's what wysiwyg editors are for, and why we use Drupal in the first place (mainly).

But, this is a system of layout that can be applied consistently on any node. I'd think it would be easy enough to allow editors to take advantage of it. I'd love to let them create as many rows with as many columns as they want on any node without having to code it up themselves.

I know I can create template files that will apply structured HTML to all nodes of a given type, or one node, or some subset of nodes.  However, I don't want to make that choice for editors.  And besides, you can't split up the body content of a node into rows and columns like that from a tpl.php file.

I've looked into Panels too, but from what I can tell that's just a GUI means of creating tpl.php files.  Same problem.

This is very similar to the unanswered question Select Panel Node Layout on Node edit form.  I'm using 7.

You're asking a chicken and egg problem. Nodes just hold data and no information about the theme (usually). You're describing mixing the two in the Body field of a node, in essence hard-coding the look (layout) of your "node" in the database.

Drupal in many respects fights this as the page content is 1 item and drupal7 cares nothing about whats around it. In D8 their is a UX initiative to make a nicer page layout creation system.

In D7 you may be interested in context_layouts found in Context. See this youtube video on its usage.

I've done something similar (but not Grid aware) using Spaces, spaces_node and Dashboard (spaces dashboard) in Drupal6 per node (I also used node_block heavily). Every node/page could have their own unique layout using Spaces and its submodule of Dashboard; you can set any content to any block/region of the page as needed using a drag-and-drop overlay. Actually, the site I'm mentioning is UCSB SageCenter. Unless your logged in and editing a Space/Dashboard you dont really see anything in the source. I added a node field to pre-assign a known space for node pages on node creation. This site was hard.

Here's a video demo on spaces_node -- its not supported anymore really.


'block/plugin' show a selected node. When editing the available nodes are filtered by type (or views) There is a way to put a 'block/plugin' in a panel which, when edited by an admin, would have a list (using views if possible) of nodes to choose?

The idea is to place this 'block/plugin' in a pane of 'services', for example, and allow the admin to easily change the viewed 'node of type services' in a easy list. Something like node_pane, but not exactly the same.

With this I can say something like 'here will be a highlighted news, there will be 3 highlighted services' and so on.

Thanks in advance =)

Ok, isn't exactly what I was looking for, but does the job.
I created a content "News Holder", then added a field using entity reference and multiple selects. This field I set to have the number of "News Content" that I want and them a just need to place this content (used panels in this case).
This field can be configured to show a list (select list) of entities that the entity reference can reference.

So, using this way the user with admin privileges viewing the page can click the cog icon and edit, to edit this node. In the edit page he have direct access to the selects of the news content. It's direct and easy to use.

If someone still manage to do something similar or better, I would love to read =)


API to display block in regions I would like to display blocks in region by code, in the same way that I can use context (so: if I'm on a node_view of type "article" display block "user login" on region "Sidebar first", for example).

I know how to load and display blocks but I don't know which is the best place to make it.

Have I to add the render function in regions template?
Or have I to use a theme function to do this?

Instead of using the admin blocks interface, if you really want to manually render blocks, you can render:

Directly in a template:

if ($block = module_invoke('module_name', 'block_view', 'block_delta')) {
  print render($block['content']);
}

Via code, with drupal_add_region_content

if ($block = module_invoke('module_name', 'block_view', 'block_delta')) {
  drupal_add_region_content('left',  $block['content']);
}


Using Panels for Layout versus custom .tpl files I'm working through some layouts that aren't entirely complex but are definitely outside of the core Drupal provides.

It really does seem like there a 20 ways to do one thing in Drupal.

Should you edit .tpl files with different regions for specific content types and nodes, or should I just stitch everything together with Panels?

I have this fear that Panels would make everything more complex and start to bog things down from a performance perspective.

Panels module

"Learn Page manager" is an interesting / amazing set of videos. They contain various topics related to the Panels module. After you reviewed these videos, you'll understand that it'll be hard to come close to all the features that come with the Panels module.

Here is a summary of the entire set of videos about this topic (quote from the link above):

  Page manager allows you to collect and manage contextual information in a flexible and consistent way. It is an important part of building infrastructure on Drupal websites, and you should know how to use this module.
  The screencast series is targeted at experienced Drupal developers.
  Episodes 1, 2 and 3 introduces the most basic concepts, such as custom pages, variants, selection rules and (to some extent) contextual objects.
  Episodes 4, 5, 6 and 7 talk about Panels, with emphasis on Views integration but also some words on efficient caching.
  Episodes 8 and 9 about access control, menu items, and not least the little-known but very useful Contextual Administration module.
  Episodes 10 and 11 talks more about using contextual objects in Page manager, including using Views as context. This is, imho, where the real power in Page manager is.
  Episodes 12 and 13 collects various bits and pieces, such as how to use Panels to easily rearrange the node edit form, import/export settings, and some extra modules that can be used with Page manager.

Refer to Explaining Panels: An Overview for Drupal Developers for another great explanation about Panels.

Some more words about Page Manager:

In Drupal 8, Page Manager has become a separated module, while formerly (up to Drupal 7), it was part of the CTools module. Here are some more quotes from the (D8 related) project page:

  It supports the creation of new pages, and allows placing blocks within that page.

  Like Drupal 7's Page Manager, it provides a concept of "page variants", each with their own selection conditions.

  Additionally, it can be used to take over an existing page, like overriding /node/% to change what is displayed when viewing a node.

  It utilizes the core Conditions, Context, and Blocks APIs to accomplish this.

In Drupal 7, Page Manager was the foundation of the Panels module.

Bean module

When talking about layout in Drupal, one often brings up "Blocks" also. If you also use the (great) Bean module, it'll open lots of new possibilities. Here is a quote about it (from its project page):

  Think of a Bean as a method to provide new types (compared to node this would be a content type) which then provides an add content interface to create as many blocks as you require (see screenshot below). The bean content can then be placed around the site just like any other block.

The video tutorial Drupal Bean module tutorial - using Bean Admin UI provides a great introduction to really understand the power of this module, and the kind of things you can do with it (by only using site building techniques, no custom coding involved). It also shows how the Bean module transforms Drupal blocks into fieldable entities.

Refer to my answers to the question about "How to control Block revisions before being published?" for more details about the Bean module (things you can also do, etc).

PS: The Bean module only started as of D7 (because of the "entities" of course that were only introduced in D7), and already has over 22K reported installs. AND it has been integrated (already) in core in D8 (refer to this issue for more information). Those who don't use it yet should definitely start looking at it in preparation of some day upgrading to D8.


Metatags trimmed body in description/summary I am using the Metatag Module. Everything works as expected, till I checked the description for each node and saw that it is empty.

Since there is no output with [node:summary] I changed it to [node:body] which works, but now the whole node is in the description field... I checked the available tokens [*:summary, *:value, *:format] with no success.

Any suggestions how to use the [node:body] in a trimmed version?

You can use any field with Metatag, so simplest way would be to use Computed Field, that

  lets you add a custom "computed fields" to your content types. These computed fields are populated with values that you define via PHP code. You may draw on anything available to Drupal, including other fields

In your custom php code for field computation, use code like this:

$body = $entity->body['und'][0]['value'];
$width = 160;
$body_trimmed = substr($body, 0, strpos(wordwrap($body, $width), "\n"));
$entity_field[0]['value'] = $body_trimmed;

It will truncate on the word boundary, giving you no more than $width characters. More about truncating on StackOverflow.

Then, simply feed this computed field to Metatag.


Views table with two columns I have 3 fields.

I've set them with view table, set their labels and they are displaying in this order:

field1 label      field2 label    field3 label

field1 value   field2 value  field3 value

They are in three columns.

How can I set them in this order like on the screenshot?

You can use Views Flipped Table module.

  This module provides a views table style with rows and columns
  flipped. This is useful for views showing few entities with many
  fields, such as product comparison.


How to override form error message Let's say I have a simple form with some id like myform. This form has field called Mobile number with id mobile_number.If a user enter mobile number less than 10, it will prompt error like It must be 10 digits.

Form validation snippet:

public function validateForm(array &$form, FormStateInterface $form_state) {

  if (strlen($form_state->getValue('mobile_number')) < 10) {
    $form_state->setErrorByName('mobile_number', $this->t('It must be 10 digits.'));
  }

}

On inspect I found something like below markups

Error message

                It must be 10 digits.

I want to manipulate markups in either of two scenarios:

1) For whole website

2) Only for form with id myform.

How can I achieve that?

I am using 8.1.3

You can use this twig to theme the status message:

status-messages.html.twig

{#
/**
 * @file
 * Default theme implementation for status messages.
 *
 * Displays status, error, and warning messages, grouped by type.
 *
 * An invisible heading identifies the messages for assistive technology.
 * Sighted users see a colored box. See http://www.w3.org/TR/WCAG-TECHS/H69.html
 * for info.
 *
 * Add an ARIA label to the contentinfo area so that assistive technology
 * user agents will better describe this landmark.
 *
 * Available variables:
 * - message_list: List of messages to be displayed, grouped by type.
 * - status_headings: List of all status types.
 * - display: (optional) May have a value of 'status' or 'error' when only
 *   displaying messages of that specific type.
 * - attributes: HTML attributes for the element, including:
 *   - class: HTML classes.
 *
 * @ingroup themeable
 */
#}
{% for type, messages in message_list %}

    {% if type == 'error' %}

    {% endif %}
      {% if status_headings[type] %}

{{ status_headings[type] }}

      {% endif %}
      {% if messages|length > 1 %}

          {% for message in messages %}

{{ message }}

          {% endfor %}

      {% else %}
        {{ messages|first }}
      {% endif %}
    {% if type == 'error' %}

    {% endif %}

{% endfor %}

I'm not sure, if you can get the form id in this template. But you can try to narrow down the kind of error message and make the modifications to this twig conditional.


Keep entity object after getTitle() method in render() method in a custom controller I've setup my controller like this:
my_controller:
  path: '/controller/{id}'
  defaults:
    _controller: '\Drupal\Mymodule\Controller\MyController::Render'
    _title_callback: '\Drupal\Mymodule\Controller\MyController::getTitle'
  requirements:
    permission: 'access content'

Now, in my MyController.php I need to load an entity object (for which {id} is the id). Unfortunately, it seems I need to load my object twice.
First, in my getTitle function because this is called first. Then again in my Render() function, which is called afterwards.
When I try to save the entity to my class as $this->entity It gets lost when the Render() function gets called. I tried to load via a constructor or create function, but these do not have access to the {id} slug in a proper manner.
What's the good practice way to make sure I need to load my entity object once for both functions?

When I try to save the entity to my class as $this->entity It gets
lost when the Render() function gets called.

Use a service. Services are singletons and when the class resolver finds an existing service it loads the instance from the container and doesn't create a new class instance:
defaults:
  _controller: 'my_service:render'
  _title_callback: 'my_service:getTitle'

For good practice this is not really necessary in this case because entities are cached in memory automatically and loading an entity twice doesn't have a performance impact.
Good practice, though, would be to load the entity via route parameter upcasting:
foobar.view:
  path: '/foobar/{foobar_placeholder}'
  defaults:
    _controller: '\Drupal\foobar\Controller\Foobar::content'
    _title: 'Oh yeah foobar'
  options:
    parameters:
      foobar_placeholder:
        type: entity:foobar

Example from https://www.drupal.org/docs/8/api/routing-system/parameters-in-routes/parameter-upcasting-in-routes


How do I alter the submit function? I want to do array_unshift for submit function in D8.
Array_unshift working perfectly for validate function but not submit function.
Below is my code:

function example_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  if ($form_id == "commerce_order_default_edit_form") {
    array_unshift($form['#validate'], 'example_manual_validate');
    array_unshift($form['#submit'], 'example_manual_submit');
  }
}
function example_manual_validate(&$form, \Drupal\Core\Form\FormStateInterface &$form_state) {
  $values = $form_state->getValues();
  dsm($values);
}

function example_manual_submit(&$form, \Drupal\Core\Form\FormStateInterface &$form_state) {
  $values = $form_state->getValues();
  dsm($values);
}

Here am altering the submit handler of the article content type while creating new article type contents

  /**
     * Implements hook_form_alter().
     */
    function example_module_form_alter(&$form, FormStateInterface $form_state,$form_id) {
   // dsm($form_id);

      switch ($form_id) {

        case 'node_article_form':      // New article nodes.
        // Attach our custom submit handler.
     array_unshift( $form['actions']['publish']['#submit'], 'example_module_node_article_form_submit');
          break;

      }

    }

    function example_module_node_article_form_submit($form, FormStateInterface $form_state) {
      drupal_set_message('custom submit ...');
    }

Source


How to create a view of duplicate entities based on title, showing the most recently created ones I have investigated a number of solutions that came close to my requirements, but not one that actually solves this, I think very common, use case:

Often after using feeds, there are duplicate entities created with the same title. Apart from the methods to prevent this from happening, I want to find a solution to list the most recently created entities of which the title already is in use.

When the most recent duplicates are listed, I want to bulk-delete them using views bulk operations.

My approach is as follows:

Create a view that lists titles of all entities of a certain bundle.
Turn on aggregation
Add the entity ID as field, with aggregation 'Count'
Add a filter: entity ID with aggregation 'Count' is 'more than 1'

The result is a list of entity titles with a column of the count of entities having that title.

Question 1:

So far so good, but I need to see the latest entities listed with an already existing title. How to make that happen?

Question 2:

I need to bulk-delete these most recent duplicates, preferably using Views Bulk Operations. However, when I add VBO(for entities) to the view, this results in an empty output. Probably because the aggregated list shows titles and not entities. This is caused by question 1 not being resolved.

EDIT:
I came up with the idea to use this view of duplicate titles, as a filter for another view that should show the latest entities having those titles.
So my 3rd question would be:

QUESTION 3: How to create a view that uses the aggregated view mentioned above as its filter, to show the entities having those titles.

I solved this using the modules

Flags
Rules
Views Rules
Rules links

with the following method:

Added a flag 'in bucket' connected to the entity
Created A views Rules display listing all entities
Created a rules link, which includes a rule with an action 'Views
loop' that performs an action on each entity in the views Rules
display. The action performed is a rules component that again uses a
views loop checking if a duplicate title is present. So for every
views list item, all views list items are compared.
If a duplciate title is found, the entity is flagged with the 'in
bucket' flag. The Rules link has as a last action the redirection to
the view that shows all entities in the bucket.
To make this more reliable, add as first action of the rules link, a
loop to remove all entities from the bucket (remove all flags).

In this way, with one click all entities are checked on duplicate titles, and the found duplciates are shown.

However, this is not the most efficient and performant way for large lists. For example when having 2000 entities, rules will need to process 2K x 2K = 4M times the comparison.
I had to limit my list to 350 items in order to have processing time of 5 minutes.
I tried to implement batch processing of the views loops, but did not succeed yet.

A more efficient way would probably be to use the view as mentioned in the question, and use that list of titles as a filter for another view which should show the most recent entities having one of this titles.
I haven't figured out how to do this yet.


error with phpunit execution: how to set PHP Test class path in phpunit.xml? I installed the conditional_fields module:

the tree is the following:

root project
  - phpunit.xml
  - web
    - modules
      - conditional_fields
        - tests
          - src
            - FunctionalJavascript
            - Unit
              - ConditionalFieldControllerTest.php

and this is the declaration of the php class I want to test:

<?php

namespace Drupal\Tests\conditional_fields\Unit;

use Drupal\Tests\UnitTestCase;

use Drupal\conditional_fields\Controller\ConditionalFieldController;

    /**
     * ConditionalFieldController units tests.
     *
     * In unit testing, there should be as few dependencies as possible.
     * We want the smallest number of moving parts to be interacting in
     * our test, or we won't be sure where the errors are, or whether our
     * tests passed by accident.
     *
     * @ingroup conditional_fields
     *
     * @group conditional_fields
     */
    class ConditionalFieldControllerTest extends UnitTestCase {
     ....
    }

In the phpunit.xml file I wrote this:

<?xml version="1.0" encoding="UTF-8"?>

<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="http://schema.phpunit.de/4.1/phpunit.xsd"
         backupGlobals="false"
         colors="true"
         bootstrap="vendor/autoload.php"
         verbose="true"
        >
    <testsuites>
        <testsuite name="drupal-composer-project tests">
            <directory>web/modules/conditional_fields/tests/src/Unit</directory>
            <file>ConditionalFieldControllerTest</file>
        </testsuite>
    </testsuites>
</phpunit>

but I get this error:

Fatal error: Class 'Drupal\Tests\UnitTestCase' not found in C:\xampp\htdocs\drupaltest2\web\modules\conditional_fields\tests\src\Unit\ConditionalFieldControllerTest.php on line 21

You must point in the phpunit.xml file to drupal's bootstrap.php file. See a working phpunit.xml file example for Drupal 8 here: http://cgit.drupalcode.org/permissions_by_term/tree/tests/phpunit.xml.dist


How do I connect to the database from a module? I would like to connect to the database from a Drupal 7 module. Currently I only have the query I want to run which is:

$query = db_select('z_lists)
->fields('country')
->condition('value', $country, '=')
->execute()
->fetchAssoc();

What I can't figure out is how to establish a connection to the default database.

Any help?

Just execute the query, Drupal takes care of everything else.

If it doesn't work, then that's for another reason.

Also, see Given that db_select is much slower than db_query, why would I want to use it?


Display all tokens programmatically? Trying to debug token I'm trying to debug creating a token. How to programmatically create a custom token in a module shows me how to create them.

Is there a way to display all available tokens? I'm trying to test if my module actually created that token.

There's a function in the token module called token_get_list() which is:

A helper function that retrieves all currently exposed tokens, and merges them recursively.

It invokes hook_token_list() for all modules so should give you every single token defined in the site.


Halt registration when certain conditions are (not) met On registration we have to look up the user-information in a remote database (JSON service), when user is not found there, or when some other error occurs, we want to halt the registration completely.

function foo_user_presave(&$edit, $account, $category) {
  $foo_bar = new FooBarSource($edit["foo_bar_invite_code"]);
  if ($foo_bar->is_valid()) {
    drupal_set_message(t('Fail'), 'error');
    //What now?
  }
}

Problem is that I fear some records are being written already in, or before hook_user_presave. From the documentation:

  A user account is about to be created or updated.

Is it safe to simply do a drupal_goto() to halt the registration? Would that cause orphaned records in the Database? What about other modules implementing this hook: would they break or be confused?

Is this hook the proper hook to determine if a user can register?

Do hook_form_alter for user registration form, and add extra validation function to the form using #validate like below.

$form['#validate'][] = 'extra_user_validation';

in function extra_user_validation set error after validation. So, that you can avoid the submit process and invoking hooks.

function extra_user_validation($form, &$form_state) {
   // Get the input values of registration form from $form_state['values']
   // Do validation & set error
}

That should work !


Image upload: Failed to open output stream I created a media entity browser and for the image upload widget i choose the DropzoneJS.The widget settings are in the image bellow, pretty standard.

And regardless of image type (png, jpg, jpeg) any image selected for upload returns with the follow error message "Failed to open output stream". I'm guessing the upload is ok but it can't be saved?

The public dir is writable (sites/default/files). This is tested successfully when for the widget type i choose normal file upload. The image is uploaded and saved successfully.

Dropzone lib is the most current one from their master branch on GIT (was previously on 4.0.1 but i thought that the version is outdated and that was causing the issue, i was wrong).

Core: 8.5

Any ideas?

In /admin/config/media/file-system look at the value of "Temporary directory" (/var/tmp or /tmp or ...) and check if that path is writable by the webserver user.


Is it possible to have nested divs in content fields on a view? I'm trying to create a view that displays certain content fields inside a div that are contained by other content fields.

For example. I am displaying an image, a title, a body, and a posted date.

I'd like to do something like this

      Title

         1/1/1999

         body text

Is this possible?

Just exclude from display all your fields.

Then, at the end, create a Global text area, where you can use tokens from your excluded fields.


How to stop cache_field table from growing? I have a website with LOTS of nodes and LOTS comments. I have lesser space in the hosting plan and don't wont to buy more. The cache_field table of the site keeps on growing due to caching.

I disabled "Cache pages for anonymous users" in admin/config/development/performance and kept
"Cache blocks" enabled. The current performance and load time with the current settings and after a cache clear is at an OK level. But still the cache_field grows. Same with the "Cache blocks" disabled.

Due to the size of the site I feel that caching of nodes and comment are not necessary.

How to stop cache_field table from growing?

More:

I'm ok with coding
I have a VPS with 20GB Disk, and 60% filled when cache is cleared. Once I cleared the cache when it was 75% filled and growing (with the cached data).
Sorry for the late data I have 512MB ram.

You could switch that cache bin so it uses something like file cache https://drupal.org/project/filecache

Also look into using memcache as that will evict the older cache data so that memcache stays within the parameters you give it.

Also consider optimizing the database; it should help to reduce the overhead
http://dominiquedecooman.com/optimize-mysql-tables-gives-35-drop-disk-usage-drupal-7-performance-tip

Finally if you really want to disable that cache you can use the DrupalFakeCache backend for those cache bins
https://drupal.org/node/797346


How to enforce edit suggestions of a post to require approval from the author of the post? I'm creating a user community site and one of the features is to reward points to registered users.

One feature I'm trying to implement is to reward points for every edit on a post only if the author accepts the edit, the user who submitted the edit should get a point only if the edit is accepted by the author of the post.

How would I implement this in Drupal 7?

Try User Points

  This module provides an API for users to gain or lose points for
  performing certain actions on your site.

  In conjunction with other modules, such as the Userpoints Nodes and
  Comments users can accumulate points for actions such as posting
  nodes, commenting or moderation duties.

  Use one of the many contributed modules to extend the functionality of
  the module to include point accumulation on page views or votes,
  upgrade roles based on point balance, or purchase goods from your
  store.

And if you need to do states of content, try Workflow

  This module allows you to create arbitrary Workflows, and assign them
  to Entities.

  Workflows are made up of workflow states. Transitions between states
  can be allowed per role. For example, a workflow with the states
  Draft, Review, and Published could be assigned to the Story node type.
  Only users with role 'chief editor' can set Stories to the published
  state. You can set up the Workflow to alter states from form, page,
  comment and a special workflow tab.

  Transitions between workflow states can have actions assigned to them.
  In our example, we could assign an action so that when the story moves
  from the Draft state to the Review state an email is sent out. Another
  action could be assigned to the transition from Review to Published so
  that the node's status is set to Published (and becomes visible on
  your website).


How to modify path alias in Drupal 8 Currently I'm on example.com/node/add page. Now I wish to add content in content type = article. What I want is, when accessing path /node/add/article, add content url should look like node/add/article?keyword='hello'

And this page still opens add node article page.

I tried changing alias at /admin/config/search/path/add

/node/add/article

to

node/add/article?keyword='hello'
But it didn't worked?

One option would be to create a custom route. You might need to use a different name than /node/add/

So in a custom module add in your_module.routing.yml

article_add:
  path: /add/article/{{ keyword }}
  defaults:
    _form: '\Drupal\your_module\Form\AddArticle::AddArticleWithYourKeyword'
  requirements:
   _permission: 'administer site configuration'

And then create a Form in your_module/src/Form/AddArticle.php

<?php

namespace Drupal\your_module\Controller;

use Drupal\Core\Controller\ControllerBase;

class AddArticle extends ControllerBase {
    public static function AddArticleWithYourKeyword($keyword) {
         //Here you can generate your form with your added keyword and return it as a render array
    }
}

This will allow you to grab a form and make edits to it, or generate an entirely custom one. In my example I made it so you pass the keyboard in the path itself not as a GET variable, but if you need you can just make the route /add/article/ and then check for GET variables inside your function.

UPDATE
Another method would be to implement the hook_form_alter function

function yourmodule_or_theme_form_node_form_alter(&$form, FormStateInterface $form_state) {
$request = \Drupal::request();
$keyword       = $request->get('keyword');
  if (in_array($form['#form_id'], ['node_article_edit_form'])) {
    $form['keyword'] = [
      '#type' => 'textfield',
      '#title' => 'keyword',
      '#default_value' => $keyword,
    ];
  }
}

Not 100% sure of the syntax but that's the general idea.


Get node's view mode within template_preprocess_page We have to get the current node's view_mode from within the mymodule_preprocess_page(&$variables) hook. When we tried the following we could not get the view_mode after performing some validation to make sure we have a node object.

In the Basic page, we have a Related Articles section that is an entity reference to the Article content type. This returns multiple nodes depending upon the page and we want to ensure the template_preprocess_node() hook is ran only once.

How can we get the current node's view_mode from within the template_preprocess_page(&$variables) hook?

Here is what we tried to do

function mymodule_preprocess_page(&$variables) {
  $node = $variables['node'];
  if(isset($node) && is_object($node) {
    // Tried printing variables but cannot find `view_mode`
    ksm($node);
  }
}

I needed to put a class based on view mode onto my pages.  I seem to remember that view mode is handled separately from the node data.  My solution was actually based on using the Display Suite submodule Switch View Mode (was already using DS).  This module creates a new base field in the entity and sets the view mode to it.

This let me use the following code to create the class:

$view_mode = $node->ds_switch->value;
if (!empty($view_mode)) {
   $variables['page_class'] .= " node-view-{$view_mode}";
}

This solution won't work with out the module.  A bit of tracing on how this works shows that it is based on using hook_entity_view_mode_alter() to get the view mode and add it to the ds_switch field on the node.

This field seems to be added by using the hook_entity_base_field_info().  See the ds_switch_view_mode.module file in the Display Suite code for details on this.


Easy database reconfiguration for migration I have build a Drupal site on my local development server and I am preparing to move it to my test server and eventually my live server.  I know where to find the database settings in my settings.php file, but there only appears to be one set of database configurations.  I would like to know if there is a good way to include three different database settings in my settings.php file, one for my development environment, one for my test server and one for my live server.  I could simply add a settings section to the file for each and simply comment out the ones that I am not using, but I would like to use an automatic solution, one that can either allow me to specify a setting for all three locations, or tries each setting until it finds a setting that works.

Berdir wrote about a very nice solution some time ago, which also made it into Drupal 8 now.

It means that you keep separate settings.php's, which are included whenever available with a small code snippet.


Undefined index error in log I'm receiving the following error message in my log

Notice: Undefined index: und in include()(line 56 of /sites/all/themes/mysite/node--recipe.tpl.php).

Here is the line off code

$node->field_recipe_skill_audio[$node->language][0]['filename']

This error message is well documented  but i've been unable to get the fixes working. I have try the following request.

$node->field_recipe_skill_audio['en'][0]['filename']
$node->field_recipe_skill_audio['und'][0]['filename']

You can avoid the notice error by checking if that field has data, e.g

if (isset($node->field_recipe_skill_audio[$node->language][0]['filename'])) {
  /* Do stuff */
}

or

if (isset($node->field_recipe_skill_audio[LANGUAGE_NONE][0]['filename'])) {
  /* Do stuff */
}


Memory size exhausted when trying to run Cron manually On my Drupal 6 website, when I run cron manually the following error message shows up:

Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 4181580 bytes) in /dirname/includes/database.mysql-common.inc on line 34

Cron is set to run every night automatically, but for a few days it was not running, so I tried it manually.

For Drupal, where should I increase memory? Should it be in settings.php, php.ini for php, or somewhere else? I'm using AWS RDS & EC2 instances.

I have this in the settings.php file:

ini_set('memory_limit', '128M');

Some help would be much appreciated.

All you need to do is increase your PHP Memory Limit from 128M to 265M

In settings.php:

ini_set('memory_limit', '256M')

For more info/other ways to change it, see Changing PHP memory limits


unlimited number of values gets really big I have created a content type with a field inside which can take unlimited number of values. eg a city with the names of its inhabitants.

The problem is that this number can get really big (i.e. 100000).

Up to 5000 people I can edit this node with no problems (apart from the fact that it takes much time to load). But above this number I just get a white screen.

What should I do in order to be able to edit (e.g. the name of a certain inhabitant) with no problems?

My UI idea would be something like pagination (loading 100 records each time I change the page), but is this possible?

Put the relationship the other way round, ie let every inhabitant be a separate entity that has an entity reference to a city.

Then you can still display them on a city content view by using an embedded view, such as EVA or Display Suite dynamic field, or using Panels. You can even embed it via a preprocess_node function using view_embed_view, and have pagination on it.

And views will use the inverse relationship just fine.

Look at the wiki entry for Cardinality (data modeling) for more information on this principle.


Why this code doesn't send an email with drupal_email()? I am developing a Drupal 6 module that should send an email after a form is submitted. So far, I wrote the following code.

function mailform_mail($key, &$message, $params) {
  $headers = array(
    'MIME-Version' => '1.0',
    'Content-Type' => 'text/html; charset=UTF-8; format=flowed',
    'Content-Transfer-Encoding' => '8Bit',
    'X-Mailer' => 'Drupal'
  );

  foreach ($headers as $key => $value) {
    $message['headers'][$key] = $value;
  }
  $message['subject'] = $params['subject'];
  $message['body'] = $params['body'];
}

/**
 * Form submission handler.
 */
function mailform_form_submit($form, &$form_state) {
  $valid_email = $form_state['values']['email'];
  $subject = $form_state['values']['Subject'];
  $body = $form_state['values']['body'];
  $params = array(
    'email'=> $valid_email,
    'body' => $body,
    'subject' => $subject,
  );

 // The first argument of drupal_mail() function must match the first part of the hook_mail function.
 // Therefore the first argument is  'mailform_form' and the the mail hook is 'mailform_form_mail'
 // For more infoormation see:
 // - http://api.drupal.org/api/function/drupal_mail/6
 // - http://api.drupal.org/api/function/hook_mail/6
 if (drupal_mail('mailform','reply', $valid_email, language_default(), $params, $from, TRUE) {
    drupal_set_message('An email has been sent to ' . $valid_email);
  }
  else {
    drupal_set_message('There was an error sending your email');
  }
}

Using this code, I can get the values after a form is submitted, but the mail is not sent out.

Is there anything wrong with the code? The module machine name is mailform.

The answer's in your comments

//Therefore the first argument is  'mailform_form'

But you're using the string mailform as the first argument.

If your module is called mailform_form as your comments suggest, use this code:

drupal_mail('mailform_form','some_mail_key', $valid_email, language_default(), $params, $from, TRUE)

If it's named mailform, use your original call to drupal_mail, but change the name of your hook function to the correct one:

function mailform_mail($key, &$message, $params) {


How to improve CDN on a drupal site? I'm checking a drupal site with YSlow and I get a "Grade E on Use a Content Delivery Network (CDN)" with this message:

  "There are 43 static components that are not on CDN."

Just wondering if the cdn will help to improve this situation.

It will only help if your files are actually on a CDN...if they are, then install that module, set it up, and you should see some performance benefits.

If not, then installing it will have zero effect, except to add a very slight extra overhead to your page build (when the module is included/hooks are run/etc).


Is there an existing D7 UI solution to control the content of emails sent by the system? On most of the projects I am working on, I have set up several different emails with the HOOK_mail. On top of that you have the default user emails provided by Drupal.

What I am looking for, is an admin UI that would list existing emails and allow admins to edit their content. A bit like what you can do with the default user emails except that I want to be able to use the wysiwyg editor as well.

I started building something custom, but I wonder if there is already something out there. I guess the Message module could potentially do the trick for custom emails but I have never seen it implemented this way.

Try out the Mail Editor and see if that's what you are looking for


User login link is always visible in menu I have created user login link in the user account menu but the link is visible all the time(even for logged users). The user profile menu link and the user logout links are displayed properly(they are added by the user module).

My link definition doesn't differ from the user's module link definitions in any way but still this happens. Also the user.login route has proper requirements so this should just not happen but it does.

This is how user module defines menu links:

user.page:
  title: 'My account'
  weight: -10
  route_name: user.page
  menu_name: account
user.logout:
  title: 'Log out'
  route_name: user.logout
  weight: 10
  menu_name: account

This is how I define my login link:

user.login:
  title: 'Log in'
  weight: -10
  route_name: user.login
  menu_name: account

This seems to be a bug, /user/login should not be accessible as an authenticated user, but it redirects to user/1.

Edit: Discussed this with @dawehner and we figured it out together. This is egression: Do not bypass route access with 'link to any page' permissions for menu links

Open a bug report. This might actually a be a pretty serious security issue, looking at AccessManager, I don't understand why that starts with an allowed() state,LoginStatusCheck returns neutral, that is merged together to an allowed().


Facets and Apache Solr in Drupal 7 - Clicking Facets results in no results being show I'm having a bit of an issue with Facets and Apache Solr, I'm not sure whether the fault lies with Solr or the Facets API.

I am using Solr as my search engine and I get results being shown when searches are performed, also shown are the amount of matches in specified fields/facets.

E.g. I search for 'content' - there are numerous values for 'content' within different categories such as 'category1', 'category2'

The search result shows as:

category1(5)
category2(7)

Implying there are 5 results in the facet category1, and 7 results in the facet category2, these are also links, however upon clicking these links the search shows as "no results found". Odd behaviour, has anyone experienced anything like this before? if so any pointers on where to look in order to resolve the issue?

I'm hoping this question is quite clear, if not just ask and I'll try provide some more details.

Thanks, Dan.

This is very odd behaviour, can you ensure you are:

running the latest version of apachesolr (3.6.1)
running the latest version of the apachesolr module (7.x-1.1) OR search_api module (7.x-1.3)
are running the latest schema.xml and solrconfig.xml (hopefully the 3.x version)

Also, try dropping and re-creating the entire index, this normally addresses more problems.


How do I upgrade drush from 3 to the latest release? On my debian 6 server, I used apt-get to install drush.  However, it looks like it downloaded drush version 3.  I want to upgrade to the latest stable release of drush (which I believe is drush 5).  How can I do this?

The short answer is on the Drush project page under the heading Install/Update - Unix/OSX:

pear upgrade drush/drush

I first had to install PEAR, but that should not be an issue.


Drupal commerce - purchase a product at registration I'm trying to use Drupal Commerce for a subscription site that will have only one product to purchase - a subscription to a service.

I'd prefer if a user could either do product subscription as a part of user registration, or immediately be redirected. Currently I'm trying the redirection with a rule to a custom order page (which I'm creating with rules), however rules doesn't seem to know what the order id is of the created entity.

So I'm either looking for a way to fix that, or another solution that I may have missed. Basically I want registration to be the easiest thing possible.

Figured this out - apparently you have to add the action, "save entity" after you create it, and also force it to save immediately.


How can I access profile fields with a % variable in Drupal Actions? I have an action setup in drupal to e-mail me when a new user registers for the site. Right now it is only telling me their user name (%username). Is there a variable that can access added fields so I can get their real name (First Last), or another way to add this info to the action message? So instead of my new user action having a message like:

"%username created an account" -> "jschmoe created and account"

I could have:

"%first_name %last_name (%username) created an account" -> "Joe Schmoe (jschmoe) created an account".

I'm using Content Profile module for the first and last name fields, though have few enough users at the moment that I could switch to Profile module fields.

You could try using the Realname module together with Token and Token Actions.


Why doesn't All Products show all my products in Drupal Commerce? I've set up a Drupal Commerce site without the sample products, and have created new products in a new product displays that I've created.

I've created Main menu items for the new displays, and the products show up when these menu items are clicked, but All Products shows no products.

How do I make All Products work? Is there a special View for this?

I know this is old, but I recently encountered the same issue. Bojan Zivanovic's suggestion ave me an idea though. The search index indicated all products were indexed, but clearing the search index and rebuilding it resolved the issue.


Images are refering wrong path on node import i import a node in my site using paste code method. after imported some images are refering wrong path ("https://www.example.com/sites/default/files/styles/large/public/test.png?itok=a2KPyReV"). but the image is inside of the below path ("https://www.example.com/sites/default/files/test.png")

The wrong path belongs to an image derived from image cache. It's the default "large" image style defined in admin/config/media/image-styles. You can try to rebuild the image cache, but success depends a bit on your "paste code method" which i'm unfamiliar with...


Find out module versions through database dump I've got a dump from my Drupal database that I've created with Backup and Migrate.

I want to find out which versions of the modules ctools and Panels have been in use.

Where do I have to look? What do I have to search for?

Import the dump file into mysql database. Create a new database in your localhost and import the db using your backup file
Browse System table.
Run below query

SELECT info
FROM  system
WHERE  filename LIKE  '%ctools.module%'
ORDER BY  system.name ASC
LIMIT 0 , 30
You will see version information in info column. Search for "Version". Above information is serialized.
For Example, As you see below "Ctools" module is 6.x-1.11 version. You can do same for panels module by changing query.


How to trigger function on vocabulary terms update? Is there a hook that being triggered when any term in taxonomy vocabulary is edited/added/deleted?

I'v tried to use hook_taxonomy_vocabulary_update but no success so far.

Oh, I probably should use term_update for this:

hook_taxonomy_term_update($term){
if ($term->vid == $vid){
// Action
  }
}

Or Rules module


Reducing Number of Fields in Content Type Context:

I have a product content type on Drupal 7 with >100 fields, and there are >7000 products, all with several revisions. Our client keeps requesting that we add and remove fields, which is quite painful and takes several tries to successfully complete due to mysql having a conniption.

The go-to strategy has been to increase the RAM on the server, but we are hitting a cost wall and this bothers me as a developer since we are just deferring dealing with the problem.

Comedy Option:

The majority of these fields are specifications which are never related, filtered or displayed outside of the detail view. Could I reasonably create a JSON product_spec field that contains all of these spec fields and write custom modules to display them on the detail/spec screens, allow editing through the API, and allow editing them on the admin interface?

Is there an existing module that does something similar? Would entitycache be a much more practical option?

This is really interesting and, whereas the suggestions in the other question are really good as pointed out by the comment above, I don't really think it's practical to give up on the Field UI for this (like mentioned in the other question).

Let me explain:

Creating a custom field is really easy, there's a good example in Panopoly Widgets for the dashboard widget, which has a custom field for the Spotlight widget.
Creating a custom entity isn't so bad either but creating every single field using Form API should be out of the question

The only plausible solution that I can think of would be to implement hook_field_storage_info() and create a new Field API storage backend that uses a better table configuration.

If you look at field_sql_storage.module in core, it's a pretty concise module that provides the one field per table storage backend, I'm sure with some hacking around you could create a new backend that uses one table per entity and stores each field in a new column there (kinda like D6 CCK with cardinality 1 fields).

You would have to be constantly altering the table schema whenever new fields are added (which should be fine). This might be the place to do it: hook_field_storage_create_field().

It's pretty theoretical but I think it'll work... the beauty of this approach is that you can still use Field UI for everything as usual.

Caveat: You're gonna have to figure out how to handle complex fields or multiple cardinality (hint: more columns?)

PS - Knowing of the frequent schema changes, you wanna make sure you have backups/concurrency for peace of mind.

Good luck and if you get this working I'd like to see it! :)


Open Atrium permission issue I've added new roles and give it to them a permissions to create content and for some content... and fields but not work with open atrium.

Please help!

My guess is that you're using the general drupal roles and permissions rather than the organic_groups ones.  Start by reading https://www.drupal.org/node/2340349, and then if you are still stuck, clarify exactly roles and permissions you've been modifying.


Drush not updating Drupal core I've been wrestling with this since yesterday and have reinstalled drush 3 times, rebooted, restarted mysql(mariaDB) and a few other things but nothing works. I'm trying to update my core from 7.14 to 7.32 and really want to do it with drush instead of manually. The only thing I think might be causing this is that I am on Debian and my sites directory is a symlink from /usr/share/drupal/sites to /etc/drupal/7/sites or that I have drush installed for root only(composer and drush files in /root)

When I try and update the core with:

drush up drupal

I get back:

Update information last refreshed: Fri, 10/24/2014 - 15:01

Name    Installed Version  Proposed version  Message

drupal  Unknown            Unknown           Specified project not found

No code updates available.

Tried clearing my drush cache to no avail and when I check for releases with drush rl it manages to successfully lists the 7.32:

Project  Release  Date         Status

drupal   7.x-dev  2014-Oct-19  Development

drupal   7.32     2014-Oct-15  Supported, Recommended, Security

I maintain a few Drupal sites with drush and have never had this problem before but this is my only server with Debian so maybe that has something to do with it. I've read a lot of the threads about issues resembling this going back all the way to 2011 but nothing seems to fix my issue.

If anyone can help then thanks and if not I guess I'll have to manually upgrade the core.

Try drush pm-refresh, and then run drush pm-updatecode again.


How can I stop the Devel module from generating blog/forum entries for Anonymous user? I'm using Devel's generate content feature to generate Blog/Forum entries for a site I'm working on and funny enough, I get to have a blog post by an anonymous user or forum topic by an anonymous user.

How can I stop Devel from doing this? I've only given Authenticated Users/ Administrators the permission to create a blog post or forum topic but still it generate for anonymous user. How can correct this?

The Devel module doesn't have options to decide to which users the generated content is assigned, but you can create a custom module to limit the users to which the created content is assigned. You need to:

Implement hook_form_alter() to add the extra form fields necessary to select which users accounts should be used in the form generated by devel_generate_content_form()
Replace the form submission handler with one that generates the content using the user accounts selected in the form

You can use the existing form submission handler (devel_generate_content_form_submit()) as guideline to build your submission handler.

function devel_generate_content_form_submit($form_id, &$form_state) {
  module_load_include('inc', 'devel_generate', 'devel_generate');
  $form_state['values']['node_types'] = array_filter($form_state['values']['node_types']);
  if ($form_state['values']['num_nodes'] <= 50 && $form_state['values']['max_comments'] <= 10) {
    module_load_include('inc', 'devel_generate');
    devel_generate_content($form_state);
  }
  else {
    module_load_include('inc', 'devel_generate', 'devel_generate_batch');
    devel_generate_batch_content($form_state);
  }
}

Unfortunately, devel_generate_content() doesn't allow to select the user accounts to use as authors of the nodes. This means you need to write all the code yourself. The bright side is that the function that in your module replaces devel_generate_content() is very similar to that function with a single difference: the function to call instead of devel_generate_content_pre_node().

function mymodule_generate_content($form_state) {
  if (!empty($form_state['values']['kill_content'])) {
    devel_generate_content_kill($form_state['values']);
  }

  if (count($form_state['values']['node_types'])) {
    // Generate nodes.
    mymodule_generate_content_pre_node($form_state['values']);
    $start = time();
    for ($i = 1; $i <= $form_state['values']['num_nodes']; $i++) {
      devel_generate_content_add_node($form_state['values']);
      if (function_exists('drush_log') && $i % drush_get_option('feedback', 1000) == 0) {
        $now = time();
        drush_log(dt('Completed !feedback nodes (!rate nodes/min)', array('!feedback' => drush_get_option('feedback', 1000), '!rate' => (drush_get_option('feedback', 1000) * 60) / ($now -$start))), 'ok');
        $start = $now;
      }
    }
  }
}

function mymodule_generate_content_pre_node(&$results) {
  // Get user id.
  $users = mymodule_get_users($results['exclude']);
  $results['users'] = $users;
}

function mymodule_get_users($exclude) {
  $users = array();
  $result = db_query_range("SELECT uid FROM {users} WHERE uid NOT IN :exclude", 0, 50, array(':exclude' => $exclude);
  foreach ($result as $record) {
    $users[] = $record->uid;
  }

  return $users;
}

The code I shown assume you add a form field (exclude) that contains the user ID for the user accounts that should not be assigned as authors of the generated nodes.

Probably, you also need to write the equivalent of devel_generate_batch_content(), which is the other function used to generate content, for your module.

Notice that the Devel generate module is used to generate content for developing/testing purposes. It should not be used to generate content for a production server/web site. That is the reason why there aren't too much options for the content to generate.


How do I create a file object from a local file? I am trying to attach a file in the custom module's directory to every new node created for a content type. How do I create the file object? The following code gives me an error.

$uri1  = file_unmanaged_copy('checklist1.pdf', 'public://checklist1.pdf', FILE_EXISTS_REPLACE);

$file1 = File::Create([
    'uri' => $uri1,
]);
$file1->save();

The error I get is the following one:

  The specified file checklist1.pdf could not be moved/copied because no file by that name exists. Please check that you supplied the correct filename.

To add, this code is in the module file inside a hook.

You need to specify the path to your module:

$module_path = drupal_get_path('module', 'module_name');

$uri1  = file_unmanaged_copy("$module_path/checklist1.pdf", 'public://checklist1.pdf', FILE_EXISTS_REPLACE);


theme still use caching even when flushed cache and using devel I am having a lot of issues with CSS editing on my site! Some colors don't change and I have tried the following to no avail:
-flush all caches
-performance - development: disabled all caching and "Aggregate and compress CSS files"
-Devel module "Rebuild the theme registry on every page load"

I also removed the .css file and my page will still load with old colors in the body background and 2 other divs!
Any help would be greatly appreciated as this is keeping me from opening up my site!

Since it sounds like you've got all the Drupal-related items checked, perhaps it's worth a shot in the dark...

Pull up the site in Chrome and inspect the element that's supposed to have the updated colors (right click and select "Inspect element"). This may reveal one of two things:

Click the "Computed" tab in the right-hand column. Is your color change being overwritten by a more specific declaration? (eg: #foo .some-class { ... } will supersede .foo-class .some-class { ... } regardless of the order in which they appear)
Perhaps you've been editing the wrong file? I know I've done it before...  Click the Sources tab and make sure the page is loading the file you expect it to load. Make some random changes, reload and check that those changes show up.

Hope that helps.


How to add options to a select list of a content type? I built a module that creates a form and let the user to add a variable called unit into database. Now this unit should be the options of select list of a content type. the form id of the content type is phone_book_node_form, but the problem is I can't add options to the select list. this is the firebug output of the form (content type)

the name of the select list field is field_phone_yegan. I tried this function in template.php

function MYTHEME_form_alter(&$form, &$form_state, $form_id){
    switch ($form_id){
        case 'phone_book_node_form':
            $form['field_phone_yegan'] = array(
                '#options' => array('yes'=>t('yes'),'no'=>t('no'))
            );
            break;
    }
}

nut nothing was added to the select list. I also tested

$form['edit-field-phone-yegan-und'] = array(
                '#options' => array('yes'=>t('yes'),'no'=>t('no'))
            );

$form['field_phone_yegan[und]'] = array(
                '#options' => array('yes'=>t('yes'),'no'=>t('no'))
            );

but it didn't work. How do I can add options to this content type select list?

It sounds like using a taxonomy would be more appropriate here. Taxonomies allow lists and terms can be automatically created from user input, in this example something like the Select (or other) module would be of use. Details from project page:

  Provides a new Forms API element which is a select/radios/checkboxes element that has an 'other' option. When 'other' is selected a textfield appears for the user to provide a custom value.


Why variable_get() returns all values of checkboxes list, even if checkbox is not selected? I have checkboxes list in system settings form:

$form['mymodule_menu_perm_menus'] = array(
    '#type' => 'checkboxes',
    '#title' => t('Menus'),
    '#options' => menu_get_menus(TRUE),
    '#default_value' => variable_get('mymodule_menu_perm_menus', array()),
);

return system_settings_form($form);

I submit this form with two checkboxes selected.

But on other page variable_get('mymodule_menu_perm_menus') return all values :/

Clearing cache doesn't help

Because Drupal doesn't actually filter out empty checkboxes values, it sets them to zero. I think this is so you get an accurate representation of what options were available when the form was submitted, and what was actually chosen by the user.

It's easy to get the filtered array though, using array_filter():

$values = array_filter(variable_get('mymodule_menu_perm_menus', array()));


How can I access webform submission values from webform-confirmation.html.twig I have a webform with Inline confirmation, AJAX enabled and saving of submissions disabled.

Is it possible to access the submitted values from the webform-confirmation.html.twig template?

I know that I can do this by adding token values to the Confirmation message in the WebForm UI. But I prefer to solve this by modifying the template.

My motivation for doing this is that I need to add a javascript snippet after the user has submitted the form. And I want to do it at the template level because I have a larger number of forms where I need to add the javascript snippet.

Cheers

Stian

You can access submissions using 'webform_submission' variable. I know the webform-confirmation template file doesn't mention that variable but, if you look closely to the controller you see there additional variable being passed to this template.

N.B on your form setting make sure to set confirmation type to be "age (redirects to new page and displays the confirmation message)"

And always the latest one on the array is your last submission.


"jquery_file_upload.id is part of the primary key but is not specified to be 'not null'" I have installed the jQuery File Upload module, and I get the following error:

  jquery_file_upload.id is part of the primary key but is not specified to be 'not null'

What does that error message mean, and how can I resolve it?

The error message is about the schema currently used by the module, which defines the primary key using the following code.

function jquery_file_upload_schema() {
  $schema['jquery_file_upload'] = array(
      'description' => t('Stores files sizes for each user.'),
      'fields' => array(
          'id' => array(
              'description' => t('auto increment'),
              'type' => 'serial',
              'size' => 'normal',
          ),
          'uid' => array(
              'description' => t('registered user'),
              'type' => 'int',
              'unsigned' => TRUE,
              'not null' => TRUE,
              'default' => 0,
          ),
          'file_name' => array(
              'description' => t('File Name.'),
              'type' => 'varchar',
              'length' => '255',
              'not null' => TRUE,
          ),
          'file_size' => array(
              'description' => t('File Size.'),
              'type' => 'float',
              'size' => 'big',
              'default' => 0,
          ),
      ),
      'primary key' => array('id'),
  );
  return $schema;
}

The correct definition would be the following one, as the fields that are part of the primary key should be declarated as "NOT NULL."

function jquery_file_upload_schema() {
  $schema['jquery_file_upload'] = array(
      'description' => t('Stores files sizes for each user.'),
      'fields' => array(
          'id' => array(
              'description' => t('auto increment'),
              'type' => 'serial',
              'size' => 'normal',
              'not null' => TRUE,
          ),
          'uid' => array(
              'description' => t('registered user'),
              'type' => 'int',
              'unsigned' => TRUE,
              'not null' => TRUE,
              'default' => 0,
          ),
          'file_name' => array(
              'description' => t('File Name.'),
              'type' => 'varchar',
              'length' => '255',
              'not null' => TRUE,
          ),
          'file_size' => array(
              'description' => t('File Size.'),
              'type' => 'float',
              'size' => 'big',
              'default' => 0,
          ),
      ),
      'primary key' => array('id'),
  );
  return $schema;
}

There is nothing you can do, if not opening an issue report for the module, in its issue queue. Be sure there isn't already a report about that.


How do I set up a shipping condition that accesses the value of a specific field in product? I have a term reference field in product called "Weight" with values "Light", "Medium" & "heavy". I am using flat rate shipping service and trying to check the value of "Weight" field in Calculation rules.I know that I need to expose it by using "entity has field" but I end up having

commerce-line-item:order:commerce-line-items:0
commerce-line-item:order:commerce-line-items:1
commerce-line-item:order:commerce-line-items:2
commerce-line-item:order:commerce-line-items:3
commerce-line-item:order:commerce-line-items:0...
commerce-line-item:order:commerce-line-items:1...
commerce-line-item:order:commerce-line-items:2...
commerce-line-item:order:commerce-line-items:3...

I was able to get to the weight field by using any of them and then did a Data Comparison

commerce-line-item:order:commerce-line-items:0:commerce-product:field-product-weight

this condition worked ok first time but not after that. can anyone please help me on this or if you think of another solution please let me know. Thanks

What you can do is loop through the line items and each line item is passed through a rule component where you can check the line item's weight. If you want to get the shipping fee for line item, you would need to set a rule set component. If you just want the component to provide the weight of the line item, a rule component will do.

I am not sure what you are trying to achieve with the rule or how your flat rate shipping works. Are you looking for the heaviest weight present in the order and apply to the order the shipping fee of that weight? Or does the fee accumulate according to how many line items and their weight? Regardless of how your shipping rate works, it's still the same concept: Loop through the line items. Pass the line item to a rule component that checks the weight of the line item.

The rule will look like this (assuming your shipping condition is: if product is light - add 0.25$ to shipping fee, 0.5$ for medium, and 1$ for heavy.)

Rule:

  /* ACTIONS*/
  // Add a variable: total_shipping_fee; set to 0.
  // Loop through line items
     // For each line item, trigger get_shipping_fee component passing line item and providing the prod_shipping_fee for the product
     //  Calculate value: total_shipping_fee + prod_shipping_fee
  // Set shipping fee to total_shipping_fee

For the rule set component: (get_shipping_fee), create three rules that checks the weight of the product; each rule returning or providing the shipping fee. For instance:

/* SETTINGS */
Parameter: line_item
Provided: shipping_fee

/* CONDITIONS */
// If product is light

/* ACTIONS */
// Set shipping_fee to 0.25$

The provided variable or variable returned by the rule component depends on how your flat rate shipping works. Also, you might need to pass another variable to the rule component.

Also, if you're new to drupal and rules, you can read the documentation to make it easier for you.

Hopefully, this will give you ideas to the actual solution of your problem.


How can I create a field to hold data on users' countries and states? I'm trying to create a content type that has multiple countries available to be selected and then multiple states/territories within those countries based on the country, but I'm not sure how to best accomplish this.

When a user is creating a piece of content they need to be able to select their country, then based on the country they select, they can select their state or territory with only those states/territories for that country available as options. I have two such countries that will have multiple states/territories - the U.S. and Canada.

I'm creating a text field using the field module that lists all the U.S. states when a parent item is selected using a list (text) and a "select text" drop-down. I also need to create a way to present the user with the Canadian territories when selecting Canada as the territory.

Right now I have two fields - "Country" and "State". Can you recommend the best way to accomplish presenting the user with the correct options for the state/territory based on their country selection? I'm drawing a blank on this one.

In Drupal 7 you should use the dedicated addressfield module for that purpose.
The composite address field provides a country drop down box with other address fields such as state loaded via ajax depending on the selected country.
USA

Canada

It's a requirement of the Commerce module for address selection.
You can hide some of the address sub-fields if needed.


Commerce - How to hook into ajax call on commerce cart form variation change When you change a product attribute on a product display page, ajax loads the fields of the new product.

See here: http://demo.commerceguys.com/ck/tops/drupal-commerce-hoodie

By changing the size, color, etc, you trigger an ajax call that changes the fields such as SKU, images, etc.

My question is, how do you add additional markup to be updated on the attribute(form field) change?

By default, the form will update all fields printed in the template in this format.

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

This wraps markup around the price with the following classes.

commerce-product-field commerce-product-field-commerce-price field-commerce-price node-880-product-commerce-price

Im assuming the ajax call is replacing fields by looking at this markup.

So how do I add additional markup, that printed in the node template, to be replaced with ajax when a form field is changed.

Im not sure what to hook into.

Many thanks.

There's a hook for that: hook_commerce_cart_attributes_refresh_alter. This is invoked when the variation is selected by the user and reacts to changes in the cart widget.

It gives you the chance of using ajax commands, so you basically have the complete control over elements and behaviors, there's an excellent tutorial in here: https://drupal.stackexchange.com/a/73325/2322

Also, a couple of examples, Commerce itself invokes the hook from the cart module
and there's this sandbox module called Commerce Single Page Checkout that uses the technique for adding a view on the refresh event using ajax_command_replace.


Adding and reading a static HTML page with The requirement is that the user can upload a folder, containing static HTML, CSS, JavaScript files, and a link is generated.

So, then I don't want to have any drupal styling whatsoever.

My initial idea

Set a specific content type, allow multiple file upload
Upload all the files to a specific directory via some kind of rules
Access the page at www.example.com/sites/default/files/MYFOLDER/index.html

Do you think this is feasible approach?

File (Field) Paths allows you to specify path using node fields. Using it, you can have node's files in directories like sites/default/files/custom_pages/[nid]/[node_title]/
Just make sure to put .htaccess inside custom_pages folder, one that will allow direct html serving.

Then you can generate link using the very same tokens.


Sharing Global Menu Links Menu to subsites How to present a global menu across multiple subsites

I've been trawling the Drupal site for answers to this and because I'm only 4 days into my Drupal 7 adventure I'm sure half my battle is finding the right words to say to the community to get what I'm asking for.

This question seems to hit the mark http://drupal.org/node/1428516

But the only answer is something about Domain Access http://drupal.org/project/domain but that looks pretty complicated when all I want to do is to splat a small block of html at the top of all my sites.

So I'm thinking the architecture would be something like this.

master site
+ - menu-global-menu
+ - global-menu-module (looks in master site db for menu-global-menu
                        and fills variable $global_menu)
+ - corporate theme (requires global-menu-module)
|
+ - > subsite 1
+ - inherits corporate theme
|
+ - > subsite 2
+ - inherits corporate theme

Does this make sense? Or should I be achieving this some other way?

So I think I've gone a long way to achieving this.

In the setting.php file of each site I declare a Data Connection called globalmenu that point's to the database belong to the menu's management site.

I make the menu and get the machine name for it; in my case menu-global-menu.

In my page.tpl.php of my theme I have included this

  <?php
  if ($global_menu){
  print($global_menu);
  }
  ?>

My module

function global_header_preprocess_page(&$variables, $hook) {

 $query_options['target'] = 'globalmenu';

 $query = db_select('menu_links', 'p', $query_options)
    ->fields('p')
    ->condition('menu_name', 'menu-global-menu', '=')
    ->execute();

 if($query->rowCount() ==   0) {
    print '
No Global Header Configured!

Check the Global Header Module Help for details

';
}

 $links = array();
 $markup = "

";

 foreach ($query as $item) {
    $markup = $markup ."
link_path."' class='global-link'>".$item->link_title."
";
 }

 $markup = $markup ."

";
 $variables['global_menu'] = $markup;
}

There's probably a much better way of doing the markup but I'm a noob so I guess someone will correct me.


How to import node view count with Feeds and Statistics module? After enabling drupal 7.x core Statistics module, on the feeds node processor mapping page, I still cannot find any suitable target to map.

This isn't currently a feature of the feeds module. You could write a module that implements hook_feeds_after_save() to create the needed database records.


Approval required for all comments apart from on the forum We need to allow all forum comments to be published automatically, however any comments to articles or any other content type will require approval before being published.

Unfortunately Drupal seems to only have a single permission "post comments without approval" which applies to both the general comments for nodes and also the comments for the forum topic (yes I know they are still nodes)

Is there any easy way round this? I was thinking maybe a rule but it seems a little over the top, surely this must be a common complaint but my searches didnt bring back anything helpful...

I know this is the reason advance forum modules recommends installing nodecomment.   You can select which content type's comments to be nodes.  Select Form topics.   In nodecomment content type select uncheck publish from the publish options.   Now every comment publish will be unpublish by default


Ajax on textfield keeps me from typing I have the ajax property set on a form element.  Its like an autocomplete except it displays the results in a div.  It works great except the textfield gets greyed out by drupal during the ajax call.  I end up having to type one character at a time between ajax calls.  Is there a way to fix this?

Here's the code for my element:

$form['auto_complete'] = array(
  '#title' => 'Auto Complete',
  '#type' => 'textfield',
    '#ajax' => array(
      'callback' => 'k_test_ajax',
      'wrapper' => 'searchresults',
      'method' => 'html',
      'event' => 'keyup',
    ),
 );

Your best bet is to either

use the #autocomplete_path and tweak the behavior by overriding the JavaScript (prototyping)
Don't use the ajax framework, but create this with custom JavaScript.

The AJAX framework can do a lot of things for you, and works very great for most things, but there are some cases like this one, where it doesn't work as intended. The problem is that you will get too many ajax requests at once if you do one for every keyup event, which most likely will mess things up if you could actually do it. This is why you need an autocomplete functionality which usually caches the results for improved performance.


where in database is renamed login for 'Rename Admin Paths" A little embarrassing - I've lost/forgotten the login page for a Drupal 8.9 website. It was renamed using the module "Rename Admin Paths."
I've gone to the module page at drupal.org and looked through issues and comments, but none of the solutions I found will work.
This site is unable to install Composer or Drush at this time, so I can't use any method there. Another suggestion was to search the 'variables' table - but that was specific to D7, I believe. I don't see that table.
I've commented within their page hoping to find the answer, but maybe someone here happens to know the answer?

Look in the config and key_value tables for "rename_admin_paths.settings"


Pagination in external api consume custom module I created a custom module in order to consume an external api call in my drupal project following this question.
The module is working fine, but I need to have a pagination in the received results which will pass as a variable in the api call:

http:/example.com/api.ashx?q=documents&page=1

How is possible to achieve that? In case I receive all the data from the api is it possible to "separate" them somehow with pagination operation?

Thanks in advance

Is responsability of the external API paginate the results with the page parameter. If it was designed for such thing.

Then you only need to request the appropiate page.

If in another hand if you receive all the data, then, you only need to divide it.

Assuming in the referenced question that $data contains all rows, you need to divide the array (array_chunk() maybe).


How to disable creation of node revisions on programmatic node update? I added a field of type computed field to existing nodes. It's required to re-save the nodes to set/update computed field values. As I do not want to update the changed timestamp I decided to not use the views bulk update to resave content. The easiest way would be a drush script, that way I can re-save content whenever it is necessary.

My first problem was that I was not able to leave the changed time unchanged on update ($node->save()). But I found that it could be re-set on a second node save.

My problem is that on each node save a new revision gets created. The node type is revision-able and beside the core module content moderation is enabled. I would appreciate any help on how to prevent the creation of revisions.

This is my current drush script in custom_helper.drush.inc:

<?php
/**
 * @file
 * Provides drush command to update all articles.
 */

use Drupal\node\Entity\Node;

/**
 * Implements hook_drush_command().
 */
function custom_helper_drush_command() {
  $items = array();
  $items['custom-resave-content'] = array(
    'description' => dt('Resaves all article entities.'),
    'options' => [
      'types' => dt('Coma separated list of content type to be resaved.'),
      'nids' => dt('Coma separated list if node ids.'),
      'field' => dt('Machine name of computed field to be updated.')
    ],
    'aliases' => array('custom-rc'),
  );
  return $items;
}

/**
 * Moves paragraphs into one paragraph reference field.
 */
function drush_custom_helper_custom_resave_content() {
  $nids = _convert_csv_to_array(drush_get_option('nids', []));
  $types = _convert_csv_to_array(drush_get_option('types', []));

  if (!$nids || $types) {
    // Get an array of node IDs.
    $query = \Drupal::entityQuery('node');
    if ($types) {
      $query->condition('type', $types, 'IN');
    }
    if ($nids) {
      $query->condition('nid', $nids, 'IN');
    }
    $nids = $query->execute();
  }

  // Load all the nodes.
  if ($nids) {
    $field_name = drush_get_option('field', '');

    $nodes = Node::loadMultiple($nids);
    foreach ($nodes as $node) {
      $entity_type = $node->getEntityType();
      $original_changed = $node->getChangedTime();
      if ($entity_type->isRevisionable()) {
        $node->setNewRevision(FALSE);
      }

      // Force update of computed field.
      if ($field_name) {
        /** @var \Drupal\Core\Field\FieldItemListInterface $items */
        $items = $node->get($field_name);
        if (empty($items[0])) {
          $items->appendItem();
        }
        $items->preSave();
      }

      // Save the updated computed field value.
      $node->setChangedTime($original_changed);
      if ($entity_type->isRevisionable()) {
        $node->setNewRevision(FALSE);
      }
      $node->save();

      // Reset changed time to original value.
      $node->setChangedTime($original_changed);
      if ($entity_type->isRevisionable()) {
        $node->setNewRevision(FALSE);
      }
      $node->save();

      $changed_after = $node->getChangedTime();
      drush_print('node:' . $node->id() . ':' . $original_changed . ':' . $changed_after);
    }
  }

  drush_log(dt('Resave finished.'), 'ok');
}

Right now, this isn't possible with content moderation installed without doing backflips such as replacing the moderation handler for the node entity type.

This is however being worked on! Here are some issues which are relevant to the problem you are having:

Allow 'syncing' content to be updated in content moderation without forcing the creation of a new revision
Allow the ChangedItem to skip updating
Better describe how SynchronizableInterface should be used for content entities

The proposal is essentially two pronged:

Better describe to callers of SynchronizableInterface::setSyncing() when it's appropriate to mark an entity as "syncing".
Encourage implementors of entity lifecycle hooks to reduce disruptive side effects while entities are syncing.

Quoting myself from the issue:

  IMO, the current 'syncing' status for content entities is shaping up
  into a flag to indicate that a save is happening under conditions
  which are outside of a typical user initiated content update and that
  as much as possible, side effects from that save should be limited.
  Examples might be:

  Deploying a workspace.
  Batch updating old revisions.
  Running an update from a migration.

  After defining some of those scenarios it becomes
  easier to rationalise eliminating some of the side effects that have
  been discussed (CM revision handling + changed timestamp).

In your case, you are attempting to resolve integrity in your model by bulk updating existing entities/revisions, it's outside a standard editorial based content change, so in my opinion it fits very clearly within the semantics that are being proposed for content entities and this interface. So with a few of these patches applied your code sample might look like:

  $entity->setSyncing(TRUE);
  $node->save();

And then the changed timestamp wouldn't be updated and content moderation wouldn't force the creation of a new revision.


users not able to post to discussion board I have a simple forum in Drupal 6 that has 3 containers.  From the admin perspective I can easily post a comment in either of the 3 containers.  However authenticated users are unable to post to any container.  The drop down box that allows you to select the container within the forum does not appear for authenticated users. I have attached a screen shot showing the difference between the two.  Yes, user permissions are all turned on to enter content for the discussion board.  Any suggestions on how to fix this issue?

I don't have a Drupal 6 site handy to check this but the problem should be caused by either authenticated user permissions (global Drupal permissions) or if you are using field-specific permissions, that would also prevent a user from seeing that field. Please check what permissions authenticated user has for taxonomy related actions (I'm assuming you are using taxonomy to display forum containers?)


Alter entity_translation vertical tab access How can you set #access to false for the vertical tab "Translation" (entity translation) on the node edit form?

When using entity translation and a user has the permission to edit a node and edit translations, a new vertical tab is injected in the node edit form:

  Translation
  Translation is published. Do notflag translation as outdated
  [x] This translation is published
  [ ] Flag translation as outdated

Since I have editors that need to edit translations but shall not have access to this v-tab (it is being confused with the Publishing options for the node, leading to people altering the translation status where the node in its entirety should be unpublished/published instead).

Using hook_form_alter() in a custom module, I do not find any trace of the above form element in the $form array. According to a grep search, it is defined in the file /modules/entity_translation/includes/translation.handler.inc:1051. I assume it is being cached somehow, as that part of the code is not being executed when the form is built (breakpoints do not trigger).

Worst case, I could use Javascript to hide the form element, but I would rather not have to rely on such a hack. If possible, I would like to set #access to false for the editor role (or similar).

The reason you cannot use hook_form_alter() to modify the tabs is because the hook you implement in your custom module is being fired before entity translation injects the tab.

If you use hook_module_implements_after() you can change the order of the execution of the hooks.

function CUSTOMMODULE_module_implements_alter(&$modules, $hook)
{
    if ($hook == "form_alter")
    {
print_r($modules);
        // save off hook
        $temp = $modules["testing"];

        // remove it
        unset($modules["testing"]);

        // add it to the end
        $modules["testing"] = $temp;
print_r($modules);
    }
}

The first print_r outputs:

Array
(
    ...
    [CUSTOMMODULE] =>
    [entity_translation] =>
)

The second print_r outputs:

Array
(
    ...
    [entity_translation] =>
    [CUSTOMMODULE] =>
)

Now that the custom module fires after entity translation, use hook_form_alter() to hide the tab:

function CUSTOMMODULE_form_alter(&$form, &$form_state, $form_id)
{
    // make sure you set the form_id in this conditional properly.
    // I am using the edit form of a "page" node type.
    if ($form_id == "page_node_form")
    {
        $form["translation"]["#access"] = FALSE;
    }
}


How can I change the search form placeholder value? How can I change the search form placeholder value? I can change the value of it in my .theme file, but I want it to be also translatable.

What is the correct way of doing this?

You don't alter a TranslatableMarkup object: You replace it with another TranslatableMarkup object you obtain from t('The new placeholder') or
new TranslatableMarkup('The new placeholder') (or a method returning a TranslatableMarkup object).

function mytheme_form_search_block_form_alter(&$form, FormStateInterface $form_state) {
  $form['keys']['#attributes']['title'] = t('The new placeholder');
}

The result of this code is the following (on Google Chrome running on OS X El Capitan).

What you are showing is not the placeholder, but the input title. To change the placeholder of a form element, you should use code similar to the following one.

function mytheme_form_search_block_form_alter(&$form, FormStateInterface $form_state) {
  $form['keys']['#attributes']['placeholder'] = t('The new placeholder');
}

Using this code, you get the following result.


taxonomy-term at the automatic creation of url alias of a content path In Drupal 7, how i can use the taxonomy-term at the automatic creation of url alias of a content path?

Install Pathauto and Token. Pathauto will let you create automatic aliases, and Token will supply the content's taxonomy term as a substitutable value.


What is error: "Base table or view not found: 1146" Base table or view not found: 1146 Table '(database).(entity)__(field_name)' doesn't exist

I have problems running my site since i deleted field (field_name) from entity (entity), to be clear entity was created from ContentEntityType.

What kind of field is it, if it has it's own table and those two underscores in table name?

How can i create field of this kind to solve this error?

It is quite urgent and my bad is i don't have any database backups.

Found the fix!!! (Yes, i am user96758)

After 3 hours of investigation, internet and uncle Google wasn't helpfull at all.

The problem was that field was created via Drupal UI in Content Type -> Manage fields.
And it was deleted programatically by using UPDATE (code example below), not by using UI.

function hook_update_N(&$sandbox){
    $update_manager = Drupal::service('entity.definition_update_manager');
    $definition = $update_manager->getFieldStorageDefinition('field_name', 'entity_id');
    $update_manager->uninstallFieldStorageDefinition($definition);
    return t('Entity: field was uninstalled');
}

I have installed module named "Devel", which is pretty good damn module and every developer should have it.

I was finding anything that contains name of my problematic field.

Thanks to Devel module i was able to find config of this field.
Usually you can see all configs at url (your_site)/devel/config

Well, i was desperate, so the last chance was to delete the config i found.
Usually the fields are named: field.field.(entity).(entity).(field_name)

I removed the config with this code below

Drupal::configFactory()
    ->getEditable('field.field.(entity).(entity).(field_name)')
    ->delete();

Then i CLEARED CACHE and IT WORKS AGAIN!


How to alter page content? Simple thing. I have some page (node). At end it produces some content, i.e.

This is original content

I want to alter it with different content, i.e.

This is changed content

So I need a way to collect original content, parse it, replace some part of it and put it back.

hook_ENTITY_TYPE_view() should be the way to do that:

https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Entity%21entity.api.php/function/hook_ENTITY_TYPE_view/8.2.x

And I tried example from that page (by Devendra Mishra) and it works, but it's adding additional content. I need a way to access original content and change it, not to just add new one.

To be clear, I don't want to change content on field level, but want to change final content, with all fields combined, ready to be rendered.

If you don't want to change the variables on field level you can parse the content in a #post_render callback after it is rendered:

/**
 * Implements hook_ENTITY_TYPE_view().
 */
function mymodule_node_view(array &$build, EntityInterface $entity, EntityViewDisplayInterface $display, $view_mode) {
  $build['#post_render'][] = function ($html, array $elements) {
    return str_replace('original', 'changed', $html);
  };
}


How do I stop View/Edit tabs appearing on Taxonomy driven Pages when I am not logged in? I have a View and Edit button appearing on pages that are Taxonomy driven, even when I am not logged in (and in Incognito Mode).

These pages use the URL /taxonomy/term/%taxonomy_term and Views, using info from the URL, are used to display certain data on these pages. For example, with /cars/honda/civic 'cars', 'honda' and 'civic' would be used in the Views to show relevant information about Honda Civics.

The issue is that whilst there is no View and Edit buttons appearing on the base /cars page, they are appearing on every sub page (/cars/honda, /cars/toyota/camry, etc).

I can't find anything out of the ordinary in Permissions.

Would any one know what I could do to stop this?

(PS clicking the Edit button whilst not logged in does nothing - just takes you to 403 page).

This was due to someone not surrounding this code with a permissions checker, eg:

 if (!user_access('administer nodes')) {
    return;
  }


is using non English words for paths recommended? I'm working on a Drupal site which has a non-english language.I want to change the paths to something better than node/[nid].Nodes also have a non-english title and I want to set the path to content/[node-title].does it cause any problem?does it affect on SEO?

I use transliteration module in combination with pathauto module to transliterate any characters in my node title beyond ASCII 128 and automatically create friendly urls for each of my nodes.

This combination works really well! :)

Whether it is actually necessary or advantageous to remove unicode characters from your site's URLs is a subject on which I'm sure there would be many different opinions.

The Russian Wikipedia doesn't transliterate, but if you need to send your site's url's in an email, then things can quickly get out of hand and look ugly: http://ru.wikipedia.org/wiki/%D0%97%D0%B0%D0%B3%D0%BB%D0%B0%D0%B2%D0%BD%D0%B0%D1%8F_%D1%81%D1%82%D1%80%D0%B0%D0%BD%D0%B8%D1%86%D0%B0

I have no experience if unicode characters in URLs affect SEO.


How to troubleshoot edit node page timeout errors? When I try to update the body of a basic page, Drupal 7 times out after I press the "Save" button and wait for a while. Surprisingly, I can successfully update my other pages through Drupal forms.

I cleared all caches but that didn't help.

I tried to update the content by editing the database directly, but, my changes to the database tables "field_data_body" and "field_revision_body" didn't affect my web page.

How I can troubleshoot the timeout error when I try to update the contents of a basic page in Drupal 7?

I'd guess that a module is performing some task in either form processing or Node API Hooks. It might be communicating with a remote service, or simply taking a long time to perform some action. It might also just be that the DB communication is slow. If such an action takes too long, you'll hit the PHP timeout and the script will terminate.

You could identify which module by several means -

Debugging (eg add debug code with times to module_invoke_all() to see which hooks take a long time)
Understanding the purpose of your modules (I wonder if "Submit To Myspace" module is slowing things down?)
Process of elimination (turn off likely candidates until the problem goes away, turn them back on one by one until it recurs)

Note that the last approach is not the most dependable; if you have a 180s timeout, and module A takes 160s, module B takes 15s, and the rest of Drupal takes 6s, you could easily be mistaken in seeing the issue go away when you disable module B, despite A being the guilty party.

If the issue affects a single page, then sit back and study what might make that specific page different. Eg LinkChecker module (if installed) tries to retrieve linked images or URLs; and if those sites timed out, your node edit might also.


Programmatically develop search exposed filters I developed a custom module to list contents of custom tables. Now I want to have search filters much like exposed filter. My code is below

$items['recording'] = array(
    'title' => 'Recordings',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('recordingcrud_sort_with_pager_content'),
    'access arguments' => array('access recordings'),
);

function recordingcrud_sort_with_pager_content($form, $form_state) {
global $user;
print_r($form_state);
if (!isset($form_state['storage']['recordingcrud']['search_criteria'])) {
  return render_table();
} else {
    print_r($_POST);
    $filters = $form_state['storage']['recordingcrud']['search_criteria'];
    return render_table($filters);
}

}

In render_table function I am rendering the listing. and calling the fom

 $search_form = drupal_get_form('recordingcrud_search_form');
$output = drupal_render($search_form);

My search form and submit handler code is:

function recordingcrud_search_form($form, &$form_state) {
$form['search_term'] = array(
    '#type' => 'textfield',
    '#title' => t('Search'),
    '#size' => 40,
    '#maxlength' => 120,
);
$form['submit'] = array(
  '#type' => 'submit',
  '#value' => 'Apply',
  '#submit' => array('recordingcrud_search_form_submit'),
);

return $form;

    }

    function recordingcrud_search_form_submit($form, $form_state) {
        $form_state['storage']['recordingcrud']['search_criteria'] = $form_state['values'];
        $form_state['rebuild'] = TRUE;
    }

But this implementation I am getting the error

  PHP Fatal error:  Unsupported operand types in
  /var/www/html/digitalFunctionalism/allprobail/includes/form.inc

What am I doing wrong?

I finally managed to do this with the following changes.

I have changed the form method from post to get and then took the value of search term for url using $_GET
Assigned action to the current page on which I am.

Changed the following code to

    'page callback' => 'drupal_get_form',
    'page arguments' => array('recordingcrud_sort_with_pager_content'),

to

'page callback' => 'recordingcrud_sort_with_pager_content',

and removed the second line.


Add "active" class automatically to Url I'm generating a URL with Url::fromUri() method.

Is there a way to add automatically an "active" class, like D7, if the page is the same of the URL?

Obviously without check manually the value of the generated URL and the page.

In the documentation is not present, but on $options array we can simply set "set_active_class" to TRUE (FALSE by default) and then drupal add a "is-active" class to the link:

Url::fromUri('internal:/progetti/selezionati', array('set_active_class' => TRUE)),

I think that this behaviour should be TRUE by default..


Address Module 8.x-1.3 I am trying to run address field on my web page, but I get an error

  The website encountered an unexpected error. Please try again later.

So I checked the logs and get

  Error: Class 'CommerceGuys\Addressing\LocaleHelper' not found in Drupal\address\Plugin\Field\FieldFormatter\AddressDefaultFormatter->getValues() (line 286 of /var/www/mywebsite/modules/contrib/address/src/Plugin/Field/FieldFormatter/AddressDefaultFormatter.php)

I checked my composer.json file and have the following required

 "drupal/address": "~1.0",
 "commerceguys/addressing": "1.x-dev",

ran

 composer update drupal/address --with-dependencies

from https://www.drupal.org/project/address
but still getting the same error, I believe the error is commerceguys/addressing, but composer update says there is nothing to be updated. Any directions to my problem will help a lot, thanks.

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.