Cannot create a views for show content revision I got a problem when adding new view in

Home > Administration > Structure > Views.

I insert options like this.

It shows (I applied Debug mode for look Stacktrace)

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

Drupal\Component\Plugin\Exception\PluginNotFoundException: The &quot;&quot; plugin does not exist. in Drupal\Core\Plugin\DefaultPluginManager-&gt;doGetDefinition() (line 52 of core/lib/Drupal/Component/Plugin/Discovery/DiscoveryTrait.php).
Drupal\Core\Plugin\DefaultPluginManager-&gt;getDefinition(NULL) (Line: 945)
Drupal\views\Plugin\views\wizard\WizardPluginBase-&gt;defaultDisplayFiltersUser(Array, Object) (Line: 904)
Drupal\views\Plugin\views\wizard\WizardPluginBase-&gt;defaultDisplayFilters(Array, Object) (Line: 725)
Drupal\views\Plugin\views\wizard\WizardPluginBase-&gt;buildDisplayOptions(Array, Object) (Line: 699)
Drupal\views\Plugin\views\wizard\WizardPluginBase-&gt;instantiateView(Array, Object) (Line: 1275)
Drupal\views\Plugin\views\wizard\WizardPluginBase-&gt;validateView(Array, Object) (Line: 167)
Drupal\views_ui\ViewAddForm-&gt;validateForm(Array, Object)
call_user_func_array(Array, Array) (Line: 83)
Drupal\Core\Form\FormValidator-&gt;executeValidateHandlers(Array, Object) (Line: 276)
Drupal\Core\Form\FormValidator-&gt;doValidateForm(Array, Object, &#039;view_add_form&#039;) (Line: 119)
Drupal\Core\Form\FormValidator-&gt;validateForm(&#039;view_add_form&#039;, Array, Object) (Line: 571)
Drupal\Core\Form\FormBuilder-&gt;processForm(&#039;view_add_form&#039;, Array, Object) (Line: 314)
Drupal\Core\Form\FormBuilder-&gt;buildForm(&#039;view_add_form&#039;, Object) (Line: 74)
Drupal\Core\Controller\FormController-&gt;getContentResult(Object, Object)
call_user_func_array(Array, Array) (Line: 123)
Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber-&gt;Drupal\Core\EventSubscriber\{closure}() (Line: 582)
Drupal\Core\Render\Renderer-&gt;executeInRenderContext(Object, Object) (Line: 124)
Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber-&gt;wrapControllerExecutionInRenderContext(Array, Array) (Line: 97)
Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber-&gt;Drupal\Core\EventSubscriber\{closure}() (Line: 151)
Symfony\Component\HttpKernel\HttpKernel-&gt;handleRaw(Object, 1) (Line: 68)
Symfony\Component\HttpKernel\HttpKernel-&gt;handle(Object, 1, 1) (Line: 57)
Drupal\Core\StackMiddleware\Session-&gt;handle(Object, 1, 1) (Line: 47)
Drupal\Core\StackMiddleware\KernelPreHandle-&gt;handle(Object, 1, 1) (Line: 99)
Drupal\page_cache\StackMiddleware\PageCache-&gt;pass(Object, 1, 1) (Line: 78)
Drupal\page_cache\StackMiddleware\PageCache-&gt;handle(Object, 1, 1) (Line: 47)
Drupal\Core\StackMiddleware\ReverseProxyMiddleware-&gt;handle(Object, 1, 1) (Line: 50)
Drupal\Core\StackMiddleware\NegotiationMiddleware-&gt;handle(Object, 1, 1) (Line: 23)
Stack\StackedHttpKernel-&gt;handle(Object, 1, 1) (Line: 664)
Drupal\Core\DrupalKernel-&gt;handle(Object) (Line: 19)

It tell The "" plugin does not exist. Any idea to find error cause for this problem. Thanks,

More information

occur on both Drupal version 8.5.1 and 8.5.3

I saw some solution in stack exchange. It solve by install GD library. but checked in Report status. it has already installed.

any advise solution.

The node_revision table doesn't contain a column for type, so you can't add the content type filter here. So don't fill in a content type for now and create the View for all types. Then add a relationship to Content in the ADVANCED section. Now all node fields are available in the View and you can add a filter for the content type in FILTER CRITERIA.


Show user email from the user entity to anonymous users Through views I am trying to show the account email address of any user to any user.

I have checked "Disable SQL rewriting", made sure the view didn't have any permissions, allowed anonymous user to view profiles. After all this it still won't show.

Note: I really don't want to create an additional field that is just syncs up this info just to show it. I want to show the actual field.

Once you done creating views, go to permission tab and check Role

http://i.imgur.com/zrcSrua.png

in the settings check anonymous, now the user will see the view.


How do I enable an onclick event in a link on a form? I am using the following code.

 $form['test'] = array(
        '#type' => 'link',
        '#href' => "javascript:;",
        '#title' => t('Show'),
        '#attributes' => array(
            'onclick' => "show_this();",
            'onsubmit' => 'return false',
        ),
        '#id' => 'myid',
  );

Its output is the following.

Show

The onclick event is working properly. I want to disable href.

How can I achieve this?

You don't need the #href to prevent the event.

$form['test'] = [
  '#type' => 'link',
  '#href' => '#',
  '#title' => t('Show'),
  '#attributes' => [
    'onclick' => "alert('hello');return false",
  ],
  '#id' => 'myid',
];

In the above example, I removed the #href and the onsubmit handler and added return false after the alert() function in the onclick handler.
I don't know what  you're trying to achieve in your code, but the above example is working for me.

UPDATE:
I update the #href in my answer.


What is the use of node--product_display.tpl.php? I am new to Drupal Commerce, what is the use of node--product_display.tpl.php?

node.tpl.php is the default theme for all content types in a drupal installation.  If you want a specific content type to have different layout/theme you can override by creating a tpl.php file like this node--[CONTENTTYPENAME].tpl.php so for example for ARTICLE content type your would copy node.tpl.php and rename to node--article.tpl.php and adjust the new file to as you desire.

Now Commerce displays a product using a CONTENT type called product display thus to change the look of this content type you will create node--product_dispaly.tpl.php

here is some more explanation of things that you can do inside a node.tpl.php file and (all overrides) https://api.drupal.org/api/drupal/modules%21node%21node.tpl.php/7.x


How can I save what filters a user wants when viewing a view? I don't know if this is possible but, I would like to allow my users to be able to filter out what content they would like to show up in a view so that every time they return to that view, their preferences are saved.

I no how to allow my users to filter content in a view but I'm having trouble saving it. I'm trying to allow my users to control their own news feeds.

I've tried looking around for a module to do this and I've been playing around with views for a while but I can't seem to hack something thing that does what I outlined. Any help would be appreciated. Thanks.

If your view is using exposed filters, there is a "Remember search" option in the View configuration. This stores the search parameters in the session, and should give you the expected effect. Admittedly, I'm thinking of Views 2, and I just assume the setting is available in Views 3 as well.


Get contextual filter ID in views row I've got a view with a contextual filter for an entity reference field. The contextual filter fetches the current node id from URL as filter criteria. The individual rows of the view are rendered as content in teaser view mode (not using fields), so basically it uses node--nodetype--teaser.html.twig to render the results. The view is attached to nodes using the EVA module

I now need the value of a field from the host/contextual node in node--nodetype--teaser.html.twig (the template used by the views row). I know how to query entities and fields, but I don't know which hook to use and how to get the node ID of the contextual filter.

How can I get the contextual filter ID and which hook should I use to pass the contextual filter down to the node teaser template?

Implement template_preprocess_node in your .theme file and get the page's node with the following code.

/**
 * Implements template_preprocess_node().
 */
my_theme_preprocess_node(&$vars) {
  // This will fire for any node type with the teaser view mode
  if ($vars['view_mode'] == 'teaser')
    $node = \Drupal::routeMatch()->getParameter('node');
    if ($node instanceof \Drupal\node\NodeInterface) {
      // You have the full node object and can access fields as needed.
      // You can even check the $node type in the above if statement to only add
      // this value to the teaser for nodes when you're on the type with your EVA
      // Make sure to add them to the $vars array to see them in your template.
    }
  }
}

See this post re: how to access fields from a node object.

Note: This doesn't do exactly what you're asking, but will work if you're viewing the full page of the node with the EVA.


How to debug views_handler_field_node_revision handler? I believe I have updated some of my modules, then the following debug message pop on the calendar page. Does anyone know what is this message and how to solve it?

  Debug:

    'Handler views_handler_field_node_revision tried to add
    additional_field nid but node could not be added!'

  in views_handler_field->add_additional_fields() (line 142 of
  /public_html/sites/all/modules/views/handlers/views_handler_field.inc).

I had this problem when the "Content revision: Title" field on my view was set to "Link this field to the original piece of content" however it wasn't using the relationship to the content.

I set it to use the "Content revision: Content" which fixed the link and the error.

I think this error is displayed with problems regarding a node_revision view and an error in the relationship, as Nels mentioned.


How can I prefill taxonomy tags for a new node being created through the node form? I have created a cck node type and associated a tagging taxonomy vocabulary with it. When users create new content, I would like to be able to prepopulate the node form.

For example, if the node type were 'cars' and one term was 'antique', I want to be able to create new instances of cars with the tag 'antique' already populated in the editing form.

I have gotten as far as creating a path such as 'node/add/auto?tid=3' ... but how do I then take that tid and use it to prepopulate the vocabulary tags field in the auto_node_form?

Have a look at the Prepopulate module.

Read the documentation on how to use it.


redirect to custom page In my custom module, I created a custom link using

function MYMODULE_menu() {
$items['addcontent'] = array(
    'title'
    => 'Confirmation page',
    'page callback'
    => 'add_content_confirmation',
    'access callback' => TRUE,
);
return $items;
}
function add_content_confirmation() {
return 'Thank you';
}

When I check mydrupal/addcontent, this link works fine

In my template.php, I added

function MYTHEME_form_alter(&$form, $form_state, $form_id) {
  if($form_id == 'my_form_id'){
    $form['actions']['submit']['#submit'][] = 'my_custom_submit';
}
function my_custom_submit()
{
  $form_state['redirect'] = 'addcontent';
}

wich redirects me to my home page.

if I write

$form_state['redirect'] = 'node/add/mycontent';

That works fine.

How can I fix it?

Thank you

This:

function my_custom_submit()

Should be this:

function my_custom_submit($form, &$form_state)

Right now you are setting redirect on a variable that doesn't exist.


menu item call from tpl file I have create one form in .tpl file with simple html form tag.
In action attribute of this form element i passed a url like 'action=savequestion'. Now in my .module file, inside hook_menu(), I am defining menu with the above url mentioned in action.

$items['savequestion'] = array(......); //like this

But when i am submitting that form defined in tpl file, It is not calling this menu item and page not found comes.

any one have idea about this? Thank you.

The right way to do this if you are using a Drupal module is to set up a form using the Form API and process things within the context of a module. You can also use a contributed module such as Webform to accomplish this too, but if you want something really custom, you should not just create a form in a template file.

All of this said, make sure your "action" is set to the same path as your menu item and that after you have created your hook_menu entry you clear the cache, so your menu item becomes part of Drupal's menu registry.


Is there a submit handler for custom fields? I built a custom field, and now I'm adding an image upload to that custom field.  The type is managed_file.  When the user saves the content, where can I handle the file after submit?

You can use hook_field_update in your module where you define your field..

  Define custom update behavior for this module's field data.

  This hook is invoked from field_attach_update() on the module that
  defines a field, during the process of updating an entity object
  (node, taxonomy term, etc.). It is invoked just before the data for
  this field on the particular entity object is updated into field
  storage. Only field modules that are storing or tracking information
  outside the standard field storage mechanism need to implement this
  hook.


cache_menu items are huge Drupal 7.24

I have been stonewalled by an interesting problem on a D7 site. Essentially the cache_menu table was getting very large but not just in items (6300 odd) some of the items are enormous.

Its a new record for me, one of the items is 1.24 mb and 26 of them are between 800k and 1mb.

The site went down when it was being git with slightly elevated traffic, its running on a load balanced AWS cluster with RDS at the back, there's no lack of resources for a 20 simultaneous connections site.

i truncated the cache_menu and regenerated everything by browsing the site and all but a few of the items are gone now but there are still the 1.2mb one and a handful of the 800kb ones.

I followed this link -  http://drupal.org/node/1234830 from here Huge cache_menu table and it appears that this particular issue has been resolved for 7.13+ so i am thinking its something architectural going wrong.

There's no core hacks, we've got an impressive search system using a logic server network (running on SOLR externally) that does hook into taxonomy terms. The site is essentially a portal of links.

Could someone give me some pointers on where to start track this issue down?

edit: CID/sizes in cache_menu, query:

SELECT cid, LENGTH(`data`)/1024 as `size KB` FROM cache_menu WHERE LENGTH(`data`)/1024 > '300' ORDER BY `size kb` DESC;

Result

links:management:tree-data:en:ec99d3452fef1ede622e66c68ba908b1dad455aa71f5e68648aeec6488b89c88
1094.2188
links:main-menu:all-cid:0:1:en
839.4873
links:main-menu:tree-data:en:ec99d3452fef1ede622e66c68ba908b1dad455aa71f5e68648aeec6488b89c88
815.6230

I suspect that you have some very large menus in your site.  Rebuilding menus is a an expensive operation, and menu trees can vary page-to-page, user-to-user, etc.  As a result, that data gets cached in {cache_menu}.

My suggestion is to query in your favorite SQL tool, and print_r() the data column for the large entries to see if anything looks out of the ordinary.  In general, the data will be your menu tree with everything from the various hook_menu() entries added in.  Modules that add extra data onto menu entries (like Menu Attributes) will have there data here, too.

You need to profile to see where the problem is actually happening.

It could be the result of a less-than-ideally configured MySQL instance.  If you do have 1M cache entries, then you may want to bump up the query cache result set limit (I think this defaults to 128K).

You may also want to investigate using memcache or redis as your cache backend.

However, if you really do have huge menus, then the slowdown could be from unserializing all of that data.  If this is the case, then you need to figure out a strategy to cache the menu output when your pages are being built up.  Enabling block level caching may help, or you may need to make your own menu blocks, and cache that output yourself.  Panels caching may be worth investigating.

It may sound odd, but you may also want try to disabling caching for {cache_menu}.  The easiest way to do this is to install one of the dummy cache modules, and configure it to just use that cache backend for {cache_menu}.


How to put a node in a menu using an URL parameter? While creating a new node, I'd like to pass a parameter in the URL: node/add/page?plid=123 in order to put the newly created node in this menu item as its child.

I tried to hook_form_alter() the node form but I couldn't populate the menu part, also I'd like to hide this part to the end user as they shouldn't alter it.

Should this be done in a hook_node_insert() with something like this answer: How to enable menu link when creating a new node ?

hook_node_insert() is probably the best place to do this. You'll want to call menu_link_save() to create the menu item, using the $_GET superglobal to retrieve the plid parameter:

mymodule_node_insert($node) {
  $item = array(
    'link_path' => 'node/' . $node->nid,
    'link_title' => $node->title,
    'plid' => $_GET['plid'],
  );
  if (!menu_link_save($item)) {
    // menu_link_save() returns the mlid of the new item. Handle a failure here,
    // which will occur if the plid supplied is invalid.
  }
}


How can I prevent a particular page being cached? I have activated the cache on my Drupal 8 site, and of course all pages are cached as expected.

However, I'd like to have a specific page bypass that cache.

In my controller I built the page as follows:

public function myPage() {
  return [
    '#markup' => time(),
  ];
}

How can I tell Drupal not to cache my page?

For Drupal 7:

Drupal has the function drupal_page_is_cacheable() which can be used to set a page to uncacheable.

Here is the documentation: https://api.drupal.org/api/drupal/includes!bootstrap.inc/function/drupal_page_is_cacheable/7

For Drupal 8:

// Deny any page caching on the current request.
\Drupal::service('page_cache_kill_switch')->trigger();

Then the code is:

public function myPage() {
  \Drupal::service('page_cache_kill_switch')->trigger();
  return [
    '#markup' => time(),
  ];
}

As usual, clean your cache once done.


Menu that conditionally shows webform, or edit previous submission How can I have a menu item "RSVP" that shows a webform, but after an authenticated user has submitted that webform, clicking on "RSVP" would now bring them back to their submission in edit mode?

rsvpdirect.info:

name = rsvpdirect
description = "Redirects webform nodes to edit if the user has already submitted it once before."
package = Custom
core = 7.x
files[] = rsvpdirect.module

rsvpdirect.module:

<?php

/**
* @file
* Forces redirect of webform node to edit the user's previous submission.
*
*/

/**
* Implementation of hook_node_view()
*/
function rsvpdirect_node_view($node, $view_mode, $langcode) {
  global $user;
  if ($node->type == 'webform' && $view_mode == 'full' && arg(0) == 'node') {
    $submissions = webform_get_submissions(array('nid' => $node->nid, 'uid' => $user->uid));
    $submission_count = webform_get_submission_count($node->nid, $user->uid);

 if ($submission_count >= 1) {
      // Get first submission
      $submission = reset($submissions);
      drupal_goto('node/' . $node->nid . '/submission/' . $submission->sid . '/edit');
    }
  }
}

You can do it using hook_node_view and redirect functionality to redirect if webform is submitted. Your menu link always point to webform page.

function YOURMODULENAME_node_view($node, $view_mode, $langcode) {
  global $user;
  if ($node->type == 'webform' && $view_mode == 'full' && arg(0) == 'node') {
    $submissions = webform_get_submissions(array('nid' => $node->nid, 'uid' => $user->uid));
    $submission_count = webform_get_submission_count($node->nid, $user->uid);
    if ($submission_count >= 1) {
      // Get first submission
      $submission = reset($submissions);
      drupal_goto('node/' . $node->nid . '/submission/' . $submission->sid . '/edit');
    }
  }
}


How do I use the states API in a hook? I'm trying to use the states API in Drupal 8 but I'm having trouble, and I'm also having difficult debugging.

Use case:

On user accounts, I have a taxonomy term reference field called Gender.  The three terms in the taxonomy vocabulary are female, male, and other.

I also have a text field on user accounts called Other.  I want to show this Other field if and only if Gender is set to other (term ID: 27).

Here is the code I'm using:

function mymodule_form_user_register_form_alter(&$form, &$form_state, $form_id) {
  $form['field_gender_other']['#states'] = array('visible' =>
    array('input[name="field-gender"]' => array('value' => '27'),
    ),
  );
}

I based this off of code I used for Drupal 7.  Unfortunately, it's not doing anything.

I looked at StateDemo.php in the fapi submodule of the Examples module for Drupal 8, but that's for building a new form, and I'm trying to modify an existing form.

You should use like below:

$form['field_popin_text']['#states'] = [
  'visible' => [
    'select[name="NAME_OF_SELECT_LIST"]' => ['value' => '27'],
  ]
];


Create a theme function for form fields I need to theme certain form fields on the user profile form page differently from other fields, for which I am trying to create a theme function that outputs html its own way, not using theme_form_element(). The reason for defining a new theme function alternative to theme_form_element() is because the html output is dramatically different.

This is my code:

function mymodule_theme() {
  return array(
    'profile_form_element' => array(
      'variables' => array(
        'element' => NULL,
      ),
    ),
  );
}

function mymodule_form_user_profile_form_alter(&$form, &$form_state) {
    $form['field_user_first_name']['#theme'] = 'profile_form_element';
    dpm($form['field_user_first_name']);
}

function theme_profile_form_element(&$variables) {
  $element = &$variables['element'];
  // my html processing would start here...
}

...but the theme function has NULL for $variables['element']. What am I doing wrong? I am attaching the structure of my form field (field_user_first_name), which was created through the UI at configuration > people > account settings > manage fields.

I think one of your problem is with this:

$element = &$variables['element'];

I don't think you can assign a reference to an array element (the &), so try changing it to:

$element = $variables['element'];

and I don't see a 'element' element, so unless I'm blind you're trying to access an element that isn't there, so it will always return NULL;


Is there a NULL value for a multi-value list? I have a list that accepts 5 different values, but some things on my spreadsheet are empty, meaning its none of the 5 things. However during the feeds import, it is saying my empty field is not a valid selection.
Is there a way I can still import even though the value is empty?

Select Element's API

#empty_option: (optional) The label to show for the first default option. By default, the label is automatically set to "- Select -" for
a required field and "- None -" for an optional field.
#empty_value: (optional) The value for the first default option, which is used to determine whether the user submitted a value or not.

So using this information, you are able to use the null value's defaults from the select element.


How to avoid missing status for Workflow access module permission just after node creation? I am using Workflow 7.x-2.8 to manage peer-reviewing publication.

When an authenticated user (an author) creates a post, he can choose a first workflow state transition from creation (by default) to draft. This draft is visible only for author and admin. This draft can be edited only by the author.

The sub-module Workflow Access allows me to manage permissions for each workflow state, which is really great. But, apparently, I have a problem with the first status assignment with Workflow Access (priority = 1).

Indeed, according to Devel Node Access module (DNA) debug mode, the status is not in node_access table and I need to rebuild permissions to clear the issue (which is OK for dev website but of course, it is not OK for production website).

When the permissions are rebuilt, everything is fine and the node_access table seems to be OK. Further, when the author decides to change the post to another workflow state (draft TO submitted), the permissions are correctly modified and the author can not edit the post anymore (pending approval).

Last detail : the content type related to this workflow is not published, by default.

I add a DNA screenshot and I hope everything is clear.

Just had the same problem for me, but for a custom hook_node_access_records().

For me the solution to implement the hook_node_grants(). and clear the cache.

Once you use the hook_node_access_records, you have to implement the hook_node_grants.


facets appear "_empty_" I'm using the Apache Solr Search Integration and Facet API modules. I'm trying to implement facets for custom fields publication_date, publication_author, and journal, which are part of the content type publication.

These 3 fields are indexed successfully as ss_date, ss_author, and ss_journal. Furthermore, I can search against these fields on the default apachesolr search page. However, the facets for these fields show up as "_empty_". For example, when the search page loads, under the "publication_author" facet header, one bullet item shows up as "_empty_ (10)", which to me means that the author field is being indexed successfully with value "NULL" or possibly literally "_empty_" for all 10 publication nodes. Code is below for just the author facet.

define custom facets

function HOOK_facetapi_facet_info(array $searcher_info) {
    $facets = array();
    // Facets are usually associated with the type of content stored in the index.
    if (isset($searcher_info['types']['node'])) {
        $facets['ss_author'] = array(
            'name' => 'ss_author',
            'label' => t('custom: author'),
            'description' => t('Shows the authors'),
            'field' => 'ss_author',
            'dependency plugins' => array('role'),
            'default widget' => 'links',
            'allowed operators' => array(FACETAPI_OPERATOR_AND => TRUE, FACETAPI_OPERATOR_OR => TRUE),
            'facet missing allowed' => FALSE,
            'facet mincount allowed' => FALSE,
            //'map callback' => 'not used for now',
            'max callback' => FALSE,
            'default sorts' => array(
                array('active', SORT_DESC),
                array('count', SORT_DESC),
                array('display', SORT_ASC),
            ),
        );
    }
    return $facets;
}

"ss_author" is the name of the field added to the ApacheSolr document during indexing. If you'd like the code used to actually index these fields, let me know. Thanks very much!

Facets, by their very nature, work best when you use them for 'select' type fields, not pure text.  Facets work very well - and automatically - with taxonomy terms for example, because terms are re-used and it's easy to group based on select type fields.

Whenever I've wanted to use custom fields as facets, I've implemented them as terms (tagging) or select fields, and then they work properly.

So, I'm wondering - is that something you could do?  Rather than setting up your fields as 'text', could you set them up as select-type fields (whether it's tags, which don't have to be predetermined or select options which you have to enter in advance)?  That type of field is easier to GROUP by - which is what facets are really doing.

It may not be an option, but I have a feeling that would resolve your issue.

Let us know how this gets resolved!


RuntimeException when patch submission. Module Webform Rest When i send a PATCH request to my site to /webform_rest/{webform_id}/submission/{sid}?_format=json with the body
{
    "data":{
        "sincronizado":1
    }
}

or
{
  "sincronizado":1
}

from postman, I receive a 500 error.
The site log displays the next error:

RuntimeException: Callable
"Drupal\webform_rest\Plugin\rest\resource\WebformSubmissionResource::patch"
requires a value for the "$webform_data" argument. en
Drupal\Component\Utility\ArgumentsResolver->handleUnresolvedArgument()
(line 142 of
/usr/home/example.com/web/core/lib/Drupal/Component/Utility/ArgumentsResolver.php).

Am I making a bad request? What is the $webform_data argument? My webform has a field "sincronizado", of type value.
I'm using Drupal 9.
REST UI 8.x-1.18.
RESTful Web Services 9.0.2
Webform 6.0.0-alpha12
Webform Rest 4.0.0-beta1

Same problem sending sid parameter with Webform rest version 8.x-2.0-beta3.
My request from postman, in curl code is

curl --location --request PATCH 'http://example.com/webform_rest/webform-id-example/submission/36?_format=json' \
--header 'Content-Type: application/json' \
--header 'Authorization: Basic (admin user and password in base 64)' \
--data-raw '{
"sincronizado":"1"
}'

Ok mate if you open up
webform_rest\Plugin\rest\resource\WebformSubmissionResource.php
and find the patch method you will see
public function patch($webform_id, $uuid, array $webform_data) { ...

looks like Webform Rest 4.0.0-beta1 is now using the submission uuid
so
/webform_rest/{webform_id}/submission/{sid}

"sid" should now be Webform Submission UUID
for the body field or the $webform_data
the module is looking for
  foreach ($webform_data as $field => $value) {
      $webform_submission->setElementData($field, $value);
    }

so your json should look like:
   {
    "filed_name": "value"
   }

because json_decode($json_string, true) will return an array.
if that does not work then file a bug ticket


Can you override a library per environment? In my libraries.yml file, I have something like this, being used to define "foo-bar" as a library that can be pulled in from various parts of the site:

foo-bar:
  version: 0.0.x
  js:
    js/foo-dev.js: {}

This works well on my local environment, but on our production and QA environments, I would like for it to look more like this:

foo-bar:
  version: 0.0.x
  js:
    js/foo-prod.js: {}

(The prod version will include optimizations that normally don't appear with minification alone).

Currently, we are using the sites/<site>/settings.*.php files and the config-split module to have different configurations based on the environment, but is there a way to have the foo-bar library reference the dev-friendly version on one environment, and the production version on all others?

Look at hook_page_attachments. In the sample snippet provided behind that link there is a simple if-request which attaches a certain library only when a certain condition is met. Do the same.

MYTHEME/MYMODULE.libraries.yml

foo-bar-dev:
  version: 0.0.x
  js:
    js/foo-dev.js: {}
foo-bar-prod:
  version: 0.0.x
  js:
    js/foo-prod.js: {}

MYTHEME.theme/MYMODULE.module

function MYTHEME/MYMODULE_page_attachments(array &$attachments) {

  // Conditionally attach an asset to the page.
  if (\Drupal::request()->getHost() == 'example.com') {
    $attachments['#attached']['library'][] = 'MYTHEME/MYMODULE/foo-bar-prod';
  }
  else {
    $attachments['#attached']['library'][] = 'MYTHEME/MYMODULE/foo-bar-dev';
  }
}

More info on base URL: how to get base url of a site?.


how to make a form field be required with hook form alter I want to alter a form to make the revision log be required.
with drupal 8, I am adding this in a module

$form['revision_information']['#required'] = TRUE;

but the field does not become required.  What am I missing?

this was the answer:

$form ['revision_log']['widget'][0]['value']['#required']=TRUE;

thanks for the tip about the widget Kevin


Allow a user to upload a PDF file to a specific block within a page Wondering if anyone can help with a problem:

I have created a content type called 'Brochures' and added a 'file' field with a pdf format. I want the user to be able to upload pdf file(s) then select a particular page for the pdf to populate having them display in a block-view on that specific page.
So the user process would be:

-add content
-select 'Brochure' content type
-browse/upload PDF
-select a page for the PDF to populate <-----This is the part that is giving me grey hair. ;)
-save

Hope I am making sense.

Always, Jason

You could use the Entity Reference module to add the "Select a page for the PDF to populate" field (in the "Brochure" content type).

Then, create a View block that filters on "content type = brochure" and which pulls the PDF file field only. Set up a Contextual Filter for the entity reference field (the one that you selected the node/page for the PDF to populate on) and provide a default value of the nid of the page being viewed.

Placing this block in a region should pull related PDFs for pages that have been referenced. Should work!


Reset Password Form does not let user enter their new password An regular registered user reset a password
An email with one-time link will sent to the user
Clicking the link will lead the user to the change password form
Now, the drupal site warn the user the link has been used. The user need to get another one-time link.
Cannot enter the reset form

Solved it by installed the Simple Password Reset module:

  Without this module enabled, core Drupal prompts the user to log in
  via a one-time login form. After clicking "Log in", the user is
  brought to their profile edit form where at long last they can change
  their password.

  With this module enabled, the user skips the one-time login form.
  Instead the password reset link brings them right to the profile edit
  form where they can immediately change their password and log in. So
  what core Drupal does in two steps, this module does in one.


Custom menu link does not show up under "List links" but is in the database I have three menus with six links each using the i18n module.

All of these links are to panel pages.  On one menu, however, there is an additional link to another custom panel that does not appear in the Menu UI (under List Links)  but is present in the database (I found it in the menu_links table).

When I go to the panel of the ghost link, the option for showing a menu link is disabled.

How can I put this link back in the UI?  Or should I simply delete it from the database and re-create it in the UI?

EDIT: I tried adding the link in the menu manually, but then it shows up twice.

Simply go to the menu and add that link in the menu and it would start showing up.


Translate Forums page title I've tried with preprocess_page, preprocess_forums even changing drupal_set_title directly in forum.module but i can't get change that ugly page title "forums".

Any idea?

Try to change the name of the (taxonomy) vocabulary that holds the names of the forums and groups.


Custom views field handler with relationship support, but without table I created a custom field handler following the very useful explanations here,
Custom views handler without table

The field handler picks the entity from each row and renders it in some way. (For simplicity lets just assume it renders a link to the entity using entity_label() and entity_uri(). It actually does more awesome stuff, but this is irrelevant here.)

Unfortunately, I found that I cannot configure a relationship when using this field handler. E.g. if I have a relationship "The node author", then I might want to render the title + link for the node author instead of the node.

Is there anything more I need to enable support for relationships?

/**
 * Implements hook_views_data().
 */
function EXAMPLE_views_data() {
  $data = array();
  $data['EXAMPLE']['table']['group'] = t('Custom');
  // #global is a special flag which let's a table appear all the time.
  $data['EXAMPLE']['table']['join']['#global'] = array();

  $data['EXAMPLE']['custom_handler'] = array(
    'title' => t('EXAMPLE field handler'),
    'help' => t('EXAMPLE field handler'),
    'field' => array(
      'handler' => ExampleViewsFieldHandler::class,
    ),
  );

  return $data;
}

I could also post the code of the field handler class, but I supposed it is not really that relevant..

Ok, I found one way to do this: Instead of registering just one handler, you register one handler per entity type. To save time, we can reuse the stuff already registered by Entity API, with entity_views_data(). This means, of course, the module needs to add Entity API as a dependency.

/**
 * Implements hook_views_data_alter().
 */
function EXAMPLE_views_data_alter(&$data) {

  foreach (entity_get_info() as $entity_type => $info) {
    if (!isset($data['views_entity_' . $entity_type]['rendered_entity'])) {
      // Only register for those entity types where Entity API already did its job.
      continue;
    }
    $data['views_entity_' . $entity_type]['EXAMPLE'] = array(
      'title' => t('Entity display plugin'),
      'help' => t('The @entity-type of the current relationship rendered using an entity display plugin.', array('@entity-type' => $info['label'])),
      'field' => array(
        'handler' => ExampleViewsFieldHandler::class,
        'type' => $entity_type,
        // The EntityFieldHandlerHelper treats the 'entity object' data
        // selector as special case for loading the base entity.
        // @todo Not sure if we really need this.
        'real field' => 'entity object',
      ),
    );
  }
}

And below is the field handler class, just a bit simplified.

Maybe it does a bit more than we really need here. E.g. we don't really need to create a render array for each row, we could work with html directly. But I think it is a good start.

class ExampleViewsFieldHandler extends \views_handler_field {

  function query() {
    // do nothing -- to override the parent query.
  }

  /**
   * Run before any fields are rendered.
   *
   * This gives the handlers some time to set up before any handler has
   * been rendered.
   *
   * @param object[] $rows
   *   An array of all objects returned from the query.
   */
  function pre_render(&$rows) {
    /**
     * @var string $entityType
     * @var object[] $entities
     */
    list($entityType, $entities) = $this->getResultEntities($rows);
    // Build the entities.
    $builds = $this->buildMultiple($entityType, $entities);
    foreach ($rows as $rowIndex => $row) {
      if (isset($builds[$rowIndex])) {
        /** @noinspection PhpUndefinedFieldInspection */
        $row->example_field_builds[$this->position] = $builds[$rowIndex];
      }
      else {
        /** @noinspection PhpUndefinedFieldInspection */
        unset($row->example_field_builds[$this->position]);
      }
    }
  }

  /**
   * @param object[] $rows
   *
   * @return mixed[]
   *
   * @see EntityFieldHandlerHelper::pre_render()
   */
  protected function getResultEntities(array $rows) {
    $relationship = !empty($this->relationship) ? $this->relationship : NULL;
    $field_alias = isset($this->real_field) ? $this->real_field : NULL;
    // Some views query classes want/allow a third parameter specifying the field name.
    /** @noinspection PhpMethodParametersCountMismatchInspection */
    list($entityType, $entities) = $this->view->query->get_result_entities($rows, $relationship, $field_alias);
    return array($entityType, $entities);
  }

  /**
   * @param object $row
   *
   * @return string
   */
  function render($row) {
    /** @noinspection PhpUndefinedFieldInspection */
    return isset($row->example_field_builds[$this->position])
      ? drupal_render($row->example_field_builds[$this->position])
      : NULL;
  }

  /**
   * @param string $entityType
   * @param object[] $entities
   *
   * @return array[]
   *   A render array for each entity.
   */
  protected function buildMultiple($entityType, array $entities) {
    $builds = array();
    foreach ($entities as $rowIndex => $entity) {
      $builds[$rowIndex] = array(
        '#markup' => entity_label($entityType, $entity),
      );
    }
    return $builds;
  }
}


Get dynamically created image URL in a block with paragraph and media bundle I have seen a lot of related answers to this question but nothing specific to my issue - apologies in advance if it has already been answered.

In Drupal 8, I have a custom block type that references a Paragraph type.  The Paragraph has a field that references an image media bundle.  So it looks something like this:

Block-> ReferenceFieldForParagraph-> Paragraph-> ReferenceFieldForMediaBundle-> MediaBundle-> ImageUploadField

I need to apply various image styles to that image and then get the URL for each image.

In the Paragraph's Display, I have set the field that references the media bundle to display Thumbnail: Original Image
I have created a twig template for the paragraph bundle and I am able
to generate my various images by doing the following:

The media bundle reference field is named field_slide_image:

{% block paragraph %}
  {% block content %}

    {# set the styles #}
    {% set image1 = content.field_slide_image.0|merge({'#image_style': 'style1'}) %}
    {% set image2 = content.field_slide_image.0|merge({'#image_style': 'style2'}) %}
    {% set image3 = content.field_slide_image.0|merge({'#image_style': 'style3'}) %}

    {# render images #}
    {{ image1 }}
    {{ image2 }}
    {{ image3 }}

  {% endblock %}
{% endblock paragraph %}

I cannot figure out how to get the URL.  I have tried to use file_url() but I don't see any reference to the uri when I use kint.  In other words, something like this doesn't work:

{% set image1 = content.field_slide_image.0|merge({'#image_style': 'style1'}) %}
{% set uri1 = file_url(image1.uri.value)  %}
{{ uri1 }}

I need the url's so that I can create a custom responsive image using the picture tag.  I need to generate this dynamically because I have another field (select box) that specifies the dimensions of the images (ie the image styles).  For example, option 1 is a 1x1 ratio, option 2 is a 3x4 ratio, etc.  I could easily print all images and set up media queries to hide/display them but I don't want to resort to that if I don't have to.

Here is what I see when I kint image1

Thanks in advance

I wouldn't try to hack the render array content. You might be more successful with the paragraph entity:

{% set uri = paragraph.field_slide_image.0.entity.field_image_upload.entity.uri.value %}

{% set url1 = uri|image_style('style1') %}
{% set url2 = uri|image_style('style2') %}
{% set url3 = uri|image_style('style3') %}

For the filter image_style install the module Twig Tweak.


Taxonomy Menu and Views don't work I have vocab Categories, I created it as a menu with Taxonomy Menus. It lists terms in the sidebar, but when clicked on term, it opens empty page saying 'There is currently no content classified with this term.' I have term Hats & Visors, so path to it is shop/hats-visors/ and I expect it to show the list of hats content. These are my settings (screenshots): http://imgur.com/a/odXf6

And to the actual Hat content path is i.e. shop/hats-visors/hat aka /node/5/

You need to associate content with that term.. To do that create a field term reference in content type.. And then edit your content and select term which you would like to associate with your content..

Login as admin
Navigate to list of content types "admin/structure/types"
Choose content type using which your are creating content. Click on Manage Fields next to it.
Add Term Reference field and choose Vocabulary Categories in settings
Create Content or Edit your existing content to associate terms to content using above field you have created.


A better way to show a node-based field in a region outside of the node itself I'm using the 'AddThis' sharing module with Facebook and Twitter so that when a user is on a page of the site they will be able to share it with others. This would include the front page.

The problem I'm discovering is that to use this module you have to add it as a field for a content type...so I can basically add it to all pages EXCEPT the home page.

Putting aside the issue with the front page for a moment, I'd like the sharing buttons to actually appear in the footer, not in the node body itself. The footer is a totally different region. Would this entail me using my .tpl files to change where this specific field appears (ie. hiding it and then showing it again but in the footer for the node)?

Or is there a better way to handle this?

If you aim to keep your footer region's wrappers in page.tpl.php your only option is to:

hide field in node.tpl (tpl file or field display settings)

render the field in page.tpl.php where you want it.
a) use hook_preprocess_page in tepmlate.php to set page=variable = field value (if exists); then print/render that variable in page.tpl.php
b) less elegant and more error prone: render field from page's $node variable

The above is assuming you're using standard drupal's theming system.

THE QUICKEST: Alternatively you can use something like:
https://www.drupal.org/project/fieldblock
to expose your value as a block a,d them place it in whatever region.
this one is compatible with whatever you use; panels DS; stabdrad block stystem; Context....


How can I clear the Menu cache after saving some configuration? I'm in the process of creating my first D7 module, partly based on the tutorial found here. My module creates (among other things) a public page to show some content, and it also has a configuration page (in the Drupal admin) that allows the user to choose the path at which this page must be displayed (e.g. "mypage" or "content/mymodule" etc).

My problem is that saving this value through the configuration form is not enough: you also have to clear the Menu cache, otherwise the old path remains active, and the new one gives you a "page not found" error.

I need that to occur automatically every time this value is changed (or every time the form is submitted). I tried using menu_rebuild() in my validation function, but it's obviously not the right place, because it is triggered before the new data is saved, and so the menu is rebuilt with the obsolete data.

How should I proceed if I want the Menu cache to be automatically cleared after the data has been validated and saved?

Here's my implementation of the pages, via hook_menu:

<?php

/**
 * Implements hook_menu().
 */
function mymodule_menu() {
  $items = array();

  // config page
  $items['admin/config/services/mymodule'] = array(
    'title' => 'mymodule',
    'description' => 'Configuration for the mymodule module',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('mymodule_form'),
    'access arguments' => array('access administration pages'),
    'type' => MENU_NORMAL_ITEM,
  );

  // public page
  $m_title = variable_get('mymodule_title', 'Mymodule');
  $m_title = $m_title ? $m_title : 'Mymodule';

  $m_path = variable_get('mymodule_path', 'mymodule');
  $m_path = $m_path ? $m_path : 'mymodule';

  $items[$m_path] = array(
      'title' => $m_title,
      'page callback' => '_mymodule_page',
      'access arguments' => array('access mymodule content'),
      'type' => MENU_NORMAL_ITEM,
  );

  return $items;
}

/**
 * Page callback: mymodule settings
 *
 * @see mymodule_menu()
 */
function mymodule_form($form, &$form_state) {
  $form['mymodule_title'] = array(
    '#type' => 'textfield',
    '#title' => t('Title displayed on the mymodule public page'),
    '#default_value' => variable_get('mymodule_title', 'Mymodule'),
    '#required' => TRUE,
  );
  $form['mymodule_path'] = array(
    '#type' => 'textfield',
    '#title' => t('Path for the mymodule public page'),
    '#default_value' => variable_get('mymodule_path', 'mymodule'),
    '#required' => TRUE,
  );
  $form['#submit'][] = 'mymodule_form_submit';

  return system_settings_form($form);
}

/**
 * Add a submit handler/function to the form.
 */
function mymodule_form_submit($form, &$form_state) {
  drupal_set_message(t('TEST: The form has been submitted.'));
  menu_rebuild();
}

/**
 * Implements validation from the Form API.
 *
 * @param $form
 *   A structured array containing the elements and properties of the form.
 * @param $form_state
 *   An array that stores information about the form's current state
 *   during processing.
 */
function mymodule_form_validate($form, &$form_state) {
  // page path validation
  $m_path = $form_state['values']['mymodule_path'];
  $m_path_db = variable_get('mymodule_path', '');
  if ($m_path_db != $m_path) {

    if (drupal_lookup_path('source', $m_path) || menu_get_item($m_path)) {
      form_set_error('mymodule_path', t('This path is already used.'));
    } else {

      // attempting to validate path value
      // see: http://drupal.stackexchange.com/questions/167923
      $m_path_parts = explode('/', $m_path);
      $has_invalid_chars = false;
      foreach ($m_path_parts as $key => $part) {
        if (urlencode($part) != $part) {
          $has_invalid_chars = true;
        }
      }
      if ($has_invalid_chars) {
        form_set_error('mymodule_path', t('This path contains invalid characters.'));
      }
    }
  }
}

?>

Edit: more code provided.

Your form code would be helpful to see here to determine if you are using a system_settings_form() function (which seems likely since you are creating a module configuration form) or just a simple form. Regardless, the answer for both is to add a submit_handler to your form.

Basic Form with Submit Handler: https://www.drupal.org/node/717740

If you are not using system_settings_form, than you can add your post-submit actions to a function named after your form definition function, or

/**
 * Add a submit handler/function to the form.
 */
function my_form_submit($form, &$form_state) {
  <YOUR menu_rebuild STUFF HERE>
}

and Form API will automatically find it. If you are using system_settings_form() for your admin form, than you can add your submit handler by adding this before calling system_settings_form()

$form['#submit'][] = 'my_form_submit';


The famous counter module "counter" is marked unsupported The famous counter module "Counter" is marked unsupported.  Is there another good choice for counter?

The Visitors module is pretty good option for the counter module.

Reports provided by the module:

  View pages that have recently been visited.
  View pages that have been hit frequently.
  View pages count per month.
  View pages count per day of month.
  View pages count per day of week.
  View pages count per hour.
  View pages count per host.
  View access log.
  View user activity report (hits, nodes, comments).
  View referrer list.


Adding referencing entities using hook_entity_property_info_alter I have a custom entity "Matching" with a multi value field entity reference jobs that references a node of type job.

function custom_alters_entity_property_info_alter(&$info) {
  $info['node']['properties']['referencing_matching'] = array(
    'label' => t('Referencing matching'),
    'type' => "entities",
    'description' => t("Matchings referecing a job"),
    'getter callback' => 'get_referencing_matching'
  );
}

function referencing_matching($node) {
  if($node->type == "job"){
    $query = new EntityFieldQuery();
    $query->entityCondition('entity_type', 'matching')
          ->fieldCondition('field_job_id', 'target_id', $node->nid, '=');
    $result = $query->execute();
    if ($result) {
      return $result;
    }
}

the "getter callback" isn't expecting an id rather than an array

It looks like you are trying to add a multi-valued entity reference property to a standard node entity. If that's the case, I think you first need to declare the property as multi-valued in hook_entity_info_alter() via the 'type' entry:

$info['node']['properties']['referencing_matching'] = array(
  'label' => t('Referencing matching'),
  'type' => 'list<matching>',
  'description' => t("Matchings referecing a job"),
  'getter callback' => 'get_referencing_matching'
);

See the hook_entity_property_info() notes for more on that.

Then, in the getter callback I believe you need to return a list of entity ids, something like:

if ($node->type == "job"){
  $query = new EntityFieldQuery();
  $query->entityCondition('entity_type', 'matching')
        ->fieldCondition('field_job_id', 'target_id', $node->nid, '=');
  $result = $query->execute();
  if (!empty($result['matching'])) {
    return array_keys($result['matching']);
  }
}

I have not tested that specific code, but this was the pattern that I used in a similar example of my own.


how to print google map field value in a page tpl I am trying to print a value of submitted for a google map field in a page.tpl.php file. I used below code to print but got a error message. I am able to print other field types using similar code but unable to do the same for map filed. Please help

<?php
  $node=node_load(41);
  print "
".$node->field_add_map['und'][0]['GoogleMapField']."
";// print styled image
?>

For a start don't load the node in the template file like that.

If you want to load a node do it in a template preprocess function in your theme's template.php file, like this for example:

/**
 * Variable preprocess function for the page template.
 */
function THEMENAME_preprocess_page(&$variables, $hook) {
  // Load a node and save it to the variables array.
  // This will then be available in the variable $node, in the page.tpl.php template.
  $variables['node'] = node_load(41);
}

However don't use $variables['node'] in the page template because it is already in use.
If you are on a node page then that variable will already be populated with the node object of the current page, so in your template you can access it using $node.

If you are aloading a node that isn't the current page node then you can do it your way but give the variable a different name, like $variables['map_node'] for example, which would then be available in the template file as $map_node.

On to the field printing.

The problem is you are trying to print the GoogleMapField property of the field value, which as far as I know doesn't exist.

The values in this field type are:

lat
lon
map_width
map_height
zoom
name

So doing what you are doing you could print those out, however I'm thinking you probably don't want those either.

So you want to print the rendered field item.
There are a few ways this can be done but a good option is using the field_view_field() function like this:

/**
 * Variable preprocess function for the page template.
 */
function THEMENAME_preprocess_page(&$variables, $hook) {
  // Load a node and save it to the variables array.
  // This will then be available in the variable $node, in the page.tpl.php template.
  $variables['map_node'] = node_load(41);
  // Get the rendered markup for the map field to print in the template.
  $variables['rendered_map'] = field_view_field('node', $map_node, 'field_add_map', 'full');
}

That example uses whatever display configuration you have set on the "full" display mode for your node type for that field. You could use "teaser" or some other view mode if you prefer.
You could even add a custom view mode specifically for this if it suits your use case.

Then in your page template you could do something like this to print the map using the render() function:

if ($rendered_map) {
  print render($rendered_map);
}


JQuery via the .info file isn't working I'm using/experimenting with Zen on my drupal site, and have just inserted a js file named alert.js into my theme's js folder.
The file has the following code:

  (function ($){
Drupal.behaviors.kiwiAlert = {
  attach: function(){
    alert('Hello World');
   }
 };
})(jQuery);

I followed up by making the necessary changes in my .info file, by inserting the following snippet:

 scripts[] = js/alert.js

Since my site is in development mode I've set the cache to be cleared/theme registry to be rebuilt upon each page load, but just in case I cleared my cache again.
And nothing, the alert message doesn't show, why is this not working??

PS: I also tried the following code in the js file, in the same context, but to no avail :C

 alert("Hello World!!");

Any and all answers will be much appreciated :)

Answered in comments, but just moving the answer here for posterity's sake.

The theme was loading the .js file, but the permissions were restricted, so the server was returning a 403 error. Changing the permissions fixed the issue.


Drupal 8 block cache I created a simple block where it shows good evening or good afternoon depending on the time.

But the problem is that i have to delete the cache otherwise it will stay at good evening ...

How do i disable the cache for this specific block ?

Here is the twig page:

  {% block content %}
{{ content }}
<p>{{ "now"|date("d,n,Y") }}
{% if "now"|date("H") >= '10' %}
 good afternoon,
{% else %}
good evening,
{% endif %}
</p>
{% endblock %}

This will disable the cache.

$build['#cache']['max-age'] = 0;

Block Cache API is removed; blocks now use standard caching patterns


How do i create nested tabs in drupal 7 view? I am trying to create an image gallery from view.

I have a content type called "Photo-Gallery" with fields  title of event,year,month and images

I have created a view with this content type and created page with Unformatted list.I am trying to make a gallery based on the following layout. How can i code custom view template?I want this by Year wise and then Month .

Unfortunately i am stuck on half way. Could you please suggest me a proper way to code the  view to get the exact result.

Awaiting quick replies.

You could use Quick Tabs Module along with Views Module to achieve this result.

A simple overview to achieve this might be:

  Since Quicktabs uses blocks as tabs, If you create a views blocks for each
  single items of a content type and then add them to quick tabs
  manually.

Look through this http://mtt.desk.com/customer/portal/articles/992921-how-to-add-quick-tabs-with-multiple-view-blocks-inside-a-specific-page to get an idea.


Update drupal module with existing custom changes I am new to drupal and am wondering when I update a drupal module, say the menu module for example.

If I have some existing custom changes to the module, is it ok to just update the module and it will retain all my custom changes once the update is completed?

Or is it going to overwrite all my custom changes and I would have to "re-do" them or will it actually create a merge conflict during the update?

I am not entirely sure the practice in updating modules where there are custom changes added to it so any insight would be helpful.  This is for drupal 8.

Thanks!

You are not supposed to hack modules or core directly, because when you update drupal and modules your changes will get lost.  If you have some valuable changes or corrections that others might benefit from its best to submit a patch to the issue queue of the module and if maintainer accepts them you benefit as well.

If maintainer does not decide to use your changes you can also consider making your own module or perhaps with a custom theme you can  accomplish what you want to do.  Drupal has a great system in place to override parts of code with your own logic without hacking core or contributed modules.

If you actually decide to keep those changes as hacks you will have to do your own merge confict resolution as drupal internal update process or even drush updating will not do it for you.


Drupal 8 - How to Reference Flags Twig Template without showing full content? I'm using Drupal 8 to construct a page, where flags are required for Adding Videos to Favorites. I am using the Flags Module, but it's a custom template, so I didn't use the {{content}} reference directly. Instead I'm using the machine names of each field in displaying and styling the node. I reference them using {{content.field_fieldname}}

The problem is that I'm unable to reference the flags that I have created using the Flags Module. They are appearing on other basic pages and articles (when I turn on those areas while editing the flags), but they fail to appear in the custom template that I have created for a node.

Could anyone please help me with this? Any sort of help is highly appreciated. Thank you.

FOUND IT

Alright guys, so it's simple.

You reference the flag this way in your Twig Templates:

{{ content.flag_machinename }}

Cheers.


Anyone know how to build a menu like this? We are redesigning a site for a client and they're wanting to create a menu similar to the one found here (the big menu below the header, not the hamburger menu at the top left):

http://www.business.vic.gov.au/

Looks like it may have been built from scratch w/ jQ but thought someone might know of an existing module or theme that could get us started in the right direction.  Appreciate any advice or help.

Thanks!

Welcome to stackexchange. When asking a question please try to be as specific in your question as possible. Try describing what you want to know – also using screenshots or wireframes is ok – but please avoid forcing others to ckick on a link to understand your question. Questions like "How can I do <link>this</link>?" are usually not very likely to get a lot of attention from the community.

That said – I did click the link – and I suppose whether there is a module providing this effect/functionality or not is probably not that important since you could achieve a fairly similar effect with either a drupal menu or a drupal view and some javascript / jquery / ajax (for loading the second level dynamically) and some additional css3 for the sliding effect.

You could probably even skip the scripting part, display a standard list of links, hide the non-active second level items and use css3 to slide the second level in once it's needed. Asking ofer at stackexchange might be the more suitable forum to ask about this (here is for example everything about 'slidetoggle').

I'm sorry this is probably not the answer you were looking for – but maybe if you provide more information on what you want to achieve someone else can point you to an appropriate module.


Error when I try to make a local translate. I get this error when I try to make translation:

  Not saved locally due to invalid HTML content.

take a look a my capture, first one shows the text to be saved as the translation, and the second capture shows the error message:

It's happening because you have <div> tags in your translation text.

locale_string_is_safe(), the function used to make sure the string provided for translation is safe, has this to say about the allowed tags:

  The allowed tag list is like filter_xss_admin(), but omitting div and img as not needed for translation and likely to cause layout issues (div) or a possible attack vector (img).

So basically you need to remove the <div> tags and your translation will work just fine.

If you're interested in the chain of functions called so you can check the logic for yourself, it's as follows:

l10n_client_save_string()
_locale_import_one_string_db()
locale_string_is_safe()

Since locale_string_is_safe() does allow <span> tags you might consider using those instead. If you need the element to be block level then you can just use CSS to do that.


Views: group by content type in an arbitrary order Note: I spend a lot of time in this question explaining, what I've been trying to do, but the end goal is to be able to sort by content type in an arbitrary order.  I'm then grouping on content type, and getting headings in my results as desired.  If you can show me how to do it without hook_views_query_alter() I'd be just as happy, though why my solution isn't working is giving me an ulcer.  I'd prefer to avoid creating a whole bunch of attachments since I'm dealing with about 20 types here, but I think that is the next thing I'll have to try if nobody can help me.

A few other answers here, have gotten me to where I feel I'm close, but I'm getting not results, hopefully someone here can see what I'm doing wrong.

My actual setup is more complex than this.  Basically I have a variable in settings that gives me some details about the different content types I'm dealing with, including a weight value for each.  I'm building my order by clause using those weight values, but that doesn't seem to be the problem, so here is the query taken to it's simplest form:

Given a view that loads a set of nodes of at least two different types, one of which (for the purposes of this function has a machine name of 'brief' and a human readable name of Briefs):

/**
 * Implements hook_views_query_alter().
 */
function MYMODULE_views_query_alter(&$view, &$query) {

    if ($view->name == "view_name" && $view->current_display == "display_block_name") {

        $caseclause = 'CASE node_type WHEN "brief" THEN 1 ELSE 2 END';
        array_unshift($view->query->orderby, array(
            'field' => $caseclause,
            'direction' => 'ASC'));
    }
}

I would expect this to give me the node listing with Briefs listed first, and other types listed afterward.  Instead I get no results.  If I remove the alteration to $view->query->orderby I get results.  I've tried checking for "Briefs" instead of "brief".  I got the column name, by adding it as a sort in the view and seeing what the view itself used, but just in case I've also tried node.type and type as the column name to put in the case statement.  I tried doing all of this with the $query object too, just in case.

I tried adding the CASE clause as $query->addExpression, setting an alias of order_col for the expression, intending to then order by that column, but the whole page stopped showing up.  It is possible I did something wrong on that attempt, if you can make that work, please let  me know.

So here's what I need:  How can I make a CASE statement work in hook_views_query_alter(), or failing that, how can I sort content type by an arbitrary order?

Here's a really brief section of the configuration variable that I have in settings.php that I'm trying to get the weight value from to do my sort.

$conf['pubtype_bundles'] = array(
    'brief' => array(
        'name' => 'Briefs',
        'weight' => 5,
        'description' => 'Issue Briefs, Policy Briefs, and Briefing Notes',
        'help' => '',
        'types' => array(
            'issue' => 'Issue Brief',
            'policy' => 'Policy Brief',
            'briefing' => 'Briefing Note',
        ),
        'typehelp' => '',
    ),
    'book' => array(
        'name' => 'Books',
        'weight' => 10,
        'description' => '',
        'help' => '',
        'types' => array(
            'book' => 'Book',
        ),
        'typehelp' => '',
    ),
);

When you want to do arbitrary sort, U must be having your own sorting routine/algo/criteria?
When you have that then you can add a "global php" field in sort criteria and then u can use a setup code(if required) and then you can write your sorting logic in "sort code".


Cancelling user account set draft pages to published When we cancelled a user account using the Delete the account and make its content belong to the Anonymous user method, we found that the author was set to Anonymous for the pages they were set as the Author, as expected. The problem is that many pages that were set to Draft were then updated to have their Author set to Anonymous and published, which is not a desired outcome. These drafts were never published and always kept in that state.

We have a view that pulls all pages that are published and content type = Basic Page. This started to pull in all the draft pages because they were set to published after the user account was cancelled.

How can we cancel an account without publishing pages that were are set to Draft moderation state?

Steps to reproduce:

Create 10 draft  Basic Pages (do not publish) where the Author is set to content admin
Cancel the user account for content admin by using Delete the account and make its content belong to the Anonymous user method.
Under /admin/content, observe the pages are now in published state with Author set to Anonymous

Current modules being used for revision:

workbench
workbench_moderation

Just did a test with the steps you provided.  I tried with just 1 node unpublished and cancelled the user and the node was assigned to the anonymous user BUT the node stayed unpublished.  I don't see any reason why the result would be any different if I tried with 10 nodes.

I believe a contrib/custom module is at fault.  See if you have any modules that deal with publishing/unpublishing content you have to disable them and test if the problem is gone.

If the above does not help I would try to disable all modules one by one and testing to see if the problem is gone on each step.  Once you find the problematic module you can post the results in the issue queue and you might also discover a patch resolving the issue.

You can also post a list of your enabled modules and someone might be able to spot a module that could be a potential candidate to be causing this behaviour.


Can't clear cache as drupal_test.cache_filter doesn't exist I run into an issue, I can't clear the cache anymore as I get this error:

PDOException: SQLSTATE[42S02]: Base table or view not found: 1146 La table 'drupal_test.cache_filter' n'existe pas: TRUNCATE {cache_filter} ; Array ( ) in cache_clear_all() (line 168 of C:\wamp\www\drupal-7.41\includes\cache.inc).

I've read a few posts on stackoverflow with the same problem but different table and I wonder if I can try to apply the same solution (I don't know much sql so I'm not sure if I can just copy and paste from any solution as I don't want to make things worse). Some solutions seem to be dropping and recreating a table called cache_field, others cache_rules but I couldn't find anything for that specific table drupal_test.cache_filter. Do you reckon it's worth trying both of them, or does anybody have another solution? Last time I had this problem - I can't remember if it was the same table though - I ended up reinstalling the whole drupal, and I'd like to avoid this.

Did you try to run drush rr in advance? It would clean up your registry of modules an quite often fixes those issues.

Maybe some module got moved or if removed try to figure out what has been removed, re-install it and try again.


Bulk translate a single node Using the Internationalization Module I have configured multiple languages (all English, but different countries). We are using the languages to present variable data on pages but don't necessarily want to translate the body. For example, Canada and the US have different phone numbers and currency but the language is still English and the copy may or may not need to be changed.

For the most part a node is Language Neutral (und) but when we need a single translation for the node, we still need to create the remaining translations as well. This is a lot of extra clicks and we have to do this hundreds of times.

Is there a way to create all of the translations with the click of a button? I spent a good deal of time searching with no luck and any help would be greatly appreciated.

The Language Fallback Module solved this for me. Rather than translate a dozen nodes, this module allows you to translate only those nodes that require it and have the others fallback to a default.


Hosting Multiple Domains seamlessly with same site code, theme, modules, data etc. not a multisites situation! I would like to use D7 to support two domains with same code, themes, modules and even database and content, completely transparent to the end-user.

So, user of oxustech.com would see only oxustech.com and user of oxustechnolgies.com would see only oxustechecholgies.com (not be redirected to oxustech.com).

We don't want to use forwarding/frame forwarding. because frame forwarding will hide the full url and will show every url as oxustechnologies.com only.

The site is under shared hosting and we don't have enough permission to change the Apache setting.

Pointing oxustechnologies.com to same htdocs didn't work.

This has worked for me in the past. Given the following assumptions:

I assume the server is already configured to direct requests for the domain oxustech.com to the correct site (meaning that this is already working for you)
I assume Drupal is finding for your site's settings.php file in the directory /sites/oxustech.com/settings.php
I assume you want to make requests for the domain oxustechnologies.com to show the SAME site (same database) as oxustech.com, but displaying the domain oxustechnologies.com as the base URL for all pages accessed through this requests.

IF this is the case, this has worked for me. Try this:

In the /sites directory, rename the file example.sites.php to sites.php
Add the following line at the end: $sites['oxustechnologies.com'] = 'oxustech.com';

This will effectively tell Drupal that oxustechnologies.com is an "alias" of oxustech.com, will use all settings (including the database) for oxustech.com. It will also always display oxsutechnologies.com as the base URL when you navigate inside the site. But people who access the site through the name oxustech.com will continue to see that as the base URL.


How do I add custom contextual links in a block? I want to add more contextual links (e.g. "Edit Block") to my block apart from the existing "Configure Block".

How can I achieve this?

I know that this blog post is 100 years old, but it still applies:

http://bleen.net/blog/easier-way-add-contextual-links-drupal-7

The basic idea is to make use of hook_contextual_links_view_alter

For example:

function MYMODULE_contextual_links_view_alter(&$element, &$items) {
  // This hook is called for EVERY set of contextual links
  // on a page.  We first want to check the $element to make
  // sure we are adding a link to the correct list of contextual
  // links. In this case we only want to add a link to blocks
  // created by the "search" module. We just add links using the
  // same array structure as is used by theme_links.
  if (isset($element['#element']['#block']) && $element['#element']['#block']->delta == "site_tweets-site_tweets_block") {
    $element['#links']['social-networks'] = array(
      'title' => 'Edit social network links',
      'href' => url('/admin/config/system/site-information', array('absolute' => TRUE)),
    );
  }
}


Adding list of nodes to another node I have a content type (named "Category") and another content type ("Article"). I want to "Category" nodes have similar functionality as taxonomy term in a way of option to assign "article" nodes to them and display list of "article" nodes teasers on the "Category" page too.

For example: Lets say I have "Category" node named "People". And several "Article" nodes ("Joe", "Frank", "Peter") somehow (part of my question) assigned to "People". When I go to "People" page, I want to see this node content and below also teasers of all assigned "Article" nodes. And I want this not only for a specific node, but for all nodes of content type "Category". How to attain this? Maybe something like taxonomy terms view, but adapted to nodes instead of taxonomy terms?

I know it's easy with taxonomy, but I want to avoid that way - because of buggy taxonomy menu and other things. Thanks

You can use Entity Reference module to create relations between the nodes you need.

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

And it works well with Views (for both forward and backward references)


How to suppress "new" indicator for imported content? Drupal works off a "history" table to keep track of the content you have looked at (in the last 30 days).
When you import old content that users have seen already it's shown as "new" because there is no entry in the history table yet.

I could insert records into the history table for all users and all content. I remember someone posted on d.o. about a "trick" that doesn't require inserting records into history, but I can't find the reference now.

Any suggestions?

You could suppress this in the theme layer, by doing a rewrite on the rendered output? That might be much safer than any kind of database hack.


How do I modify a webform submission field right before it is saved? When an end-user is submitting data entered in a Drupal 8 webform, I would like my custom module to modify a field that is on the same form based on values of other fields. I am having trouble accessing the values of the submitted data and also setting the value of the field that I wish to change before being saved.

There is a sample webform API file included which has some starters for hooks. A hook which I found may be useful is the following.

function hook_webform_submission_form_alter(array &$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {}

I used the dpm() to print the values of these variables. The $form_state variable has the data submitted, and I know I can use the $form variable to change these values before being saved.

How can I get values of the data submitted and also set the value of another field on that same page before the submission is saved? In Drupal 7 this was fairly straightforward, but with Drupal 8 navigating the array and object structures of variables is not as transparent.

You can use preSave method in your handler. Please check out the Webform module handler tests module which is part of Webform codebase, it has TestWebformHandler.php file which defines the submission test handler which displays a status message for every handler event.

For example:

<?php

namespace Drupal\webform_test_handler\Plugin\WebformHandler;

use Drupal\Core\Form\FormStateInterface;
use Drupal\webform\Plugin\WebformHandlerBase;
use Drupal\webform\WebformInterface;
use Drupal\webform\WebformSubmissionInterface;

/**
 * Webform submission test handler.
 *
 * @WebformHandler(
 *   id = "test",
 *   label = @Translation("Test"),
 *   category = @Translation("Testing"),
 *   description = @Translation("Tests webform submission handler behaviors."),
 *   cardinality = \Drupal\webform\Plugin\WebformHandlerInterface::CARDINALITY_SINGLE,
 *   results = \Drupal\webform\Plugin\WebformHandlerInterface::RESULTS_IGNORED,
 *   submission = \Drupal\webform\Plugin\WebformHandlerInterface::SUBMISSION_REQUIRED,
 * )
 */
class TestWebformHandler extends WebformHandlerBase {
  /**
   * {@inheritdoc}
   */
  public function preCreate(array $values) {
    $this->displayMessage(__FUNCTION__);
  }

  /**
   * {@inheritdoc}
   */
  public function postCreate(WebformSubmissionInterface $webform_submission) {
    $this->displayMessage(__FUNCTION__);
  }

  /**
   * {@inheritdoc}
   */
  public function postLoad(WebformSubmissionInterface $webform_submission) {
    $this->displayMessage(__FUNCTION__);
  }

  /**
   * {@inheritdoc}
   */
  public function preDelete(WebformSubmissionInterface $webform_submission) {
    $this->displayMessage(__FUNCTION__);
  }

  /**
   * {@inheritdoc}
   */
  public function postDelete(WebformSubmissionInterface $webform_submission) {
    $this->displayMessage(__FUNCTION__);
  }

  /**
   * {@inheritdoc}
   */
  public function preSave(WebformSubmissionInterface $webform_submission) {
    $this->displayMessage(__FUNCTION__);
  }

  /**
   * {@inheritdoc}
   */
  public function postSave(WebformSubmissionInterface $webform_submission, $update = TRUE) {
    $this->displayMessage(__FUNCTION__, $update ? 'update' : 'insert');
  }
}

Then you can use a standard ways of modifying your $webform_submission.

See also: Way to do an action after a webform submission has been created.


How do I display a field twice in a node's display? In my full node display I want to show the same field twice, in a different mode each time.

Specifically, I have a collection of images, I want one up top and the rest below in my already existing gallery view of the node. What I don't know how to do is to show the field for my image twice in a single node display. Is there a module that will allow me to do this with a minimum of fuss?

Should be pretty easy if you use Display suite:

Add a dynamic field (admin/structure/ds/fields/manage_ctools) and select the entity type (node).

Your new field should be in the manage display tab of the entity type selected, activate it (put it in the section you want).

Click on the gear icon and then 'select content'

Then drill down in the options (node -> the field you would like to duplicate)

If you don't use display suite just print that field in a tpl.php file.


Best method to upload / link to multimedia files in D6? I need a solution to allow users to upload multimedia files (audio, video, images, documents, links to such) to a node. Ideally, something like a combination of FileField + Embedded Media Field that supports different media and styles the viewer accordingly.

I know that module Media is supposed to solve this problem on D7, but I'm looking for a D6 solution.

I've tried:

jQuery Media but it doesn't handle many file types that I need - plus I prefer a server-side solution.
Styles + FileField Styles but they just don't work.

Have a look at ShadowBox, it supports a lot of formats and the FileField module which I think is essential for your set up:

  Media extensions supported:
  - Images (png, jpg, jpeg, gif, bmp)
  - Video (avi, mpg, mpeg)
  - Quicktime (dv, mov, moov, movie, mp4)
  - Windows Media Player (asf, wm, wmv)
  - Flash (swf, flv)
  - IFrame (asp, aspx, cgi, cfm, htm, html, pdf, pl, php*, phtml, rb, rhtml, shtml, txt, vbs)

Source: Comparison of Lightbox-type modules.

There's algo the Lightbox2 module with is aroung since a long time and have quite a big installed base.


Finding commerce custom fields inside a rules loop I have a few custom fields added to line items (so buyers can add specific information for each item they add to their cart.)

I need access to those custom fields using rules. However, I can't seem to get at them inside of a loop.

In order to get access them in the first place, I used "Entity has field", and they show up just fine to use in actions, until I get inside a loop. line-items:... doesn't include those custom fields.

What am I missing?

The trick for this is to use a component.

Create a new component, and check for the fields using "entity has field". Then, in the original rule, loop over the line items, and put the component inside that loop.

The kicker is that it is impossible (possibly? not I couldn't find a way) to get other product-level fields into this component.


I only want to modify one tpl.php for a theme, do I need to copy the base theme? I only need to have one tpl.php added to a theme,but the theme I am using is not my own.  If I still want to have this theme as my "base" and then create my own theme with the tpl.php using a theme suggestion I want, how do I get this to work.

I have tried setting the base theme as the default and then creating my own theme with the tpl.php I want and enabling it, but it isn't working. If this is the correct way to do this, what is the minumum needed in the .info file and the folder for this to work?

The minimalist amount you need for a subtheme info file are the 2 required keys, name & core, plus the declared base theme key, base theme.

If you a create info file with those keys, copy over the tpl.php (e.g. page.tpl.php) from the base theme, modify it, flush caches (to rebuild the theme registry), and use the Enable and set default from the theme administration page, you should have a working subtheme.

See the d.o. docs on creating a subtheme for more info.


Drupal Commerce and Views Trouble I am using Drupal Commerce and Views to make a products page that has a number of elements on it that are somewhat complex.

So far my page is a simple view that lists products as a table that also has some filters that users can modify to sort through products. However I am having trouble adding fields to that view to add the other elements i want to display.

What i need:

I need to add a "Add to cart" button for each product displayed.
I also need to add a product image that changes to the smaller displayed images when clicked.
In addition I also want to add a number of custom text fields that do not change when the user is applying the filters to the page.

What I have done so far:

I have attempted to use Views Field View and create sub views and add them to a parent view, however I am having trouble getting the sub views to show up.
Found a couple of sites that show methods of adding "Add to Cart" buttons manually by editing the files. But i wanted to make sure there was not module for it already.

If anyone can point me in the right direction i would appreciate it.

It sounds like you need to make a View of product display nodes, and not product entities.

The product display node has the product reference field on it, which provides the 'add to cart' formatter.

You can also show the product image and add other arbitrary text fields to the display node


Where is the information in the node_info hook displayed in drupal I am beginning with drupal. I cannot see where the information which I write in the hook node_info displayed in drupal. What is the link to check it?

You should see it on the add content page. If you don't, either you need to clear cache, the module isn't enabled, or the module is coded incorrectly.


How can I have a node with the URL /themes I've created a node and have given it the URL /themes. In full: http://site-name.com/themes.

Permissions on the Drupal system folder 'themes' mean that the URL /themes gives: 403 forbidden.

Is there anyway to have a node with /themes? I'd prefer if possible to keep my current file structure as I think it would be difficult to change with my current host (Pantheon).

In your .htaccess file, the URL re-write has the a code to point the path to the respective folder, if present.. you can change that!


Organic Groups and Panels I've got Panels working with Organic Groups (d7) using the documentation about "Drupal 7 Panels integration guide (OG 7.x-1.x)". It describes how to create a node panel that detects when you are viewing a group and then displays the layout accordingly.

This is great, however, I would now would like to create a new variant that would allow more specific customization of a specific group. Say for example I have a special group called "Education" that would need to arrange their group home page slightly different from others.

I have made some adjustments to what I think would do the trick, but it does not work. Here is what I have done:

Cloned the original varient from the documentation
Under Contexts, added a new context "Organic groups group" and specified the group id of the "Education" Group
Under Selection rules, added a new "Context exists", and selected my context created in the above step
Made some adjustments to layout
Saved, and reordered variants to make this one come first

This worked.... however for some reason it applies to all groups not just to my "Education" group. Again, I would like to have a custom layout for my "Education" group, and have a default layout for the rest. I'm still new at panels, can anyone spot what I'm doing wrong based on my description?

You could also try specifying by url string "education/*" or even node ID instead.


How to add custom class in custom module? I am not able to add custom class in custom module, I need to add class "ajax-link" in the anchor link to make it ajax based page load  .

function hook_node_view(array &$build, \Drupal\node\Entity\Node
$node, \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display,
 $view_mode) {

 if ($display->getComponent('prevnext_next')) {
$build['prevnext_next'] = [
  '#theme' => 'prevnext',
  '#direction' => 'next',
  '#text' => t('Next'),
  '#nid' => $previous_next['next'],
  '#attributes' => array(
  'class' => array(
  'ajax-link'
      ),
    ),
  '#url' => Url::fromUserInput('/node/' . $previous_next['next']."?an=left")->toString(),
  '#void' => empty($previous_next['next']),
];
 }
   }

What am I doing wrong in the code ?

I want to create link something like this:

Next

you can try code :

  $url = Url::fromRoute('entity.node.canonical', ['node' => $previous_next['next'],'an'=>'left']);
  $url->setOptions([
      'attributes' => [
          'class' => ['ajax-link custom-class']
      ],
  ]);

  $build['prevnext_next'] = [
      '#type' => 'link',
      '#title' => t('Next'),
      '#url' =>  $url,
  ];


Grab URL as file upload for Drupal 7? When creating a content type, you have the option of adding a "file upload" field. How can I extend the functionality of this upload file to allow for the option of simply entering a URL instead of manually downloading the file and uploading it again? I basically want another field, called URL, where I enter the URL of the image. Drupal must then grab the URL as if though I uploaded it. Which means I must be able to "press upload" and actually see the thumbnail as per normal functionality.

I have a site from which we often grab images, but every time I first have to download it. It would save me a lot of trouble if I could just provide the URL and let Drupal do its thing.

You're looking for the FileField Sources module:

  FileField Sources is an extension to the FileField module. The FileField module lets you upload files from your computer through a CCK field. The FileField Sources module expands on this ability by allowing you to select new or existing files through additional means, including:

  Re-use files by an auto-complete textfield
  Attach server-side files uploaded via FTP
  Transfer files from a remote server (cURL required)
  Paste a file directly from the clipboard (Drupal 7 only)
  Select existing files through the IMCE file browser

Emphasis mine.


How to implement Likert Scale with EntityForm? I was using Webform, but I need to provide an autocomplete field to reference a node of a particular type. I see many recommendations to dump Webform and use EntityForm, but the first question type I need to reproduce is a Likert scale. I don't see any discussion of how to create this fundamental question type with EntityForm. Do I really need to build each Likert scale question by typing option names/ids into a select field? Would there then be a way to report on the sum of a set of items in my form?

A Likert Item is a question like "What do you think of this module? Answer 1 (strongly disagree) to 5 (strongly agree)." A Likert Scale is the sum of responses to a series of Likert Items.

Webform has a very nice implementation.

[...] you can make form elements that don't have directly corresponding elements in the FAPI. The "grid" component is a good example of this, and in this case, I think it's exactly what you're wanting. You can effectively create a likert scale by creating "options" along the top with these keys:

-2|Strongly disagree
-1|Disagree
0|Neutral
1|Agree
2|Strongly agree

Source: https://www.drupal.org/node/291658


How to link the file icon to the file and to hide the filename? I have uploaded files to be displayed in a table together with some other informations (title, tags etc). One row of this table the filename which links to the downloadable file. Next to the filename a file icon is displayed be daefault, which isn't linked.

That's how it looks now:

I want the filename to be hidden and the file icon linked to the downloadable file.

What functions would I have to override to make that happen? Or what other way may exist?

The problem with generic file display is that icon is not linkable, therefor a CSS solution is useless.

So in order to make the icon linkable you need to create another file display formate or alter theme_file_link

My solution is to add additional display formate, code as follow:

/**
 * Implements hook_field_formatter_info().
 */
function mymodule_field_formatter_info() {
  return array(
    'mymodule_link_icon' => array(
      'label' => t('Linkable icon'),
      'field types' => array('file'),
    ),
  );
}

/**
 * Implements hook_field_formatter_view().
 */
function mymodule_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  $element = array();

  switch ($display['type']) {

    case 'mymodule_link_icon':

      foreach ($items as $delta => $item) {

        $file = (object) $item;

        $url = file_create_url($file->uri);

        $icon_directory = variable_get('file_icon_directory', drupal_get_path('module', 'file') . '/icons');

        $icon = theme('file_icon', array('file' => $file, 'icon_directory' => $icon_directory));

        $options['attributes']['title'] = check_plain($file->filename);

        $options['html'] = TRUE;

        $link_icon = '' . l($icon, $url, $options) . '';

        $element[$delta] = $element[$delta] = array('#markup' => $link_icon);
      }

      break;
  }

  return $element;
}

After you implement the above code in a module and enable it, make sure to change field formatter option in your view to Linkable icon


Develop new content type for xml to html translation (Drupal 6) What I would like to achieve is the this:

Develop new content type
Add two fields to the content type : XML, XSLT,  /  text areas
When I use this content type later on I want to be able to paste some XML into the XML field, some XSLT into the XSLT field. When I save my new content I want the XML to be translated into HTML.

So in view mode I would always see the HTML, 'edit' mode would give me away of manipulating the XML / XSLT

I started following this tutorial: http://drupal.org/node/231019. But that does not cover how /where to save my new fields.
This is how far I got following the tutorial:

/**
* Implementation of hook_node_info().
*/
function xmlparser_node_info() {
  return array (
    'node_amlparser'=>array(
    'name'          => t('XML Parser'),
    'module'        => 'xmlparser',
    'description'   => 'This module takes XML and XSLT to generate HTML'
  )
 );
}
/**
* Implementation of hook_perm().
*/
function xmlparser_perm () {
  return array ('create xml content','edit own xml content');
}
/**
* Implementation of hook_access().
*/
function xmlparser_access($op, $node, $account) {
  if ($op == 'create') {
    // Only users with permission to do so may create this node type.
    return user_access('create xml contene', $account);
  }
  if ($op == 'update' || $op == 'delete') {
  if (user_access('edit own xml content', $account) && ($account->uid == $node->uid)) {return TRUE;}
  }
}
/**
* Implementation of hook_form().
*/
function xmlparser_form (&$node, $form_state) {
  $type = node_get_types('type', $node);

  $form['title'] = array(
    '#type' => 'textfield',
'#title' => check_plain($type->title_label),
'#required' => TRUE,
'#default_value' => $node->title,
'#weight' => -5
  );
  $form['xml'] = array(
    '#type' => 'textarea',
'#title' => check_plain('xml'),
'#required' => TRUE,
'#weight' => -5
  );
  $form['xslt'] = array(
    '#type' => 'textarea',
'#title' => check_plain('xslt'),
'#required' => TRUE,
'#weight' => -5
  );
  $form['body_filter']['body'] = array(
    '#type' => 'textarea',
'#title' => check_plain($type->body_label),
'#default_value' => $node->body,
'#required' => FALSE
  );
  $form['body_filter']['filter'] = filter_form($node->format);
    return $form;
}

So this brought me to the point that my content type comes up when creating new content - cool. But where do I need to go now to actually save my values? Where would I save my HTML once the XML is parsed on submit?

I know quite a few question, but any input would be great appreciated!

Thanks,
 Uwe

Here is an idea that will keep coding to a minimum using already existing modules:

Using CCK if D6 or the fields if D7 create a regular content type and add an extra field for the XML as I will use the automatically added body to store the XSLT. On the content type display section hide the XSLT field, this way the data is collected, but it is not shown when the node is been view.
I will install the custom formatter module to create a text formatter where I can apply the XSLT to the XML and then present it as HTML.
If I can not apply the formatter directly to the body field in the content type display settings I will the hide both fields (body & XSLT) and using views attachment in D6 or EVA in D7 attach the body field with the formatter applied to the content type.
Last but not least if I plan to re-use this setup in others sites I will use the "Features" module to exported.


Why is my custom module giving a "page not found" message when using https? I have a custom module that is a form. The first section in the hook_form() function is

if (!$_SERVER['HTTPS'] == 'on') {
    drupal_goto('https://mysite/mymodule');
}

If I comment out this section, the form works as expected. If the https redirect is left as is, I get a page not found error. This occurs only for unauthenticated users. If I am logged in, the form displays correctly.

I am on Drupal 6

EDIT: I turned off caching on my Drupal site and the form works again. The caching must have broken my form. I will see if I can find a way to not allow the form to be cached by Drupal.

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}

or take a look at this article


How is a theme template file picked up? Does any one know how Drupal 8 picks up theme template file? I mean in source code.

I have module which use a custom template file for a custom block , but the custom template file was not been picked up.

I have tried many different ways, but none working, so I have decided to looking Drupal 8 source code to find out , but I am unable to find out exact source code that picks up the theme template file.

I had a similar problem and tried:

{% include 'my-template.html.twig' %}
{% include directory ~ '/templates/my-template.html.twig' %}

but ThemeRegistryLoader wouldn't recognize 'my-template'. This syntax worked:

{% include 'modules/custom/my_module/templates/my-template.html.twig' %}


Cache drupal private images Is there a way to cache drupal private images in client browser? I have a website with private profile images that are used many times and I want to cache them even for a very few time.
How can I do that?

Thanks

I finally found how to handle it : there is a hook_file_download where i can add and set header for the file :

function mymodule_file_download($uri){

// Getting file info
  $info = image_get_info($uri);

  // For images files
  if(isset($info['mime_type']) && strpos($info['mime_type'], 'image/') === 0){
    // cache max-age : 1 day
    // expire-date : now + 86400 s
    // etag using a hash of the file size variable
    return array('Cache-Control' => 'max-age=86400, private',
                 'Expires' => gmdate('D, d M Y H:i:s', time() + 86400) .' GMT',
                 'Last-Modified' => gmdate('D, d M Y H:i:s', time() - 86400) .' GMT',
                 'ETag' => strtr(md5($info['file_size']), 0, 10));
  }
}