Adding button to toolbar for non-admin Im trying to add a button to the toolbar for my module. Now I know I can just it in the menu and blah blah but I want it to make it when the module is activated. I think im on the right track using hook_menu however it doesn't exactly specify the callback to do this.

This is what I have so far....

function mysite_form_menu() {
$items = array();
$items['admin/config/mysite_form/ads'] = array(
    'title' => 'mysite Ad\'s',
    'description' => 'Allows administrators to adjust ads.',
    'page callback' => 'ads_page_callback',
    'access callback' => 'current_user_hide_tabs',
    'page arguments' => array('ads'),
    'access arguments' => array('administer editor mysite settings'),
    'file' => 'thank_you_ads.inc',
    'file path' => drupal_get_path('module', 'mysite_form'),
);
}
function current_user_hide_tabs() {
  global $user;

  if (isset($user->roles['3']) || isset($user->roles['5'])) :
  return true;
  else :
  return false;
  endif;

}

This is a image of the toolbar I am talking about so there is not any confusion.

The buttons on the toolbar are automatically added when the module is enabled, as long as the menu items defined from the module with hook_menu() are sub-menus of the admin menu defined from the System module.

The function that renders the toolbar is toolbar_view(), which contains the following code.

  // Retrieve the admin menu from the database.
  $links = toolbar_menu_navigation_links(toolbar_get_menu_tree());
  $build['toolbar_menu'] = array(
    '#theme' => 'links__toolbar_menu',
    '#links' => $links,
    '#attributes' => array('id' => 'toolbar-menu'),
    '#heading' => array(
      'text' => t('Administrative toolbar'),
      'level' => 'h2',
      'class' => 'element-invisible',
    ),
  );

toolbar_menu_navigation_links() excludes the hidden menu items, and the ones to which the user doesn't have access.

toolbar_view() is called from toolbar_pre_render(), which is the pre-render function added from toolbar_page_build() to $page['page_top']['toolbar']. Once the module is disabled, the menu items should not be anymore visible on the toolbar. The Toolbar module doesn't use any cache; I would expect the change to be immediately visible.

To appear on the toolbar, the menu item needs to be a direct sub-menu of admin. Differently, as in your case, it will not appear in the toolbar.

To test it, I added the following code in a module I use to test code.

/**
 * Implements hook_menu().
 */
function code_testing_menu() {
  $items['admin/mysite_form'] = array(
    'title' => 'My site form',
    'description' => 'Set custom settings for a site',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('code_testing_mysite_form'),
    'access callback' => 'code_testing_mysite_access',
  );

  return $items;
}

function code_testing_mysite_form($form, &$form_state) {
  $form['code_testing_switch_lights'] = array(
    '#type' => 'checkbox',
    '#title' => t('Switch lights on.'),
    '#default_value' => variable_get('code_testing_switch_lights', TRUE),
  );

  return $form;
}

function code_testing_mysite_access() {
  return user_access('administer site');
}

What I obtained is visible in the following screenshots.

Once the module is disabled, the toolbar doesn't contain anymore the menu.

I would rather not put a menu item directly, under admin, if not in particular cases. If the menu item just shows a form for a module's settings, I would not show it in the toolbar. If, vice versa, the module would show a page of links like the Advanced help does, then I could consider adding the menu item directly under admin.

In the other cases, I would consider adding links through the Shortcut module. This would mean adding code in hook_enable() that:

Creates a new shortcut set to use for the users with a specific role
Sets the new shortcut set as default for those users

In hook_disable(), the code should:

Change back to the old shortcut set

Once the module is uninstalled, it should remove the shortcut set it created.

As alternative, the module could add a new link to the shortcut set used from user with a specific role.

The functions that such code would use are the following ones:

shortcut_default_set()
shortcut_set_save()
shortcut_set_load()
shortcut_set_assign_user()

Playing with the Shortcut module, and manually adding a link to a menu item defined in hook_menu() from a module that I then disable, I noticed the link is automatically removed from the shortcut set once the module is disabled. Even after re-enabling the module, the link is not anymore shown as part of the shortcut set.

The second screenshot shows the shortcut content after the module is disabled.

After I re-enable the module (which defines the "My site form" menu callback I shown before), this is what appears as content of the shortcut set. I didn't save the shortcut set, since the other screenshot.


Views block for content that is older than current node created date How should I go about creating a view that only shows content that is older than the current node's creation date? I've created the argument using 'Content: created date' but I struggle to pass this over to the filter criteria.

To be honest, I'm not even sure this is the correct way to do it.

You'll need to create a block which accepts the node created date as an argument. Then you'll need to set the condition to only show nodes which have a created date < the argument value.

To pass on the node's created date as an argument, I think it's easiest just to embed the View block into the node's template using a PHP snippet. So you'll be looking at something along the lines of:

<?php print views_embed_view('my_view','my_block_machine_name', $node->created); ?>

You might have to check for the correct variable name for the created date of the node, but I think "created" is correct.

hope this helps!


register.json does not login the user or return the user's session/token/password I have tried far too many variations to list here, but the basic point is I cannot get the user logged in immediately after registration via Services. I have tried a fresh Drupal 7.33 install with only Services 7.x.3.11 enabled and the default resource settings provided by drupalgap 7.x.1.9

When I register using the Drupal interface, the user is created, the session opened, and I land on my profile page logged in.

vs.

When I call the Services endpoint /services/user/register.json, Drupal creates the account but the session does not persist. See my screenshots below.

How can I either A. get the session to persist for subsequent Service resource calls OR B. hook to add the user's or auto-generated password back into the json response so I can programmatically resubmit the /login.json form client-side (which does persist) ?

This question how could the global $user be different between the Drupal interface and Services module? describes my same problem using LoginToboggan.

In my screenshot you'll see a debug line called "login debug". It comes from line 333 of "/sites/all/modules/logintoboggan/logintoboggan.module" where I've tried all of this to no avail...

function logintoboggan_process_login($account, &$edit, $redirect = array()){
  global $user;

  $user = user_load($account->uid);

//watchdog('login debug', json_encode($account));
watchdog('login debug', json_encode($edit));

  //user_login_submit(array(), array('uid' => $account->uid));
  user_login_finalize($edit);

//  $user = user_load($account->uid);
//  $user->token = drupal_get_token('services'); // WE HAVE A TOKEN ALTHOUGH I DOUBT THIS WOULD WORK IN TERMS OF SESSION PERSISTANCE
//  user_login_finalize($edit);
//  module_invoke_all('hook_user_login');
//  module_invoke_all('tripchi_user_login');
//  module_invoke_all('logintoboggan_user_login');

Not sure if you need an answer at this point (or if this is even one), but it looks like you have "Require e-mail verification when a visitor creates an account" turned on?

In your image, in the second window (where you see the message from drupal_set_message()), it says that an email was sent and you will need to follow instructions to gain full message.

To turn this off, navigate to /admin/config/people/accounts and uncheck Require e-mail verification when a visitor creates an account.

If you look at the user table in the database, the status column should show a 1 for enabled, 0 for disabled (meaning he hasn't clicked on the link in the email).

Hope it helps!


Is it possible to apply FAPI #states to profile2 fields on the user registration form? I have a profile embedded into the user registration form and am trying to add a conditional to one of the fields in order to show/hide related fields.

The fields are all part of the same fieldgroup in the following layout:

username
email

profile (fieldset)
 - About you (fieldset)
  - fields

submit button

I think the issue is how to actually target the fields and apply #states to them.  Any ideas? I tried digging through Devel Themer, but couldn't get anywhere with it.

If you want to alter a form, you need to create a custom module and implement hook_form_alter (or hook_form_FORM_ID_alter) in it. In your hook_form_alter implementation you will have the $form array available. Look up the element you're interested in and add a #states property to it.

The above is just theory; I have not tried it specifically with the profile2 form and a #states property, but I assume that it would work.


Dynamically inject page content I'm using Drupal 7. I want to set up a dynamic page, which shows expertises' portfolios. I want to have a basic framework for that page and query data dynamically into the page.

For example, when someone goes to site/expertise?=em, they will find Em's portfolio, but when someone goes to site/expertise?=sarah, they will find Sarah's portfolio. It should be the same page, but just dynamically injected data.

Ideally the administrator will be able to upload xml or excel files and somewhere in the template will query the data from the uploaded database to update the data. Is that even possible, or are there any modules I can use?

You can create a view and add a contextual filter

Contextual filter :

Author filter :

Accept the author's name in the url :


Image styles: Does not work with large images The image styles, thumbnails and so on, are not created on my Drupal 7 site, when the original file is bigger than 5 MB. I did not find any error message in the log messages and the v-server, the site is hosted on, seems to have sufficient power to convert large files: I have 4 GHZ CPU and 4 GB RAM.
The original file is uploaded correctly and I have double checked the file permissions.

Does anybody know, what to do?

I installed Imagemagick and now everything works as expected.


Sort grouping field associated with taxonomy term by weight on drupal 8 views I'm currently trying to figure out how I can sort the grouping fields(Taxonomy Term) by weight that I have setup on my views.

As shown in this screenshot below I have a grouping field that is associated with a taxonomy term.

Application Deadline
Scholarship Deadline
Class Dates

The only problem is that, it is not sorted accordingly by weight.

Is there a way I could the taxonomy terms by weight. I tried configuring the views but I can't seem to find the solution in solving my problem.

I had to manually move the terms to a new order for the weights to change from a default 0 (you can click "show row weights" on the taxonomy page to see that they have changed after dragging out of order and then back into order; you only need to do this with one term to apply to all terms within a given level).


Authored By field conditional statement I am racking my brain trying to figure out how to create a conditional statement in Drupal concerning the "Authored By" field.

Right now, I have a special node template for a content type in my Drupal installation. I need to be able to define in that template when the "Authored By" field is filled in to display JUST the author full name but if it is not filled in, to display NOTHING.

I don't know I am having such a hard time accomplishing something so seemingly elementary, but any help would be greatly appreciated!

I believe the default variable for the author is $name. So you could perform a simple if statement in the template:

if (isset ($name)) {
print $name;
}

That will check if the $name variable is set - and if it is, print it out. If it's not set, nothing will happen.


How to set same filter value to be searched to the different filters on the same page? I am using 3 exposed filter on same page for video, audio and album search, what I want is when I enter filter criteria for one filter all filters should take same filter criteria. Is there anyone who is having an idea to do this?

You should enter the same identifier for all views, if you want to use one exposed value for all views in current page.


Can we automate scheduled published/Unpublished nodes in drupal 8? Schedular Module helps to schedule Nodes publish and un-published in Drupal 8. But it affect took place on each cron run only.

For example. If I set Publish a Node A on 19/10/16 14:30 but site configure to run cron after each hour. So it's get published on 14:00.
Is their any way to make it publish on exactly 14:30.

Thanks

The Scheduler module has it's own cron: http://example.com/en/admin/config/content/scheduler/cron, so you can configure any granularity you need


"Check boxes/radio buttons" Widget is NOT displaying content in Drupal7 In Drupal 7 Admin, I added a choice field of Type "List (text)" and widget "Check boxes/radio buttons", in which I see the list of check boxes in the Admin.
But I don't see anything in the Live Website (it does not show up)

Below is the code that I am using in the node-view-VIEWNAME.tpl.php page:

<?php if ( render ($content['field_choice']) ): ?>
Choice(s): <?php print render ($content['field_choice']); ?>
<?php endif; ?>

The code above works fine for Fields of Type Text.
How would I modify the code to render the content for check-boxes?

Never mind. I had a typo in the $content[] array element.
The one I set in the admin is slightly different than the one I declared in the template.
(small typo). Amazing!

My code above also works fine with check-boxes.


Establish whether a node is NEW in a custom #submit function I need to test whether a user is creating a new node as opposed to editing an existing node in a custom #submit function added to a node edit/creation form.

I can access the node via

$node = $form_state->getFormObject()->getEntity();

$node->id() - gives the new node ID so cant be used.

$node->get('nid')  - also gives an gives the new node ID so cant be used.

$node->isNew() - This is actually FALSE in this hook despite it being new content.

You could try this method:

if ($form_state->getFormObject()->getOperation() == 'edit') {
  // existing node
}

These are the operations defined for node:

 "form" = {
   "default" = "Drupal\node\NodeForm",
   "delete" = "Drupal\node\Form\NodeDeleteForm",
   "edit" = "Drupal\node\NodeForm"
 },


Services module update date field Hi i am using drupal services 3 module. Every thing is perfect except updating date field. I tried many ways to update that field but didn't get any solution. Is any core issue related to date field?

it depends on the field widget how you submit your values for the service.
For instance when you have a date field (datetime) with a select/dropdown widget, the form of the value should be the following:

"field_date":{"und":[{"value":{"month":"3","year":"2013","day":"6","hour":"0","minute":"0","second":"0"}}]},


Check whether multiple images are uploaded to a field? Is there a way to check whether or not more than one image is uploaded to a field? I'm working on a custom node template and want a conditional to do x if only one image and y if more than 1.

You can get it done in a few lines using the field_get_items function:

if ($items = field_get_items('node', $node, 'field_name')) {
  if (count($items) == 1) {
    // ...
  }
  elseif (count($items) > 1) {
    // ...
  }
}

It'd be best to keep this logic out of the template file itself and put it in a preprocess function though.


Change the site name programmatically for a specific page I am trying to change the site name when a user enters specific pages on my website.
I know the variable for the site name is $site_name and is being retrieved from the system.tpl.html file.

So I am trying to set different site names depending the URL; for example, when a user visits /about_us, the site name should change.

In my template.php file, I have captured the path in a variable.

$path = drupal_get_path_alias();
if ($path == 'about_us') {
  $site_name = 'New title';
}

This won't work.

How can this be achieved?

I think you mean page.tpl.php (not system.tpl.html, which isn't a standard Drupal file).

That said, you need to put your code in a hook_preprocess_page() function inside template.php, and actually alter the template variables that are passed in. At the moment you're just creating a variable called $site_name in the local scope, and Drupal has no way to pick that up.

Try this:

function MYTHEME_preprocess_page(&$vars) {
  $path = drupal_get_path_alias();
  if ($path == 'about_us') {
    $vars['site_name'] = 'New title';
  }
}

Have a look at Setting up variables for use in a template for a bit more info.


What is the proper way of retrieving and handling sessions when making multiple calls to the API? I can't log in consistently via Services 3 in Drupal 7.

POST http://<mydrupaldomain>/services/user/login.json
{
"username":"admin",
"password":"password"
}

The first time I make this request I get a session name and id back.
Which is what I want. I use the session information to make
successive calls such as update user.
The second time I make this
request the response comes back as HTML for the login screen.
The third time I get

  401 Unauthorized: Access denied for user anonymous

And at the forth time I get am able to login again with a NEW session name and id.

I make these requests within seconds of each other. I will have an application which will be making multiple API calls to Drupal per second.  This includes creating a user and updating a user both of which requires that I get a user session id in order for the request to be served by the API.

Questions:  Why the inconsistent behavior? On each login attempt I expected to get either a new session info back or, if the user is already logged in, the current session.

What is the proper way of retrieving and handling sessions when making multiple calls to the Services API?

Apparently the Services module submits a form in order to log a user in.  I expected /login to purely go through the backend.

Having said that, I disabled a module which hooked into my login form and now I am getting the expected results.


How to add parameter to URL when passing ids as arguments to a page? I have a view with an action Pass ids as arguments to a page where I need to add to the link. There is a parameter which I receive in the URL. I can print the parameter in the view, but I am not able to pass it as a token. It is not parsed.

Any ideas?

Basically I need to duplicate a node and assign to it a dynamic list of properties (other nodes). I created a view and added a VBO field. User select the ids and they get passed to my URL for elaboration. So far so good. My problem is that I need to pass, in addition to the ids, another field from the view. I tried to specify it in the URL /admin/myurl/[my_field], but it doesn't parse the token.

As per suggestion from this post, you should write a custom action using hook_action_info similar as Pass ids as arguments VBO action, so consider duplicating it as a starting point.

See also the following feature request: Token support in "Pass ids as arguments to a page" URL field.


Og Membership entity not created when assigning new node to Group; works when editing node Using Organic Groups 7.x-2.9, I have two content types:
- Series (Group)
- Event (Group Content)

When creating an Event, a users has a select list of the Series they can assign this Event to (og_group_ref).  However, upon saving this new Event there is no og_membership entity created (recorded in the table og_membership) and, therefore, the new Event is not in the Series group.

If you then edit this event and select the Series, the og_membership entity is created and the relationship is reflected on the Event. (Possibly related, there is no data in the table field_data_og_group_ref).

Using breakpoints - everything appears to be the same with one exception: When OgMembership::save() is called during the creation of a new entity the event entity object does have the nid; however, the node (Event) has not yet been saved in the node table.

What needs to be done in order to have the relationship when a new node (that is a group content) is created?

[EDIT] It seems the og_membership entity is being saved and then deleted.  I found this issue regarding data loss.  I don't think it's related (as of yet) because I don't have any active OG rules; however, it did make me check further.  When creating group content and associating it with a group, the og_membership table auto increment does increase by 1, although no record was written.  This tells me a record was written and deleted.

[EDIT] The above linked issue led me to another hook_node_insert that is used in this site.  This hook uses entity_metadata_wrapper to set a field value, commenting this out stops the og_membership entity from being deleted.

The issue turned out to be a hook_node_insert using entity_metadata_wrapper.  I refactored that code to use hook_node_presave to set the field value (field unrelated to organic group) instead: $node->field_short_url_code[LANGUAGE_NONE][0]['value'] = $string; and all is well.


How do other modules update elements using AJAX callbacks? I have a block, of which I want to update the contents via AJAX. So the block is:

$block['subject'] = t('My Block');
$block['content'] = '

';

And the form element AJAX part:

$form['select_element']['#ajax'] = array(
  'callback' => 'ajax_callback',
  'wrapper' => 'block_wrapper',
  'method' => 'replace',
);

The callback:

function ajax_callback($form, $form_state) {
  return views_embed_view('view_name', 'default', $form_state['values']['select_element']);
}

However when I change the form element the whole block content is replaced and the wrapper is replaced by a empty div, so subsequent alterations of the select element fail to update the block.

The wrapper documentation explains the entire div is replaced, not just it contents. But many modules (like for example Views) have dynamically updating form elements where changing a select element toggles other parts of a form, which keeps working no matter how often you change it. Do they insert the wrapper div again in the response? And how should I alter the response of views_embed_view to put the contents in a wrapper div?

Thanks @Tasneem for directing me. I did it as follows:

function hook_form() {
  $form['select_element'] = array(
    '#type' => 'select',
    '#options' => $options,
    '#default_value' => $default,
    '#ajax' => array(
      'callback' => 'ajax_callback',
      'wrapper' => 'block_wrapper',
      'method' => 'replace',
    ),
  );

  $form['block_wrapper'] = array(
    '#type' => 'item',
    '#title' => t('Contents'),
    '#id' => 'block_wrapper',
    '#markup' => views_embed_view(...),
  );

  return $form;
}

function ajax_callback($form, $form_state) {
  $form['block_wrapper'] = array(
    '#type' => 'item',
    '#title' => t('Contents'),
    '#id' => 'block_wrapper',
    '#markup' => views_embed_view(...),
  );

  // Returning the entire $form here made the select element appear twice, so only return the wrapper element.
  return $form['block_wrapper'];
}


Add field from rendered entity in view I would like to display the body summary of a single, specific article in the header of a view using the "entity: rendered entity" option and selecting "content." I can display the full content of the article and the teaser, but I don't see a way to access the article's fields individually. I don't want to display the title / author information. (My (probably wrong) guess is the "tokens" option, but upon selecting it, I see no place to utilize the tokens.) Insight appreciated. Thanks!

If you can display the Full & Teaser view modes, then you can display any custom view modes, too.

Install the Display Suite module and create a new 'view mode' - let's call it "body" - and on the same screen, make sure it's applied to nodes. Then go to Structure -> Content Types -> Article (or whatever your content type is called) -> Manage Display, and you will see three tabs: Default, Teaser and Body (the view mode you just created). Scroll to the bottom of the page and choose a layout (single column should do the trick), and then drag the body field into the appropriate region. Don't forget to save the form after rearranging fields.

At this point you can go into your view, and select the new 'Body' view mode where the options for 'Full' and 'Teaser' were showing up earlier.


How to convert field labels to search boxes in views I have a requirement where I need to convert the labels of specific/all fields of a view to search boxes on user click. The search box will be an autocomplete field.
Here, say for eg. the label TITLE gets converted to a search box on user click and provides suggestions(from the title field) as the user types characters

Since these are completely different things you may want to add the autocomplete fields as exposed filters from the view and then add them to the label using javascript. You could use jQuery .append into the label tag with a click listener.


How to open various files(image,video,txt) as pop-up on the current browser page instead of opening in separate page? I have seen on several sites, particularly news sites, If we click on video, the video does not open in the separate page, instead small window in the middle of the screen pops-up and video does play there itself and you can close that and behind that your current page is as it is. Same way when we click the image icon on the stackexchange text form to upload the image, small windows open of drag and drop appears.

Hence is there possible in drupal 7, for images, videos, pdf, txt files, word files etc. which opens on the same screen as pop-up in front of current screen.

What you're describing is a modal window. There's a few modules out there for Drupal that create modal windows. The one that probably best fits your use case (media consumption) is Colorbox. Out of the box, it only handles images but there are a number of supporting modules that can handle other media files. See the Colorbox project page link for more information.


Link to a file field in the body text? I have a content type that has a file field. I would like the body field to be able to link to the file. E.g. "Our research (PDF download) shows..." with the link becoming the download path for the file.

I can see the challenge: the path may not even exist at the time of creating the content. Is this something the token module can help with?

Not 100% exactly what you're asking for, but it may solve your requirement:

The IMCE module allows you to upload documents (and images) and integrates them in the body text. You don't need a separate file field if all you need is a document integrated into your text via a link.


Drupal 7 not able to run cron after views/panels update After an update of several modules to their latest versions (views, panels, ctools) it seems Drupal can no longer run cron, whether automatically or manual. It gives the error: "Cron run failed."

I have no idea what might be causing this and only discovered it some 10 days after performing the updates. The lightweight cron (for scheduled content) that I have set up externally in cpanel still runs.

Also a bit worrying is, when visiting mywebstie.com/cron.php (as an anon) it shows me my actual frontpage with some broken css. Which, I believe, is an unintended behaviour as it should show a blank page or a "content not found" page.

I believe the number 1 suspect is the views module, since immediately after the update I noticed that admin/content view no longer updates the "node views today" value and it just continuously increments this value without reinitialising every 24hours.

Any ideas of what might be the issue here?

Everthing was normal before the said updates: I have Unix server using Centos. BTW I have a local copy of the site using Xampp and it has the same cron problem as the live site. I am inclined to believe this is not a server problem.

PS: I have never used drush..

For troubleshooting cron.php problems found this:

https://www.drupal.org/node/553430

Cron stopped running; logs say: "Attempting to re-run cron while it is already running."

I have been able to trigger cron using the ultimate cron module, which is in beta.

Still don't understand what was going and didn't find the faulty module but the "attempting to re-run cron while it's already running" error msg has gone away from the logs.


How to stop autosuggest in node author field and write our own? Is there anyway to stopping auto suggest in author field of node content and write our own author names instead of users??

You could write a small module that implements hook_form_alter in which you remove the autocomplete functionality for this field.  This should convert it to a textfield.  However, this will certainly break if an author name that is not also the username of a user is inserted, since this field is used to populate $node->uid, which must have a valid username.

A more viable solution would be to create a vocabulary of your author names, and a taxonomy term field on your content type (pointing at that vocabulary).  And then display this field as you desire.


How to add delete link for imported content type For the content type which is imported by feature, there is no delete link for it, but we can delete them by going to the url /admin/structure/types/manage/YOUR_CONTENT_TYPE/delete

My question is how to make the delete link also available for the imported content type?

Although I am agains editing db directly, the simplest solution would be do edit table in your database.

find 'node_type' table and under 'custom', for your content type, change 0 to 1.


How to build route for entity without loading it? I'm making a tree view of vocabulary terms and I need to link each term to it's page(depends on which link template name is provided as argument to my function).

I'm loading the terms with taxonomy_get_tree and I could get fully loaded entities with it but if the vocabulary grows this will impact performance. So I'm thinking if there is a way to get the route data to build links for the terms without the need to load the whole taxonomy term entities?

I could hard-code the routes because I know them but that would mean that for every new vocabulary or term link template the code would have to be changed which is not much of a solution.

So is there a way to build the route for the provided link template with only term ID?

Even in Drupal 7 https://api.drupal.org/api/drupal/includes%21common.inc/function/entity_uri/7 you needed the full blown entity for the URI to it. There's nothing new here.


How to set multiple arguments for views contextual filters from twig Am using twig tweak module to render views from Twig file. I have pass multiple values for the country contextual filter in the view. I was able to pass single parameter like:

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

Not sure how to pass multiple values here:

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

This is not working.

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

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

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

Than in your twig:

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


Can't get the author's picture printed onto a node in Drupal 7 After reading the documentation, it seems that the correct way of doing that is like this:

php print $user_picture;

It won't work (it doesn't print anything at all).

Afetr asking around, I get this answer, which sadly won't work either:

global $user;
$image = theme('user_picture', $user);
print $image

That code was suggested as a "last resource", but when I try to use it, I get this error message:

  Fatal error: Cannot use object of type stdClass as array in /includes/theme.inc on line 1054

Line 1054 is the following one:

  // Line 1054
  if (isset($variables['#theme']) || isset($variables['#theme_wrappers'])) {
  //
    $element = $variables;
    $variables = array();
    if (isset($info['variables'])) {
      foreach (array_keys($info['variables']) as $name) {
        if (isset($element["#$name"])) {
          $variables[$name] = $element["#$name"];
        }
      }
    }

It´s pretty clear that it should work, but it doesn't.

Using contemplate module, I get this output as an alternative, but it doesn't work either.

<?php print $node->picture ?>

I've tried then with Devel module (using the /devel tab of the node):

I get this:

picture (String, 4 characters ) 2876
$...->picture

Wich won't work, because the output is just "2876", but is the only "picture" there.

So what can I do? How can I trace this problem?

Have you tried examining the $user object itself? It should be something like

    <?php
    global $user;
    print $user->picture;
    ?>

Or if that is loading the logged in user(which it will) as opposed to the user(creator of the node) you are viewing try on a node:

<?php
$user_object = user_load($uid));
print $user_object->picture;
?>


Unable save/update any content after migrating from local to production This is the first time I have made my Drupal site live on a production server (Ubuntu ls 10.04).

These are the steps I did:

Zip the entire webroot folder
Upload to the production server
Extract the contents into the webroot
Take db dump from local server
Dump into the production server
Update the production's Drupal admin password

I do not have a problem viewing the contents, but I am unable to save any content including the configuration settings such as Site information. It doesn't throw any error message or update the content.

What other steps might I have missed?

Check mod_rewrite (server module) and .htaccess (configuration files in Drupal installation, which easily can be left behind when copying) which take care of lot of the URL and path functionality.

Read more from https://drupal.org/getting-started/clean-urls

Credits to this question:
Can't save settings after copying site to new server


drupal entity property show in views I am using ECK module to create entity type. Now i want to show property of that entity to be show with views. Is there any way to do it?

If ECK doesn't define the entity and property types for views, you will have to do that yourself using either hook_views_data or hook_views_data_alter.


Ajax call returning JSON forces IE8 and 7 to download file instead of reading it I have a Drupal 7 site and I'm having this issue, commented here for Drupal 6

The thing is that, when ajax response is set as Content-Type: text/javascript; charset=utf-8 IE 7 and 8 try to download the file. The solution they propose is to change a line in common.inc to declare the response as Content-Type: text/html; charset=utf-8

The solution they propose there means I have to modify Drupal core, I would prefer not to do that as this will be a problem in future Drupal updates.

So, have any of you found this problem? do you know another solution?

PS: When I enter my site, I also find a javascript error in consle saying JQuery is not defined in a lina of drupal.js where it does jQuery.noConflict(); // Allow other JavaScript libraries to use $. I don't think it's related but comment it just in case...

Thank you

I finally located the error: it was because of the file codification, some of them were in UTF-8 and other ones in UTF-8 without BOM so IE7 detected an strange character at the beginning of the json being unable to parse it, coding all files (js files, php and module files) in UTF-8 without BOM solved the problem


Adding additional fields on user registration page (first name, last name) In Drupal 7, what methods are there to add additional textfields to the user registration page at /user/register? I mainly want to also get their first + last name during registration. There doesnt seem to be a way via the interface to add these extra fields as required for sign up.

What is the quickest way of adding these extra text fields on sign up?

You just need to goto:

Administration » Configuration » People » Account settings » Manage fields


How to stop a loop in rules? I'm using Conditional Rules module, there some conditions inside the loop I need to break out of. However, there's no action in rules for stopping/terminating the loop.

I tried a custom rules where I tried the following but it does not work:

function my_module_break_rules_loop() {
  return FALSE;
}
function my_module_break_rules_loop() {
  return 0;
}
function my_module_break_rules_loop() {
  break;
}

The break works but display with this error message:

  PHP Fatal error:  Cannot break/continue 1 level in

Any one know how to stop/terminate the loop?

Install Conditional Rules so that you can add "conditions" between " rule actions". After that you can create a variable which iterates and use that to stop after the third elements.


entity translation access permission alter I'm using Entity Translation for node translations.

I would like to modify access to edit form for this translation language based on roles and node properties. I've a field in the node entity with a select list of languages, translator should only access translate nodes in languages that are checked in that list.

Which is the best option to modify the access to the node/{NID}/edit/{LANGUAGE} ?

hook_menu_alter ?
hook_node_access(): this hook is called but how can I get the language? ($_GET could be problematic I think).
Extending the EntityTranslation class?
Other?

This is how its working for me, with args() we can get path ie english or any other language node is there :

  Example Paths in my case:

  node/[nid]/edit/add/sv/en

  node/[nid]/edit/add/en/sv

  node/[nid]/edit/sv

  node/[nid]/edit/en

define('ROLE_EDITOR',4); // role ID 4
define('ROLE_EDITOR_ENGLISH',10); // role ID 10

function my_module_node_access($node,$op,$account) {
  global $user;

  if (in_array(ROLE_EDITOR, array_keys($user->roles)) && !in_array(ROLE_EDITOR_ENGLISH, array_keys($user->roles))) {
    if(arg(3)== "en"){
      return NODE_ACCESS_DENY;
    }
    if(arg(3) == "add" && arg(4) == "sv"){
      return NODE_ACCESS_DENY;
    }
  }

  if (!in_array(ROLE_EDITOR, array_keys($user->roles)) && in_array(ROLE_EDITOR_ENGLISH, array_keys($user->roles))) {
    if(arg(3)== "sv" || arg(3)== NULL){  // Null is need to add as edit and edit/sv is same in my case because sv is defult language
      return NODE_ACCESS_DENY;
    }
    if(arg(3) == "add" && arg(4) == "en"){
      return NODE_ACCESS_DENY;
    }
  }

}


create views for a field submitted more than once in one row I have a content type that only has one field. (for example weight)
The user submits this field multiple times.
now I want to create a view that shows all the weights submitted by the user in one row, not in separate rows.

How can I create this kind of view?

1)Change your views format into grid set its maximum column

3)Allow Group By Authored into Grids

4)Add css

   float: left;
   width: 80%;


Display Comment Form in Sidebar I'm relatively new to Drupal and I'm working on a page that needs comment functionality for non-authenticated users. I tried some various forms (Webform, EntityForm) but they just seemed like way too much. The comments module has exactly what I need as far as submission and moderation goes.

I tried adding the form to the sidebar of a page but it showed up with a massive rich text editor and kind of broke the layout.

Is it possible to insert a very basic comment form with a simple long-text field and a submit button? If so...how?

Screenshot:

You may use Panels module.

Using that you can place comment form any where as your specification.

For more info go through project documentation .


drupal 7 lack of understandig location of bartik's color.css I liked to change some css color styles. I created my own css file and let bartik theme (my enabled theme) know this in its info file. But no changes took effect.
Then i realized, that there are two color.css files. One is in bartik/css/ and the other in sites/default/files/color/. The second one is used. Can someone explain to me, why not all css are just taken from bartik/css. I think i didn't get the concept yet.

The Bartik theme has support for the Color module, which is a module that allows themes to change the color used in their images, or in their CSS style files basing on a schema defined in the theme settings page.

When the selected color set is not the default one, color_scheme_form_submit() generates the files that will be used for the theme. The files you have seen inside the sites/default/files/color directory are the ones generated from the Color module, and that will be used for the theme. The files in the theme directory are the ones used when the color set is the default one.

As side note, if you are editing the files used by a theme that supports the Color module, you need to disable, and then re-enable it, or the files used for the theme could still be the old ones.


How to display nodes only after certain dates? (An Advent calendar is in progress) I'd like to build an Advent calendar with Drupal 7 as a warm-up exercise.

What would be the recommended way to protect future calendar entries from being accessed before their time?

I have 3–5 different content types to be used as calendar entries.

Everything should be accessible to anonymous users as well, so I only need to check the current date.

We have a client who uses the Scheduler module for their blog.  They write a backlog of posts, and then post date them for when they want them to appear.  You should be able to use this.  Make nodes for all of the days, and date them for when you want them to appear.  As long as you have cron workng properly, nodes should appear when they should.

Another option is to use the Date module along with Views.  Make a content type with a date field.  Set the date field to the day you want it to appear.  Then make a view over that content type, and add a filter to compare the date field against the current day.

Of the choices, I would go with Scheduler.


Views module core patching inside a sub-site I have a multi-site setup like below:

abc-parent/sites/all/modules/views
abc-parent/sites/pqr-child/modules/views (consisting core patching done in views)

When i do the above i get errors like cannot redeclare function

I wanted to do a core patching for views inside just 'pqr-child' site so that customization remains only to pqr-child and not for all the sites inside 'abc-parent'

Can anyone please help me achieve the above.

Thanks.

Modules that are placed inside sites/all/modules directory are accessible to all sites setup inside sites directory. Thats why it is showing you the error.

So basically you are trying to apply a patch for pqr-child site only. So you can do :

If it is a general patch, you can apply it to sites/all/modules/views directory. So there is no need of adding views directory for pqr-child site.
If it is a hack, then my suggestion is not to hack the module, instead you can write a custom module to fulfil your requirements.
But if it still necessary to hack the module, you need to copy the sites/all/modules/views to all the sites/subsites/modules directory and delete it from sites/all/modules.


Drupal 7 When a new user registers, where is the confirmation e-mail sent? Im using Drupal 7, when a new user registers an account I want to be able to approve/deny their membership and then allow them on the website as a registered user. When a new user registers, where is that registration e-mail sent to? And can I change where that e-mail goes?

Set the new user account setting to "administrator approval is required" here:

Admin > Configuration > People > Account Settings


How do I properly delete a field collection? I added a new field (houses) to user accounts. This field is a list of a collection fields.

I need to list all the fields in a user field collection (I can via the FieldCollectionItem::loadMultiple(array(12,45,...)) and remove all of them.

This is my code:

$array_of_fieldcollection = get_array_of_fieldcollection_of_user();

$fieldscollection = FieldCollectionItem::loadMultiple($array_of_fieldcollection);

foreach($fieldscollection as $fieldcollection){
  $fieldcollection->delete();
}

When I execute it and go to the user profile edit page, I get this error:

  The website encountered an unexpected error. Please try again later.
  More detail in the Apache log.

  TypeError: Argument 1 passed to Drupal\Core\Entity\Entity\EntityFormDisplay::buildForm() must implement interface Drupal\Core\Entity\FieldableEntityInterface, null given, called in /var/www/www.orlengine.com/modules/contrib/old_field_collection/src/Plugin/Field/FieldWidget/FieldCollectionEmbedWidget.php on line 71 in drupaldirectory/core/lib/Drupal/Core/Entity/Entity/EntityFormDisplay.php on line 159, referer: https://192.168.1.45/user/9

Isn't my code the proper way to delete all the field of a field collection?

The code you've shared is correct. The problem is that when we attach a Field Collection field to "User" entity the Host Entity of Field Collection is not set.

Because of which when we delete a Field Collection Entity programmatically the Host Entity field value (i.e. User in this case) is not updated with deletion. This causes Drupal to load Field collection which doesn't exists in system.

Rewriting the deletion code below:

use Drupal\field_collection\Entity\FieldCollectionItem;

// Load all field collections to delete.
$field_collections = FieldCollectionItem::loadMultiple(array(1, 2));
foreach($field_collections as $field_collection){
  // Delete field collection.
  $field_collection->delete();
}


Creating a Custom Formatter I'm learning to develop for Drupal 7 and figured I'd start with something simple, like a custom formatter.  I have a content type that contains several boolean fields indicating if the content type belongs to certain class of objects. When I create a view of the content types, all the boolean fields show a 1 or a 0, when I would like it to display an image instead.  I created the following CheckBoxFormatter.module file

    <?PHP
        /**
         * @file
         * Creates a custom format for boolean fields, a checked checkbox for true
         * and unchecked for false
         */

        /**
         * Implements hook_field_formtatter_info()
         */
        function CheckBoxFormatter_field_formatter_info() {
            return array(
                'CheckBoxFormatter' => array(
                    'label' => t('Checkboxes'),
                    'field types' => array('boolean')
                ),
            );
        }

        /**
         * Implements hook_field_formatter_view()
         */
        function CheckBoxFormatter_field_formatter_view($obj_type, $object, $field, $instance, $langcode, $items, $display) {
            $elements = array();
            foreach($items as $delta => $item) {

                //Build variables array for formatter
                $element = array(
                    '#obj_type' => $obj_type,
                    '#object' => $object,
                    '#field' => $field,
                    '#instance' => $instance,
                    '#langcode' => $langcode,
                    '#items' => $items,
                    '#display' => $display
                );

                if (function_exists($function = "{$display['module']}_field_formatter_{$display['type']}")) {
                    $elements[$delta] = array(
                        '#markup' => $function($element)
                    );
                }
            }
            return $elements;
        }

        /**
         *  creates the actual checkboxes
         */
         function CheckBoxFormatter_field_formatter_CheckBoxFormatter($variables) {
             $img = array("<URL TO UNCECKED>","<URL TO CHECKED>");
             $disp = array("Unchecked","Checked");

             $element = array();
             foreach($variables['#items'] as $delta => $item) {
                 $element[$delta] = array(
                     '#markup' => '<img src="' . $img[$item['value']] . '" alt="' . $disp[$item['value']] . '" />'
                 );
             }

             return $element;
         }

I uploaded this to all/sites/modules/CheckBoxFormatter.  I was able to activate the module in the modules section of my drupal site.   Now, when I go back to the view I created, this new formatter doesn't show up.  I also do not see it as an option under Manage Display for the content type.  What am I doing wrong?

Finally found it. I knew it had to be something simple.  I was using the wrong field type. Turns out it should have been list_boolean instead of simply boolean.  I also simplified the code

    <?PHP
        /**
         * @file
         * Creates a custom format for boolean fields, a checked checkbox for true
         * and unchecked for false
         */

        /**
         * Implements hook_field_formtatter_info()
         */
        function CheckBoxFormatter_field_formatter_info() {
            return array(
                'checkboxes' => array(
                    'label' => t('Checkboxes'),
                    'field types' => array('list_boolean')
                ),
            );
        }

        /**
         * Implements hook_field_formatter_view()
         */
        function CheckBoxFormatter_field_formatter_view($obj_type, $object, $field, $instance, $langcode, $items, $display) {
            $output = array();
            $img = array("uncheck.jpg","check.jpg");
            $disp = array("Unchecked","Checked");

            if($display['type'] == "checkboxes") {
                foreach($items as $delta => $item) {
                    $output[$delta] = array(
                        '#markup' => '<img src="' . $img[$item['value']] . '" alt="' . $disp[$item['value']] . '" />'
                    );
                }
            }
            return $output;
        }


is Form api ajax attribute good in performance ? does it require an entire bootsrap? Ajax is used for better user experience and also for better performance in a webapp ( change only the requested item instead of the entire page ).

In my case the form will require ajax functionality, interacting live with the Product Configuration Soap Service.
The performance of this form will be important due to the fact that many users may be accessing it simultaneously.

But how #ajax works in Drupal ? Does It require an entire bootsrap ? If so, will drupal be a good solution in my case ?

Whether or not the request method is AJAX has no bearing on whether a full bootstrap is performed - that's completely down to the behaviour of the path that's being requested. If your AJAX call requests '/js/my-page.js', and that menu path is somehow configured not to bootstrap fully, then you won't incur a bootstrap penalty.
To that end, I would highly recommend installing the High-performance JavaScript callback handler module.

JavaScript callback handler is an interim solution for high-performance server requests including (but not limited to) AHAH, AJAX, JSON, XML, etc.
This project targets module developers and provides a "bare bone" callback handler which is intended to be addressed by modules wanting to improve response times for specialized tasks.

It will allow you to define router items for which a full bootstrap will not run; in fact you can pick exactly which modules should be loaded, and which other files should be included, for your callback's requirements.
I've used it before with great success, and have seen very noticeable improvements when converting custom (and even core) AJAX callbacks to use this method. It's blindingly fast.
It also has integration with a bunch of other modules (SHS for example).
As to whether Drupal will be able to handle your project - that's not for us to say; have a look at the various options available (including this one), do some benchmarking and stress testing per your project/client-established requirements, and it'll become apparent whether or not Drupal will meet your needs.


How do I change and translate the "completion message" in Commerce checkouts? I want to change the text of the "completion message" that is shown when an order is paid for successfully.  I also want to translate this message.

By default, the completion message text is:

Your order number is 1.
You can view your order on your account page when logged in.

I'm using Commerce 2 with Drupal 8.4.1.

By default, at /admin/commerce/config/checkout-flows/manage/default, the checkout flow looks like this:

There is no option to edit the completion message.  Also, there is a translate link at the top of the page, but this translate link only lets me translate the name of the checkout flow, not the completion message.

So how do I edit/translate the completion message?

Template approach (recommended)

As revealed in the comment by @bojanz, you can just make a copy of the template file in your theme:

commerce/modules/checkout/templates/commerce-checkout-completion-message.html.twig

Custom checkout pane approach

There is documentation for this.

You can create your own custom checkout pane, which can be done with drupal console or by hand.

/MYMODULE/src/Plugin/Commerce/CheckoutPane

<?php

namespace Drupal\my_checkout_pane\Plugin\Commerce\CheckoutPane;

use Drupal\commerce_checkout\Plugin\Commerce\CheckoutPane\CheckoutPaneInterface;
use Drupal\commerce_checkout\Plugin\Commerce\CheckoutPane\CheckoutPaneBase;
use Drupal\Core\Form\FormStateInterface;

/**
 * @CommerceCheckoutPane(
 *  id = "custom_completion_message",
 *  label = @Translation("Custom completion message"),
 *  admin_label = @Translation("Custom completion message"),
 * )
 */
class CustomCompletionMessage extends CheckoutPaneBase implements CheckoutPaneInterface {

  /**
   * {@inheritdoc}
   */
  public function buildPaneForm(array $pane_form, FormStateInterface $form_state, array &$complete_form) {
    $pane_form['message'] = [
      '#markup' => $this->t('This is a custom completion message.'),
    ];
    return $pane_form;
  }

}


Dynamic select list in the form (dependent dropdown) I'm using Drupal seven. I want to make the options in a select list be dependent on the value chosen in another select list in a form.  I'm sure this has been asked many times before, but I am having difficulty finding a clear answer for how to do this.

The form is for users to enter a work history.  They need to select a squadron which is a node reference to the squadron field type, and this is in a drop-down list.  However, the squadron, is dependent upon a city drop-down list.  Users first need to select a city which will then filter the options for the squadron.  In the squadron content type, I created a taxonomy for city which gets tagged to the squadron.

I would be very grateful for any pointers as to the best way (simplest?) to go about this, or for any useful resources online which would help.

You can use Ajax to accomplish this. Drupal 7 has good Ajax support now. On your first select list (city) you'll need to add Ajax information. Then, the second select list can be populated based on the information in the first. You can also even hide the second select list until an option in the first is selected, and I'll explain how to do that in a bit.
First, to set up the basic form:

$form['city'] = array(
  '#type' => 'select',
  '#title' => t('City'),
  '#options' => $options,
  '#ajax' => array(
    'event' => 'change',
    'wrapper' => 'squadron-wrapper',
    'callback' => 'mymodule_ajax_callback',
    'method' => 'replace',
  ),
);
$form['squadron_wrapper'] = array('#prefix' => '
', '#suffix' => '
');
$form['squadron_wrapper']['squadron'] = array(
  '#type' => 'select',
  '#title' => t('Squadron'),
  '#options' => $squadron_options,
);

This is just the basic setup of the elements. Now you'll need a way to determine what options should go in squadron. First you need to make your Ajax callback identified in 'city' select list. In most cases you can just return the element that wraps the ajax element, in this case $form.

function mymodule_ajax_callback($form, $form_state) {
  return $form;
}

Now, when the 'city' select list changes it will rebuild the squadron-wrapper part of the form. Your 'city' value will now be in $form_state['values']. So, when the form is rebuilt we need to determine what options to give to the select list based on the value of 'city'.

// Get the value of the 'city' field.
$city = isset($form_state['values']['city']) ? $form_state['values']['city'] : 'default';
switch ($city) {
  case 'default':
    // Set default options.
    break;
  case 'losangeles':
    // Set up $squadron_options for los angeles.
    break;
}

// If you want to hide the squadron select list until a city is
// selected then you can do another conditional.
if ($city !== 'default') {
  $form['squadron_wrapper']['squadron'] = array(
    '#type' => 'select',
    '#title' => t('Squadron'),
    '#options' => $squadron_options,
  );
}


D8: Unable to set cache max-age on ResourceResponse I'm trying to create a REST API get response. My class extends ResourceBase and this is inside my classes get function.

$response = new ResourceResponse(['time' => time()], 200);

$cache_meta_data = new CacheableMetadata();
$cache_meta_data->setCacheMaxAge(2);
$response->addCacheableDependency($page);
$response->addCacheableDependency($cache_meta_data);

return $response;

This will return the timestamp, but it will be cached forever until I manually clear the Drupal cache. When I curl the interface this is the output for the first hit.

curl 'https://mylocaldrupal.dd:8443/rest/upcoming_matches/1?_format=json' -i -k
HTTP/1.1 200 OK
Date: Sun, 11 Feb 2018 17:03:06 GMT
Server: Apache/2.4.17 (Unix) OpenSSL/1.0.1h mod_fcgid/2.3.9
X-Powered-By: PHP/7.0.14
Cache-Control: must-revalidate, no-cache, private
X-Drupal-Dynamic-Cache: UNCACHEABLE
X-UA-Compatible: IE=edge
Content-language: en
X-Content-Type-Options: nosniff
X-Frame-Options: SAMEORIGIN
Expires: Sun, 19 Nov 1978 05:00:00 GMT
X-Generator: Drupal 8 (https://www.drupal.org)
X-Drupal-Cache: MISS
Transfer-Encoding: chunked
Content-Type: application/json

{"time":1518368586}

And a second hit after a few seconds:

curl 'https://mylocaldrupal.dd:8443/rest/upcoming_matches/1?_format=json' -i -k
HTTP/1.1 200 OK
Date: Sun, 11 Feb 2018 17:04:41 GMT
Server: Apache/2.4.17 (Unix) OpenSSL/1.0.1h mod_fcgid/2.3.9
X-Powered-By: PHP/7.0.14
Cache-Control: must-revalidate, no-cache, private
X-Drupal-Dynamic-Cache: UNCACHEABLE
X-UA-Compatible: IE=edge
Content-language: en
X-Content-Type-Options: nosniff
X-Frame-Options: SAMEORIGIN
Expires: Sun, 19 Nov 1978 05:00:00 GMT
X-Generator: Drupal 8 (https://www.drupal.org)
X-Drupal-Cache: HIT
Transfer-Encoding: chunked
Content-Type: application/json

{"time":1518368586}

Can't really figure it out and the Drupal.org docs doesn't really seem to help me neither. Am I missing something obvious?

The referenced question from 4k4 describes how to disable the internal page cache completely.

To not disable but set an expiration on the anonymous/internal page cache, you can use the Expires header, just set it to a date in the future and that will be respected. That's the only thing that the internal page cache module currently respects.

See the linked core issue for more information, it's partially simply an overlook that it wasn't done before 8.0 but now it would be an API change to start respecting it and lots of things would then make Drupal uncacheable, like the language switcher block. So we'll have to be very careful with any change we make.


Change front page url by keeping its content I would like to change front page url to some string, e.g. http://example.com/pattern and need all url('<front>') links to be changed to the new url and 301 redirect to new url after openening the site directly as well.

You simple need to configure that in your website settings:

Configuration >> System >> Site information

There you will find the "Front page" panel where you can enter your new front page URL.

Cheers!


How to set multiple values to an unlimited Term Refence field with Rules I have two content types: Ingredient and Recipe Sheets.

Both Ingredient and Recipe Sheet have a term refence field called Allergens.

Ingredient has the Allergens term reference field filled in. IE: Milk, Gluten.

While in Recipe Sheets Allergens is empty.

Ingredient has an Entity Reference to Recipe Sheets.

Now, I want when Ingredient content type is viewed, to automtiacally copy all the terms from allergens and put them into the Allergens of the Recipe Sheet that is entity referenced (the entity reference field can only have 1 value).

In my rule, when Ingredient is viewed, I use Action of loop then item list to get all the Allergen field terms from A (Ingredient). Then another action to run my component and I pass that list to my component.

Here is my component ("B" refers to "Recipe Sheet"):

When I do this action, for Allergens, only the last tax term gets checked in B.

How do I get it, so it checks all the terms from the list and not just the last one?

Sample Rules Export:

{ "rules_testing" : {
    "LABEL" : "Testing",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_view" : [] },
    "IF" : [
      { "node_is_of_type" : {
          "node" : [ "node" ],
          "type" : { "value" : { "ingredients" : "ingredients" } }
        }
      }
    ],
    "DO" : [
      { "LOOP" : {
          "USING" : { "list" : [ "node:field-allergens" ] },
          "ITEM" : { "list_item" : "Current list item" },
          "DO" : [
            { "entity_fetch" : {
                "USING" : { "type" : "taxonomy_term", "id" : [ "list-item:tid" ] },
                "PROVIDE" : { "entity_fetched" : { "entity_fetched" : "Fetched entity" } }
              }
            },
            { "component_rules_lalala" : {
                "node_referenced" : [ "node:field-reference" ],
                "nids_of_terms_from_allergens" : [ "entity-fetched:parents-all" ]
              }
            }
          ]
        }
      }
    ]
  }
}

Sample Component Export:

{ "rules_lalala" : {
    "LABEL" : "lalala",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : {
      "node_referenced" : { "label" : "Node(s) from Entity Reference", "type" : "node" },
      "nids_of_terms_from_allergens" : {
        "label" : "NIDS of Allergens from Ingredients",
        "type" : "list\u003Ctaxonomy_term\u003E"
      }
    },
    "IF" : [
      { "node_is_of_type" : {
          "node" : [ "node-referenced" ],
          "type" : { "value" : { "recipe_sheets" : "recipe_sheets" } }
        }
      }
    ],
    "DO" : [
      { "data_set" : {
          "data" : [ "node-referenced:field-allergens" ],
          "value" : [ "nids-of-terms-from-allergens" ]
        }
      }
    ]
  }
}

Part 1: Understanding the problem

Your action Set a data value can only set 1 value, which explains what you currently experience, i.e the last one.

Try to replace that action with an action "Add an item to a list".
When doing so, you probably also want to set "ENFORCE UNIQUENESS" to true, so that you "only add the item to the list if it is not yet contained". Even though for your case it may not make a difference, IMO that is a kind of safety-belt when using this action.

However, you also have to add a prior action like "Fetch entity by ID", before this "Add an item to a list".

For more details, have a look at the tutorial "Lists and loops", starting from around 9:00.

Part 2: Fixing the problem

Below are more detailed instructions, where appropriate with references to the equivalent that is shown in that video. And a corrected Rule and Rules Component (in Rules export format).

Step 1: Simplify the Rule

In the Rule that calls your Rules Component, apply these changes:

Delete all Rules Actions you had added (sorry ...).
Only add 1 action, which is to invoke the Rules Component with 2 appropriate parameters, i.e.:

for Node(s) from Entity Reference use node:field-reference as its data selector
for List of Allergens from Ingredients use node:field-allergens as its data selector.

Here is an export of what I recommend as your (corrected) Rule:

{ "rules_copy_all_terms_to_another_node" : {
    "LABEL" : "Copy all terms to another node",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_view" : [] },
    "IF" : [
      { "node_is_of_type" : {
          "node" : [ "node" ],
          "type" : { "value" : { "ingredients" : "ingredients" } }
        }
      }
    ],
    "DO" : [
      { "component_rules_add_a_term_to_a_node" : {
          "node_referenced" : [ "node:field-reference" ],
          "list_of_allergens_terms" : [ "node:field-allergens" ]
        }
      }
    ]
  }
}

Step 2: Rework the Rules Component

In your Rules Component, apply these changes:

Remove the action to "Set a data value" (we'll use Rules Action "Add an item to a list" instead, as detailed below).
The 2 parms you passed to the Rules Components seem OK (I just slightly renamed them to improve readability).
Add a loop, to iterate over each term contained in the list of terms (which is passed as a parameter), and add the extra Action for each item in this loop, like so:

Add an action Fetch entity by ID, whereas you want to fetch (= load) a taxonomy term, similar to what is shown in the video around 10:40. And the ID of what you want to fetch is the 2nd parm of your Rules Component, followed by ":tid", similar to what is shown in the video around 10:50, though your Rules Component should use "data selection" to select your 2nd parm (the video just uses a data identifier of "1"). Make sure to remember what you use as variable name here similar to what is shown in the video around 11:20, let's assume you name it "(allergens_term_fetched".
Add an action to Add an item to a list, similar to what is shown in the video around 11:40. The data list to which an item is to be added in your case is node-referenced:field-allergens (instead of node:field-tags as shown in the video). While doing so, the next thing is similar to what is shown in the video around 12:00: the "item to add" should be "(allergens-term-fetched" (if you used that name I suggested). You probably also want to check the "enforce uniqueness" (see video around 12:40, though the video does not check it), and for "insert position" I'd use "append the item to the end" (see video around 12:55).

Note: the Rules Condition in your Rules Component is fine (and also similar to what is shown in the video), no changes needed to that.

Here is an export of what I recommend as your (corrected) Rules Component:

{ "rules_add_a_term_to_a_node" : {
    "LABEL" : "Add a term to a node",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : {
      "node_referenced" : { "label" : "Node(s) from Entity Reference", "type" : "node" },
      "list_of_allergens_terms" : {
        "label" : "List of Allergens from Ingredients",
        "type" : "list\u003Ctaxonomy_term\u003E"
      }
    },
    "IF" : [
      { "node_is_of_type" : {
          "node" : [ "node-referenced" ],
          "type" : { "value" : { "recipe_sheets" : "recipe_sheets" } }
        }
      }
    ],
    "DO" : [
      { "LOOP" : {
          "USING" : { "list" : [ "list-of-allergens-terms" ] },
          "ITEM" : { "next_allergens_term" : "Next Allergens term" },
          "DO" : [
            { "entity_fetch" : {
                "USING" : { "type" : "taxonomy_term", "id" : [ "next-allergens-term:tid" ] },
                "PROVIDE" : { "entity_fetched" : { "allergens_term_fetched" : "Fetched Allergens term" } }
              }
            },
            { "list_add" : {
                "list" : [ "node-referenced:field-allergens" ],
                "item" : [ "allergens-term-fetched" ],
                "unique" : "1"
              }
            }
          ]
        }
      }
    ]
  }
}

Step 3: Time for QA-testing

Only believe what you've seen with your own eyes ... So use the Rules UI to import my corrected Rule and Rules Component. If you didn't do so yet, make sure you have a content type with the same machine name ingredients (doesn't matter what the content type of the entity referenced node is). And also make sure both content types have a term reference with machine name allergens. If the import fails, it must be because those machine names don't match, or the fields are missing (so fix that and retry the import).

After the import completed, and you have at least 1 node of each type (with an entity reference), it's Party Time ... Make sure your taxonomy terms include terms like salt, pepper, strawberries, bananas, whatever.

FYI: in my experimental setup, the combination of the above Rule and Rules Component seemed to work as requested in the question here ... one of my terms for testing was ... Champagne.

Voilà ... No custom code, sweat, no?


SVG icons do not show up when remotely connected I have installed Drupal 8 in my linux machine for testing. Everything seems fine initially when I'm accessing D8 from my local machine.

However when I tried to access it via another machine on the same network, the svg icons do not show up. After further investigation using firefox element inspect, I realized some of the request urls are from 192.168.1.18, which is my linux machine IP, while the rest are either from localhost or 127.0.0.1.

Am I missing any configuration here?

Thanks

Make sure that in your code you dont reference the icon like http://127.0.0.1/sites/default/somepath/youricon.svg but you re using a relative path instead like sites/default/somepath/youricon.svg.


Monthly magazine content organising I have to develop a monthly online magazine and I am looking for suggestions on the best way to organize the content.

Since it's a monthly publication, I want to organise content under January, for example. January will have multiple articles, advertisements etc all of which are nodes.

When time moves on to February, I want to unpublish January and consequently unpublish all the nodes associated with it.

Does anyone have any ideas on how I might accomplish this?

I can offer next thing, you can create a taxonomyvocabulary  with months, and to unpublish nodes, you can do next thing:

Query to db to find nodes with taxonomy term inside(for example January)
Load node with node_load
Set the $node->status = 0
and save the node with node_save

This will unpublish all nodes with that month. About associated nodes - can say for sure, how they accosiated with a node?
Probably you will need to write your own module.


How to show the parent and child taxonomy term? I have a vocabulary like this:

Parent 1

Child 1
Child 2
Child 3

Parent 2

Child 1
Child 2

Now I would like to use a view to create a list of a Parent term with its Child terms. I try to do this with Views UI, but only show the term parent... No the child term's. It is very confusing for me.

Can anyone help with this case? Thanks :D

Views can do this. Views is a UI for sql searches so you are setting the definition for the query that will be made of the content database.

Create a view to display a taxonomy term with a page with a path configured along this line category/%. The % is a wildcard that will make the view respond to any value applied in the URL that matches this format.
Set up your display and any filters desired.
Define a relationship (third column of view UI page) and set it to taxonomy term: parent. This tells the view to look at the parent field in each taxonomy term searched. (Note that Drupal includes a field for each term that identifies its parent, but not its siblings or children).
Next we tell the view to interpret the wildcard from the URL we used in the path for the view: Define a contextual filter (above the relationship selection) and set it to a taxonomy:termID. In the form, set the relationship to Parent in the drop down box. This tells View that the term being called in the URL will be applied as a filter for the 'parent' field of the taxonomy terms as they are searched.
Finally we must complete refining the contextual filter. You can tell the view what to do if it does not find an answer in that section of the form if you want, but we must tell it what to do if it does find solutions in the query. To do so check the validation check box. Set the Validator to Taxonomy term and select the vocabulary that applies to your hierarchy. Then select either Term ID or Term name converted to term ID as the Filter value type. If the value you are passing in the % is a term ID, then you are done. If the passed value is a term Name, then you may want to check the box to convert dashes to spaces. IF you have multiple word term names, the URL will have dashes, which do not match the actual spaces in the term name. This little correction makes them agree so a test succeeds.
Finally go to the preview area and enter the name or ID for a term you know has children and you should get the list of children terms. Use the sorting settings to arrange them in whatever order you need.

Good Luck!


Add content -> taxonomy autocomplete input field size My content type has a taxonomy auto-complete field.
My problem is that some content requires like 10-20 taxonomy terms where my input field for it is way to small.

I don't see in my 'manage fields' settings where I can define this length.

You can use the Entity Reference module; it allows the size of the autocomplete input field to be changed.


Naming convention for Drupal views I have a view setup named Homepage Suppliers.

It is a jCarousel format that displays an image field which links to the content.

What I'm looking to do, is theme this using a view template to get it exactly how I want it.

I've tried using the following file names:

views-view--homepage-suppliers.tpl.php

views-view-list--homepage-suppliers.tpl.php

Do these look right?

Thanks

Views has a nice built-in way to help you decipher which template filename(s) to use.

Open up your view in edit mode, go to the display that you're interested in, and open up the 'Advanced' tab. Right at the bottom you'll see the "Theme: Information" link. Click that, and you'll be presented with a popup that looks something like this:

Once you've decided on the right filename, create the file and populate it, then make sure to clear Drupal's theme registry caches or the changes won't get picked up.


Rename/hide "Save" and "Save as draft" buttons for non-admin roles I have four content types on my site that registered users can create, but they are set to be approved by admins before publishing. Since the site also sends out notifications to subscribers when a new node is created, the following problem occurred - the regular users could save new nodes which are not published until approval, but the notifications go out immediately after they save it anyway.

The registered users creating new nodes must not have the ability to create i.e. save the node and that's why we added the "Save as draft" option (via Save Draft module). What I need is to only show the "Save as draft" button, possibly under another label and completely hide the "Save" button. Understandingly, I would need to do this only if the user is not an admin or an editor, otherwise I might create a big confusion on the site.

This is the rule which sends notifications to users who subscribed for notifications:

{ "rules_new_content_notifications" : {
    "LABEL" : "New content notifications",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_insert--slucaj_plan" : { "bundle" : "slucaj_plan" },
      "node_insert--inicijativa" : { "bundle" : "inicijativa" },
      "node_insert--izgradnja" : { "bundle" : "izgradnja" },
      "node_insert--projekat" : { "bundle" : "projekat" } },
    "DO" : [
      { "mail_to_users_of_role" : {
          "roles" : { "value" : { "8" : "8" } },
          "subject" : "New content created",
          "message" : "..."
        }
      }
    ]
  }
}

The content approval module only sets the node to "unpublished" after a non-admin saves it and the way the administrators approve it later is to edit it and set as "published".

Focusing just on the save draft module (whatever rules you are using are unrelated).

You can implement a custom module will the following form alteration:

/**
 * Implements hook_form_BASE_FORM_alter().
 */
function MODULENAME_form_node_form_alter(&$form, &$form_state, $form_id) {
  // Get the current user object.
  global $user;
  // Role ids of the current user.
  $user_roles = array_keys($user->roles);
  // Role ids of your admin roles.
  // Change these to suite your role ids.
  $admin_roles = array(8, 9);

  // For users that don't have the appropriate roles.
  if (!array_intersect_key($user_roles, $admin_roles)) {
    // Restrict access to the save button.
    $form['actions']['submit']['#access'] = FALSE;
    // Change label of save draft button if it is present on this
    // content type.
    if (isset($form['actions']['draft'])) {
      $form['actions']['draft']['#value'] = t('Save as draft button label');
    }
  }
}

For this to work your module's form alter function needs to run after the save draft module.
To achieve this you need to either add an install function that changes the
weight of your module in the system database table so that it is 1 (save draft is 0 so you need a higher number), or you can implement hook_module_implements_alter() to make your form alter hook run after.

For more information on making your form alter run after the save draft form alter see the two answers at How can I modify the advanced search form when my hook runs too early? - these explain how to do both the solutions I mentioned above.


Views charts with node revision date as x-axis I have 4 nodes with a field status (just an example, it could have more fields). The content type is set to create revisions on every update.

What I need is to create a chart in views like the one below, using Charts and Highcharts.

So, first time I create the 4 nodes:

3 have status = No Run;
1 have status = Blocked;

After updating the 4 nodes, a new revision is created and now each node has a different status value:

1 have status = No Run;
1 have status = Blocked;
1 have status = Passed;
1 have status = Not Completed;

On the third revision:

2 have status = Passed;
2 have status = Not Completed;

... and so on...

I tried everything in views without success. I started by trying to show the data needed in table format but I can only view the latest revision, not all.

Anyone has a clue on how to accomplish this?

I'm willing to make this with code also but I would like to try views first.

Thanks!

Ok,

After some struggle, I managed to get the results I needed so, I will share how to do it. Hope it helps anyone with the same question.

At the time of this answer, this will only work with the most recent Dev version. Also, after that, you have to apply this patch. It won't work unless you make these two steps.

On your content type, check if you have the Create new revision option checked.

In views, create a new view to show Content revisions and format as Chart. Change the following inside views:

===== First Display =====

Remove the Content revision: Content relationship.

Remove the Content: Published (Yes) filter.

If you have more than one content type, the way you filter (at least I did it this way) is to add a field to the Filter criteria like this: Content (historical data): [your field] (not empty).

Set Use aggregation to yes.

Add a Content revision: Nid field to the display and set aggregation to COUNT.

On the Chart settings, select field Content revision: Updated date to provide labels and COUNT(Content revision: Nid) to provide data.

The result is a display that shows the total of nodes for each revision (x-axis date).

===== Second (and similar) displays =====

Now, you create chart add-on displays for each of the different states/values of your data field (in my case it was a status_field).

The settings for these displays are the same as the first one with one difference:

Add the [your field] field to the filter section and filter by one of the states/values. You will have to do this for each dispay, each one represents the chart for each state.

Combine the chart add-on with parent chart.

Finally, to get the chart as stacked, you have to create some code. Add the following code to your module:

function mymoudle_chart_alter(&$chart, $chart_id) {
    if ($chart_id == '[my_chart_machine_name]__[first_display_machine_name]') {
    $chart['#stacking'] = TRUE;
}

Notes: remove the [ and ] from above example but keep both undersores (__).

And that's it. This is the result I got:

I have the update date of the revision to show as unix timestamp but you can have it as you like!

As suggested, here is a similar chart but using 'bar' type:


How to show a View field depending on roles? I have a view, and I added 2 fields: "title" and "edit link".
Now I just want to show the "edit link" link if the visitor is a registered user, and has the "administrators" role.

How can I accomplish it?

Check the permissions for the role of "administrators" (D7: admin/people/permissions, D6: admin/user/permissions).  If the user has permission to edit the node, the edit link will be visible, if not, the edit link will not be shown. Views takes into account a user's (role's) permissions.

D7 Example:  Say you are creating a list of Stories. If the administrators role has the permission "Story: Edit any content", the user will be able to see the "Edit" link for that node in the listing, while if the role only has the permission "Story: Edit own content" the "Edit" link will only be shown if the current user created the Story.


Feeds Module Periodic Import not working I created a Job portal using the feeds module. I have the Periodic Import on every 3 hours. It says you have to configure your cron. I have read where there are others having issues a few years ago and they say to use Ultimate cron or Elysia Cron. I tried both and am not sure what/ where I am suppose to set and still isn't working.

If you are using Ultimate Cron, make sure you set the 3 hour cron to the Job Scheduler cron and and also to the Feeds crons (there are like 4 of them).


Commerce orders - header On the orders admin page you have options to change fields in your table and sort fields, ect. In the headers option I have 'global: view order form' selected, and above the table there is a box where you can search for order numbers. I want to be able to not only search for order numbers, but also search for customer names, dates, money amounts, ect. Can you add in search criteria to that header?

Did yout try simply add new filters?

For example, user:

Add Filter Criteria
Chose Filter - User
Search for "name" field
Select "User: Name"
Check "Expose this filter to visitors, to allow them to change"
Click "Apply"

That's all you need to do. I should notice that for amount and date you can expose operator for your own needs.

In the same way you can add SORT CRITERIAS


Permission creating taxonomy terms per vocabulary Is there a module that will allow me to allow a specific role to create/edit/delete terms in a specific vocabulary without allowing them to edit the taxonomy itself or terms on another vocabulary?

The only taxonomy permission I see is "administer taxonomy", which is decidedly more than I want to give those users.  My google-fu turned up numerous modules that will permission the nodes by terms, but none that allow permissioning of the vocabulary itself.

thanks!

For Drupal 6, this looks like the module for you: Vocabulary Permissions Per Role


Hide 'successfully added to cart' message I use commerce checkout on a Drupal site but it is primarily an information site. So I effectively want to hide the cart from the user.

This means that on addition of a product to the cart, I want to remove the Drupal message 'Product' added to your cart.

This can't just be hidden in CSS because we want other checkout messages to still be visible.

I'm pretty sure that's just set by a rule called "Display an Add to Cart message".

You should be able to delete/disable that rule in the UI and the message will disappear.


How to query drupal timefield data Scenario:

We have a bunch of events, each event has a date field, and a separate time field that has a start and end value. I'm trying to build a module pulls in the next event that hasn't ended yet. Also, if there are more than one events on that day, we need to pull all of them.

My main problem is figuring out how to construct the values that I need to query that time field with, it seems to be stored is a format that I'm not familiar with, e.g. the value 4:30PM is stored as 59400. I can't find any documentation that specifies how to convert that value back and forth.

Any Drupal gurus / php gurus out there know what that conversion is?

Thanks, Neil

Think of it as "the number of seconds since the the start of the day". To get the number of hours from that:

59400 / 60 / 60 = 16.5

So 16.5 hours since the start of the day: 16:30, or 4:30PM.

If you're looking to get something meaningful out of '16.5' for display on the front end, the timefield module has a theme function:

$formatted = theme('timefield_formatter', array('time' => $time));

Or if you have the value in the field of an entity object, you could use field_view_field() instead. The theme function has more options, you'd need to scan through the module code to understand what these are and which you might want to use.


Drupal 8 programmatical block can't be place in "Block Place UI" I have been using drupal examples https://www.drupal.org/project/examples and developing my own examples for practice. But I have come against an issue I can't workout. Below is my link to the block code I have been developing.

d8 module block example on github

I can get the block to display under admin/structure/block, but when I press the "Display Block" button in the overlay I get no response can someone tell me why? See image

The error I am getting from the ajax call is

ajax.js?v=8.1.8:965 Uncaught AjaxError:
An AJAX HTTP error occurred.
HTTP Result Code: 200
Debugging information follows.
Path: /d8/admin/structure/block/add/pnc_block_test/pnc?region=-1
StatusText: OK
ResponseText:
Fatal error:  Class 'Drupal\Core\block\BlockBase' not found in /vagrant/src/d8/modules/custom/pnc/pnc_block_test/src/Plugin/Block/PncBlockTest.php on line 23

What I have trying to achieve is the following

Message have say

  Fatal error:  Class 'Drupal\Core\block\BlockBase' not found in
  /vagrant/src/d8/modules/custom/pnc/pnc_block_test/src/Plugin/Block/PncBlockTest.php
  on line 23

problem here is wrong typo block not Block

replace

// Module block exit. But this class not exit
use Drupal\Core\block\BlockBase;

with

//path folder core/lib/Drupal/Core/Block
use Drupal\Core\Block\BlockBase;


Drupal Search- Linking Multiple Entities with Relations as a Single Unit I've got a site that currently uses Views exposed filters for search.  I'm looking at other search solutions for Drupal in an attempt to make more complicated searches possible.

The searches on my site are of users, but the catch is that each user, in addition to a user profile, has four nodes of four different content types connected to that profile with relations (from the Relation module).  These four nodes should also be considered part of the user profile.

In Views, I handle this by adding the four relations to the view, which allows me to pull the four pieces of content into the view.  My question is, is there a way to use Search API (with or without Solr) to link each user profile with its content based on the relations?  Or is there another search solution for Drupal that can accomplish this?

I don't need a step-by-step tutorial; I just want to understand whether it's possible to use relations from the Relation module to link entities (nodes and users) as a single "unit" in search in Drupal.

This turns out to be really easy.  On the Create Index page, just add the Related Entity (User->Node) Option for the relevant relation.  The entities will then all be index together as a single unit and you can do Views and Facets and all sorts of fun things with them.


With a custom form, how to sanitize user input before query gets to URL? I followed this tutorial to create a custom Search form that takes users to the main search page with a query in the URL (meaning it uses a get method). This gives me more flexibility than using an exposed filter, so I'd like this to work. One thing that I want to do, however, is make sure that if someone searched:

<script>alert('foo')</script>

that the query in the URL would not have the tags included. Drupal has plenty of sanitization functions, so I'm not worried about that. But I can't figure out WHERE in the custom form plugin I would actually add the sanitization.

Please help! I've included the code of my plugin below:

<?php

namespace Drupal\my_custom_search\Plugin\Form;

use Drupal\Component\Utility\Html;
use Drupal\Component\Utility\Xss;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;

class MyCustomSearchForm extends FormBase {
  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'site_search_form';
  }
  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {

    $form['#action'] = '/search';
    $form['#method'] = 'get';
    $form['#attributes']['class'][] = 'usa-search';
    $form['#attributes']['class'][] = 'usa-search-big';

    $form['fulltext_search'] = [
      '#type' => 'search',
      '#attributes' => [
        'id' => array('search-field-big'),
        'size' => '',
        'maxlength' => '',
      ],
      '#prefix' => '',
      '#suffix' => '',
    ];

    $form['actions']['submit'] = [
      '#type' => 'submit',
      '#value' => $this->t('Search'),
      '#button_type' => 'search',
      '#attributes' => [
         'class' => ['usa-search-submit-text'],
      ],
      '#name' => '',
    ];

    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {

  }

}

UPDATE: I ended up adding 'pattern' => '[^/><\][\\\x22,;|]+', in the attributes array, and this at least prevents submission of text with characters I don't want. I may still try to find a JS solution that works better for the user.

Drupal's mantra is to sanitise upon output, not input. See Writing secure code for Drupal 8 for more information.

So there's no need to sanitise upon submission, just make sure that if you're rendering that value anywhere, it's done in a secure manner (as explained in the docs above).

If you decide that you still need the solution you've outlined, it's going to have to be implemented in JavaScript. Your form method is GET so the browser handles the input -> URL conversion, not Drupal.


How to use function like 'rtrim' in drupal? I need to remove extension from string, i'm wondering what function could do that ?

Some like the rtrim($string,'string to remove')

$string could be the filename

I've added a file into database, now to retrieve it, i want to remove the extension '.epub'

this is the postman response :

{
 "code": "0",
 "response": [
{
  "epub": "http://localhost/drupal/sites/default/files/moby-dick.epub",
  "f_id": "5",
  "uid": "64"
   }
 ]
 }

I want to retrieve :

"epub": "http://localhost/drupal/sites/default/files/moby-dick",<== no .epub

This is my first try :

$file = file_load($fid);
            //$realURI = drupal_realpath($file->uri); ca marche

            $realURI = file_create_url($file->uri);
            $new = drupal_basename($realURI, '.epub');
            $n = file_create_url($new);
            $res->epub = $realURI;<== show the new (without .epub)

but now it shows :

"epub": "http://localhost/drupal/moby-dick"

I need to keep /sites/default/files/ because the file is there
What can i add for keep it work with the right path please

Thank you

Use the Drupal file API to do this; file_move() will take care of renaming.

  $file = file_load($fid);
  $new_file_uri = preg_replace('/\\.([a-zA-Z]+)$/', '', $file->uri); //Remove .whatever from the file name
  file_move($file, $new_file_uri);


Programmatically show field in different regions depending on content I'm creating an Omega sub theme & three regions ("Sidebar 1", "Content" & "Sidebar 2") inside of the "Content zone". "Sidebar 1" & "Content" are both set to always show, "Sidebar 2" however is set to only show if there's content inside of it.

I also have a field which contains links related to the page, this is output programmatically into all three regions but CSS hides all but one. This is done so it can be shown in the "Sidebar 1" region which stacks above the "Content" region on small screens but on larger screens it'll be hidden in the "Sidebar 1" region & shown in the "Sidebar 2" region instead, on the right hand side. If "Sidebar 2" doesn't exist it'll then be shown in "Content."

"Sidebar 1" pretty much only contains a menu, only on some pages though, which is again programmatically output. The reason being that I want to label / title of the menu to be set to the name of the currently active page and it was the best way I could see of doing it.

I've almost got it all working as I have a class set on the content zone div which states how many regions are inside of it (2 means no "Sidebar 2", 3 means it's there) & the first sidebar now adds a class stating if it's empty or not.

I've attempted to add a class to the "Sidebar 2" region by using drupal_get_region_content("sidebar_1") to detect if the "Sidebar 1" region is empty of not and add a class to the "Sidebar 2" region based on this will CSS selectors will use. Problem is no mater what I try or what region I try to output drupal_get_region_content always returns NULL.

The basics of what I'm trying to do
I'll try and write here what I'm wanting in a more concise manor, above I've also included how I'm trying to do it.

I have some pages with three regions in the content zone, I want to output a field in all three regions so they can be shown & hidden at different screen sizes with CSS.

The left sidebar might have a menu in which is added programatically. If it does not have this then the second sidebar doesn't need to the field I'm outputting programmatically will just be shown in the first sidebar & main content area.

I realise this is very long, appreciate anyone who's read it and any help you can offer.

"I have some pages with three regions in the content zone, I want to
  output a field in all three regions so they can be shown & hidden at
  different screen sizes with CSS..."

If this is the case, you could solve this entirely in CSS, by using media queries to show / hide areas -or your field -depending on the browser size. And you don't even need to have the same field in all the three regions.

However, if what you want is to show / hide columns inside your content depending on a field value, you might be looking for the Display Suite module, which allows you to easily create different layouts and view modes. For example, you could:

Create one view mode with 2 columns and another one with 3 columns.
Add the fields you want to display in each one of those view modes.
If you want to switch the view mode, depending on whether a field has a value or not, you could use hook_entity_view_mode_alter() like this:

function YOUR_MODULE_entity_view_mode_alter(&$view_mode, $context) {
  // If viewing a node in the two_columns view mode...
  if ($context['entity_type'] == 'node' && $view_mode == 'two_columns') {

    // If your field 'something' has a value, change the view mode to 'three_columns'.
    if (!empty($context['entity']->field_something)) {
      $view_mode = 'three_columns';
    }
  }
}

Or you could also use the Contextal View Mode module to change the view mode for a node based off of a context.


Drupal Website showing only some images I was told to migrate a Drupal website, but I've never worked with it before so I'm having some difficulties here. I'm trying to run the site in localhost/myfolder.

The URL generated for images is:

/sites/default/files/images/myFile.jpg

The link is broken because it should be:

myfolder/sites/default/files/images/myFile.jpg

I have this on my sites/default/settings.php file:

$base_url = 'http://localhost/myfolder';  // NO trailing slash!

I also added this to my myfolder/.htaccess file:

RewriteEngine on
RewriteBase /myFolder

I ran out of ideas, any help would be deeply apprecciated. Thanks.

While migrating a site from a local instance to a staging instance there is always such problems of links of the images. we normally give myfolder/sites/default/files/images/myFile.jpg but while migrating to staging instance it should be /sites/default/files/images/myFile.jpg so that the server could trace the images.

If we use give myfolder/sites/default/files/images/myFile.jpg it would work fine within your local instance but while on staging it wont get loaded.

So always give /sites/default/files/images/myFile.jpg so that there is no problem....