How to remove the form_state, form_id and form_build_id when submitting a form? I have been creating a payment gateway integration module for Drupal 7.

When I post the form to the payment gateway API, it is posting extra variables like form_id, form_build_id, and form_token.

Can anybody tell me a way to eliminate these extra variables?

In Drupal 7, you can use the form_state_values_clean() function that removes:

form_id
form_token
form_build_id
op

Usage example:

<?php
/**
 * Let's say this is your form.
 */
function your_form($form, &$form_state) {
  // Form items go here.

  // Let's add the form actions element...
  $form['actions'] = array(
    '#type' => 'actions',
  );

  // ...and the form submission button with a function callback that removes
  // 'form_id', 'form_token', 'form_build_id' and 'op' values upon form submit.
  $form['actions']['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit'),
    '#submit' => array('your_form_submit'),
  );
}

/**
 * And this is the submission handler/callback for your form where
 * 'form_id', 'form_token', 'form_build_id' and 'op' values will be removed.
 */
function your_form_submit($form, &$form_state) {
  // Let's unset 'form_id', 'form_token', 'form_build_id' and 'op'.
  form_state_values_clean($form_state);

  // Now the $form_state['values'] doesn't contain 'form_id', 'form_token',
  // 'form_build_id' and 'op'.
  $form_values = $form_state['values'];

  // Do the rest…
}


Responsive image styles In /admin/config/media/responsive-image-style. I created a responsive image style. The breakpoints group is bartik so now I have 3 breakpoints. Wide, Narrow and Mobile. I want to use a new image style I created called small, its 80x80 scaled pixels. I set all 3 breakpoints to use small. But in Mobile I want the image to stretch a little maybe have it go from 120 wide to 80 wide. Is this possible? Does that make sense? If I select multiple image style under small this field appears Enter the value for the sizes attribute, for example: (min-width:700px) 700px, 100vw. What does this mean and where can I find some format examples?

Responsive Image Style:
Here you can tell WHEN and WHAT STYLE to apply
Image style:
Here you can tell WHAT OPERATION should take place on the original image.

Create a new image style with scale & crop (or whatever fits you) first,
and then set this image style to the right Responsive Image Style interval (in your case the smallest)


orConditionGroup() - unexpected result $query = \Drupal::entityQuery('node');

$group = $query->orConditionGroup()
 ->condition('field_ref1_user.entity:user.uid', $user->id())
 ->condition('field_ref2_user.entity:user.uid', $user->id());

$ids = $query
 ->condition('status', 1)
 ->condition('type', 'mynodetype')
 ->condition($group)
 ->execute();

The first condition in $group met 3 nodes and the second condition met 1 additional node (different from 3 nodes of condition 1) so since it is OR condition I expect to get 4 node IDs but I receive only 3 node IDs that met the first $group condition.

If I switch the conditions within the $group, I get 1 node ID, that met the first condition. It's seems that the second condition in the group is ignored.

What is wrong with my code?
Is there a way to see the query that actually executed?

Edit
I have activated WebProfiler to see the actual query.

WHERE (node_field_data.status = '1') AND (node_field_data.type = 'mynodetype') AND ((users_field_data.uid = '11') or (users_field_data.uid = '11'))

These are 2 different user reference fields but for both of them the query checks users_field_data.uid = '11'

I can't see any issues with your code, and this might be a dumb answer, but a while back I was having trouble with chaining together entity query conditions. I got everything working by splitting it into individual statements. It didn't seem logical that that should make a difference, but it did. (Though, I'm sure it's possible I had some other logical problem that was the actual issue, and separating into statements was just incidental.) But maybe try...

$group = $query->orConditionGroup();
$group->condition('field_ref1_user.entity:user.uid', $user->id());
$group->condition('field_ref2_user.entity:user.uid', $user->id());

$query->condition('status', 1);
$query->condition('type', 'mynodetype');
$query->condition($group);
$ids = $query->execute();


Why are some menus created for authenticated users not displaying? Whatever menus created for authenticated user, some menus are displaying and some created menus are not displaying.

If I login as admin, it shows all created menus and its child menus.

Why is this?

Some of the links are not visible to authenticated user, because the URL you provided to respective menu links are not accessible to authenticated user.

Example: Suppose menu link is Add Article and URL is /node/add/article. So here if authenticated user not having Article node add permission, then in such case Add Article will not be visible to that user.


How to add a new row to the registration form? I'm using LoginToboggan module. Via this module user can register or login.

And now I want to add another row to this form. For example: Phone number or Age.

How can I achieve this? Or is there another way of achieving this?

Without using LoginToboggan also you can achieve you requirement.

Goto Configuration > Account settings > Manage Field and then add field.
In field configuration Display on user registration form checkbox.


Override container.html.twig template for a specific context I would like to override the container.html.twig template but the twig debugging tool doesn't give any suggestion.

I tried to add suggestion following https://drupal.stackexchange.com/a/249565/85029 answer but I end up with the suggestion being container----.html.twig.

The context is a display field with an embed view in a node.

I guess, the solution might be pretty close from what I have now (using the suggestion hook) but I'm not able to have some satisfying suggestion.

My current hook is

function mytheme_theme_suggestions_container_alter(&$suggestions, array $variables) {
  $element = $variables['element'];

  if (isset($element['#type']) && $element['#type'] == 'view') {
    $suggestions[] = 'container__' . $element['#name'];
    $suggestions[] = 'container__' . $element['#name'] . '__' . $element['#display_id'];
  }

  if (isset($element['#type']) && $element['#type'] == 'container' && isset($element['children']['#type'])) {
    $suggestions[] = 'container__' . $element['children']['#type'];
  }
}

Edit :

Ended up with something corresponding to my expectations by adding

if (isset($element[0]) && $element[0]["#theme"]) {
    foreach ($element[0]["#theme"] as $themElem) {
        $suggestions[] = 'container__' . $themElem;
        }
}

I just did this a month ago for the same reason:

/**
 * Implements hook_theme_suggestions_container_alter().
 */
function mytheme_theme_suggestions_container_alter(&$suggestions, array $variables) {
  $element = $variables['element'];

  if (isset($element['#type']) && $element['#type'] == 'view') {
    $suggestions[] = 'container__' . $element['#name'];
    $suggestions[] = 'container__' . $element['#name'] . '__' . $element['#display_id'];
  }

  if (isset($element['#type']) && $element['#type'] == 'container' && isset($element['children']['#type'])) {
    $suggestions[] = 'container__' . $element['children']['#type'];
  }
}

This will work for Views and general types. It is coming up blank because you need to handle it a little differently depending on whats being rendered.

Then in my twig file I am just doing:

{{ children }}

because I didn't want wrapping divs.


Taxonomy breadcrumb on taxonony block in views (by contextual filters) I have set up a block that shows up on the relevant pages that shows up other nodes with the same taxonomy terms (by means of contextual filters that take the argument from a given page).

Can I add a breadcrumb to the header of this block view? I have Crumbs installed.

Example Case:
This is a commerce site, and all the products are tagged by 2 vocabularies: "category" and "collection". Items that share a category tag are "internally similar" (say, all the apples), while "collection" tage are whose that the seller wants to present as similar (say, an apple and a specialized apple knife).
At the bottom of the product page are two blocks (views, contextual filters that take term argument from page) that display products that share both respective taxonomy terms with the main product on the page, and I want those to have a "taxonomy breadcrumb": not only a title with the (linked) tag  name, but also its parents (s).
I have actually  achieved that functionality by adding a views attachment to the block views.

I think this could be done with Crumbs programmatically, but this might be overkill. It would also be fragile, because it would depend on Crumbs functionality that is not really part of the public API, so could change in future versions of Crumbs.
Also consider that you don't really need the full breadcrumb, just the taxonomy trail.

Instead, you could write a custom Views header plugin. Unfortunately it is a bit hard to find documentation on that.

Or, you could alter the views header with one of the views hooks.

Or you could use the theme layer to override the views theme output for this specific view.

Or override the block template for the specific block. I think this one is actually the easiest for a starter, and for this specific situation. You can get the taxonomy term from the node, and you get the node with menu_get_object().

Have a look at https://api.drupal.org/api/drupal/modules%21taxonomy%21taxonomy.pages.inc/function/taxonomy_term_page/7 to see how the taxonomy page calculates a breadcrumb based on the taxonomy hierarchy.

(I am mentioning more than one solution here, because other readers might have slightly different requirements.)


Tracking Sessions and Calling a web service I have a module that simply has a couple functions that retrieve cookie information, set cookie information and calls a web service using the web service client to help track the users information.  However, when i installed the module, it did not recognize the function that executes the loading of the service from the web service client.  It returned the following error:

Call to undefined function wsclient_service_load()

The code is simple and looks like this:

function set_session_tracking_data() {
$sessionGuid = com_create_guid();

//Time for Cookie Experation
$time = time()+3600;

if (isset($_COOKIE["Drupal_VisitorGUID"])) {
    $sessionId = $_COOKIE["Drupal_VisitorGUID"];
}
else {
    $sessionId = $sessionGuid;

    setcookie('Drupal_VisitorGUID', $sessionId, $time);

    $params = array('visitorGuid' => $sessionGuid);
    $service = wsclient_service_load('tracking');
    $result = $service->CreateVisitor($params);
}
}

The function set_session_tracking_data is being called from a module created solely for tracking purposes.  It has no hooks.  Simply has a function called set_tracking_params() and in that function we call set_session_tracking_data().  The code is below:

function set_tracking_params() {
//Sets Module Path
$modulePath = drupal_get_path('module', 'eddy_tracking');

//Time for Cookie Experation
$time = time()+3600;

if (!isset($_COOKIE["cid"]) && !empty($_GET['cid'])) {
    setcookie('cid', $_GET['cid'], $time);
    dsm($_COOKIE["tsource"]);
}

if (isset($_COOKIE["key"]) && empty($_GET['key'])) {
    setcookie('key', $_GET['key'], $time);
}

set_tracking_params()
}
set_eddy_tracking_params();

I made the wsclient a dependency but it still does not recognize the function. If i put this same code within a block module i created, the code executes without a hitch.  Can someone please help me with this issue?  Or perhaps someone can mention to me the best practice at setting sessions and tracking a users session.  Any help would be greatly aprreciated.  Thanks!

There seems to be a bit of confusion in your code: the set_tracking_params() function calls itself, which would would result in an infinite recursion.

That being said, you're calling the set_eddy_tracking_params () function directly in the PHP file which means it will probably be executed before Drupal's full bootstrap has run, and before the wsclient module file has been loaded.

If you're trying to run this function on every page then hook_init() would be the best place for it; it's called early on in every page load:

function MODULENAME_init() {
  set_eddy_tracking_params();
}


Drupal 8 Installation Is Just Plain HTML I just installed Drupal 8 in a subdirectory. I pushed all of the files to the directory, I installed Drupal with a minimal setup and and edited my .htaccess file to make Drupal work with my subdirectory. Now, it displays my website, but without any CSS or Javascript. It's just plain HTML text. How can I fix this problem?

Wow. I just solved the problem. I didn't realize that by default on a Minimal installation that the Stark theme, which is simply a plain HTML theme, was enabled by default. I switched the theme and now it works fine.


How to create another Front Page and switch between the two? (in dev process) I am working on creating an alternative front page for an existing site. I do not want to disturb the existing front page but I just want to create another page (which I will later point to as front page - once design is complete).

Question: How do I create a page where I can add Blocks and other items? (I did it from Views - but doing so from Views requires me to add fields).

I do not want to add fields from views - want to do it entirely with blocks (even in the main content area)

You can use context http://drupal.org/project/context to achieve this.  You can filter on the path and then add blocks to that specific page.

But you will need a holder page.  Sometimes I create a holder content type and then modify the node template to not display anything or just the title.  Then I can attach any view/block or w/e to it.  So that piece of content is just a "holder".


Which link field accepts an URL or a Node reference? I am looking for a field just like Link, but that allows the user enter a URL or via an autocomplete a node/entity reference.

This is because this field might be an external link or an internal link in which case it should refer to the entity.

Any suggestions?

In Drupal 8 this works with normal link fields. You simply can choose if only internal, only external or both type of links can be entered in this field. You'll then get a autocomplete field that accepts either an entity title or an external link and a title.


Language fallback to site default in internationalization This should be simple enough; but, I'm trying it since a day now with no success.

My site contains listing pages or different content types. By default all the content is of language "English".
When a user (author) translates a content in the listing to other language (say Spanish), and switches to that language using "language switcher"; only nodes of that language are being listed.
This is because I've added Content: Language (= Current user's language) filter to the view.

What I require is when a node does not have a Spanish translation, it should show that node in English. In short I want "English" as a fallback language to all the views (and site). I've tried ORing the filters so that I could list "current language" OR "English", but it shows the both the translated nodes and their corresponding nodes in "English", which is obvious.

Note I've made it compulsory for a user to select content for every content type.

I've tried Language Fallback module, but it did not work.

I think what you need is this module: Select translation

  The options are : Use current language ; if not available use original language

I've used it before and it works pretty well.


How to make Toolbar unsticky at the top? Drupal 7

The toolbar is sticky at the top even you scroll down the page.

How can I make it unsticky at the top?

Thanks.

The fixed position is hard-coded into the toolbar.css file included with the core module.

To override it add the following to a CSS file that you're including with the admin theme:

#toolbar {
  position: static !important;
}

body.toolbar, body.toolbar-drawer {
  padding-top: 0 !important;
}

The !important declarations may or not be necessary depending on the order of inclusion...try without it first, and if it doesn't work, try adding it.


entity_form removes uid So i have defined a block

case 'foo_post':
    global $user;
    $values = array(
        'type' => 'foo',
        'uid' => $user->uid,
        'status' => 1,
        'comment' => 0,
        'promote' => 0
    );
    $entity = entity_create('node', $values);

    $ewrapper = entity_metadata_wrapper('node', $entity);
    $ewrapper->og_group_ref->set(menu_get_object()->nid);

    $block['subject'] = t('Create a new foo');
    $block['content'] = entity_form('node', $entity, 'add');
    $block['content']['#attributes']['class'][] = drupal_html_class('panel-body');
    $block['content']['title']['#access'] = FALSE;
    $block['content']['form_title'] = ['#markup' => sprintf('<h4>%s</h4>', $block['subject']), '#weight' => -1];
    $block['content']['form_advanced'] = [
        '#collapsible' => TRUE,
        '#collapsed' => TRUE,
        '#type' => 'fieldset',
        '#title' => t('Advanced settings'),
        'additional_settings' => $block['content']['additional_settings'],
        'og_group_ref' => $block['content']['og_group_ref']
    ];
    unset($block['content']['og_group_ref']);
    unset($block['content']['additional_settings']);
    break;

Most of the things work already, except the form wouldn't take the user ID of the user submitting the form. What did I do wrong here?

The $user variable may not be set in this context - it is not automatically available as a local variable.

Try adding global $user; before the code.


Views, Blocks, and Content Types I made a content type where I have used views to make my content into a block. But the content type's page shows two copies of the data. One from the content type, and another from the block made through views. I want the data that is shown through views, but I also want to keep the edit content tab for easy editing. I am not sure what other information I need to give to make the problem clearer.

From what i understand, you are most probably doing it wrong :).

If you want to change the node display, have a look at the Display Suite.

If you insist on changing it with views, you might want to switch to a page display, set the path to node/nid to override the default node view and do what you need there.


Webform submitted data in views I am using the Webform and displaying it using the Views module.

Unfortunately, I couldn't get the submitted data of the webform in views.

Any suggeestions?

you need to add new view 'admin/structure/views/add' and into Show select webform submission continue and edit ... you can get all the submission list into the view.

Add field webform submission data:value

Then select webform node and field you want.

You can see the fields like this

View result

Try it.


Displaying titles of collapsed menus I'm currently converting a mock-up and I need to display four menus in a list, the first two are expanded, and I need to display both the titles and menu items, and the next two are collapsed, so I need to display the titles but not the menu items. It should look something like this:

Menu 1

Menu item 1
Menu item 2
Menu item 3

Menu 2

Menu item 1
Menu item 2
Menu item 3

Menu 3
Menu 4

Is there an easy way to do that in Drupal's admin panel?

The "easiest" way to do this in Drupals admin panel is to set the menu titles as parent menu items and use "Show as expanded" settings (admin/structure/menu/item/yourmenuname/edit) and hide the menu-names with the block name settings (set to <none>)


how do i create a site that allows users to create "organizations? I'm creating a site where users should be able to create organizations(groups) that other users should be able to join....a list of these orgs should be accessible by all users of the site on an "orgs" page.....whats the best way to do this? thank you very much!

The module to do this with in Drupal would be Organic Groups https://drupal.org/project/og. It's not a trivial module though. Here's the official documentation: https://drupal.org/node/1114858.

There are some online courses available from for example Lullabot: http://drupalize.me/series/organic-groups-drupal-7
and Brian Lewis: http://modulesunraveled.com/organic-groups-7x-2x.


How to prevent required field validation in validation function? Issue: When create a node and node publish check box is checked, all validation should work (it's working fine). but when create a node and node publish check box is not checked , then all validation should skip.

function mymodule_form_alter(&$form, &$form_state) {
   array_unshift($form['#validate'], 'mymodule_reqursive_unrequired');
}

function mymodule_reqursive_unrequired(&$form, &$form_state) {
    // print_r($form);die;
    $form['actions_copy']['submit']['#limit_validation_errors'] = array();
    $form['actions']['submit']['#limit_validation_errors'] = array();

    $form['title']['#required'] = FALSE;
    $blog_images = $form['field_image_blog'][LANGUAGE_NONE];
    $form['field_page_title'][LANGUAGE_NONE][0]['#required'] = FALSE;
    foreach($blog_images as $image_k => $blog_image) {
      $form['field_image_blog'][LANGUAGE_NONE][$image_k]['#required'] = FALSE;
    }
    // print_r($form);die;
}

Any suggestion ?

After a lot of debugging and search i get the solution.

function mymodule_reqursive_unrequired(&$form, &$form_state) {
    // print_r($form);die;
   if(!$form_state['values']['status']) {
     drupal_static('form_set_error', NULL, TRUE);
     drupal_get_messages();
   }
    // print_r($form);die;
}

for reference check it


Paragraphs preprocess I want to give content editors the ability to add a Feed of some sort (Maybe Twitter, Tumblr, etc) to a particular node.  I'd like to use Paragraphs because I want them to be able to drop this Feed in between various other pieces of content.

The Paragraph Bundle would just have one field to accept the resource URL.  I would do all the necessary processing behind the scenes and would send the formatted content back to the node via a twig template.

I've got a version working using a block instead of a paragraph bundle, and I'd like to use the same custom module to allow for a paragraph, but I'm unsure in Drupal 8 how best to structure this.

The best I can come up with, is a preprocess function of some sort- preprocess_node, or preprocess_paragraph (which I think exist in D8) that would kick off the whole thing, but I was wondering if there was some kind of base Entity class that has a method I can overwrite or something. (Similar to how the BlockBase class has the "build" method.)

A paragraph is a content entity with fields, that is viewed within its parent entity. It uses exactly the same mechanism to be displays as nodes, comments, and so on. Through field formatters.

You can implement your own field formatter plugin that transforms your (link?) field in any way you want. You receive field items and have to return a render array. That's the only restriction.

Like all plugins, it's a class with an annotation, in a specific namespace/folder. The default formatter for link fields is LinkFormatter. The most important method is viewElements().


how to change hierarchical taxonomy path using Pathauto i have posted it on drupal forum also  but there was no answer. Here is that:

  i am really working hard to know how i can add sub-categories in drupal 7. so i want to change the path of parent terms taxonomy path like this way:
  Category 1 - Path should be: mysite.com/category/Category 1
  - sub category 1 - Path should be: mysite.com/category/Category 1/sub category 1
  - sub category 2 - Path should be: mysite.com/category/Category 1/sub category 2
  Category 2 - Path should be: mysite.com/category/Category 2
  - sub category 1 - Path should be: mysite.com/category/Category 2/sub category 1
  - sub category 2 - Path should be: mysite.com/category/Category 2/sub category 2
  i think this can be done with URL aliases > PATTERNS
  but as a beginner i am really confused how to do. So, some one please help as can be described.

this work for me:

[term:vocabulary]/[term:parents:join-path]/[term:name]

this pattern generates the path: Category-Name/Category-1/sub-category-1/Term-Name


Having different theme elements for different pages I am trying to wrap up an HTML theme into a drupal template and I cannot get right idea on how to do this.

I am having a front page, that is unique in it's elements. Then, I am having another page that only keeps the header from the front page, and footer. On this page, I am having some boxes, in witch the content should be nodes. How can I do this?

After that, I am having different pages where I need to add their elements from the admin panel as content. So, there will be more categories, and I need to list the elements from each category into some pages that have different style.

Also, there are regions like footer, where I have some logos ( images ) that again, they need to be nodes and added/edited from the admin panel as content.

Can someone point me to the right direction?

I have tried to create some pages from the admin panel, and tried to use files like page--.tpl.php to have a page in witch I should add nodes/content as the page elements but it is not rendering. Neither if I try lie page--node--.tpl.php or things like that.

I have searched on google for a few hours but I haven't mnaged to get the propper solution.

Thank you in advice!

Best regards,
Alex

Check out Context module - it will allow you to structure the website based on the node type, URL or other parameters. Depending on this, you can have different blocks displayed, or use different layouts.

See also Display Suite and Panels modules for even more possibilities.

If you want to avoid using additional modules, you can achieve similar functionality through code and preprocess_html or preprocess_page implementations. You can specify special templates that will be selected dynamically, e.g.:

function MYTHEME_preprocess_page(&$variables) {
  // Make sure we are on the single node page.
  if (arg(0) == 'node' && arg(1) && !arg(2)) {
    // This will allow you to have separate page.tpl.php template used only
    // for single nodes. You should have page--single-node.tpl.php file in
    // your theme to see this in action. You can combine this with any
    // additional number of conditions, e.g. node type, user role etc.
    $variables['theme_hook_suggestions'][] = 'page__single_node';
  }
}


Asking for confirmartion on node creation I want ask for confirmation if a duplicate node is getting created. But how do I do it?

I know how to do it if I'm creating the form myself but in node creation I'm not creating the form.

I also know Drupal confirm_form, how "storage" is used in multistep forms. But how to use it along with the code which is not mine. Where to plug it?

@AgA: "I want ask for confirmation if a duplicate node is getting created. But how do I do it?"

The way you do it is to validate any new node added by a user against existing nodes.

Towards this end, hook_node_validate() is your friend. :-) You'd make a module that implements hook_node_validate(), and within that function do a query using the data the user input. If you find similar nodes that already exist, you can form_set_error() an error message. Click through to the API site and there's even some sample code.


Programmatically add a taxonomy term to an existing content type How would you programmatically add a taxonomy term to an already created content type? Presupposing that I already have the taxonomy field available on all the selected content-types beforehand.

I wish to bulk add a taxonomy term to several nodes. I noticed in the content display list there is a way to filter down to a term when it already exists on nodes, but is there a way to possibly add it to a content-type that doesn't have it yet?

I read the question and comments for Programmatically create taxonomy term, and this is partially there, but I don't know how to get it further.

You should check out the Views Bulk Operations (VBO) module. It allows you to create a View to generate a list of target nodes (or other things like Users) and perform an action on each of those nodes. One fo the available actions is modifying the taxonomy terms used on these nodes. This is actually the exact example used in the documentation for VBO on d.o. It seems like this is exactly what you're looking to do, just not actually programmatically. Maybe that's ok... but if not, you can create this VBO and then execute it programmatically using views_bulk_operations_execute.


Entity field query issue to correctly sorting my results I have field order in my content type, in which I have assigned numeric values for my 21 products in order to sort them in ascending order. Results should be displayed like the below order as I expect:

1
2
3
4
5
6
7
8 and so on to 21.

But products are displaying in the following order:

1
10
11
12
13
14
15 up to 19 then
2
20
21
3
4
5
6 up to 9

I dont know why. Here is my snippet.

 $query = new EntityFieldQuery();
 $query->entityCondition('entity_type', 'node');
 $query->fieldOrderBy('field_order', 'value', 'ASC');
 $query->entityCondition('bundle', 'my_content_type');
 $query->pager(8,0);
 $query->propertyCondition('status', 1);

I can't make Molot's comment an answer, but I'll post one for posterity (and to close out this question).

The issue involves your data field type, integer vs. string. When the field is a string, sorting in SQL query will place the rows in lexicographic order, where the first character value is given precedence. When the field is an integer, sorting in SQL query will place the rows in numeric order, where the entire value of the number is used.


Where do I find the Facebook application id for the the fb_social module? I just installed the fb_social module. Now I need to set up the module which requires the Facebook application id.

Under the field reads: Get the ID of your facebook app or create a new facebook app : here.

But the link drive me to the main page of my facebook account.

Where is the right place to find it?

Login as FB app admin
Go here: https://developers.facebook.com/apps
Copy the destination for "Edit settings" link for your app
Take app ID from the URL. This is the pattern: https://developers.facebook.com/apps/[your app ID]/summary


Conditional statement doesn't work in node.html.twig I want to use {% if %} in a node.html.twig, but it doesn't work.

I am using this code.

{% if content.field_number == 0 %}
  zero
{% else %}
  one
{% endif %}

It always print one.

The following code always print zero.

{% if content.field_number %}
  zero
{% else %}
  one
{% endif %}

What code should I use to zero when the field contains zero?

content.field_number is the rendered output and the value of the field is somewhere inside the render array, for example in a #markup. But this will change whenever someone reconfigures the view mode.

It is better to use the node object in this case, because the field value will be available for all view mode configurations:

{% if node.field_number.value %}
  not zero
{% else %}
  zero
{% endif %}


How to access Vertical Tabs from Contrib Modules in Panels? Drupal node forms have a vertical tabs area, which provides options such as "Revision Information", "Authoring Information", "Publishing Options" etc.
Contrib modules such as Node Hierarchy and XML sitemap can add custom tabs to this area.

How do you access these tabs from contrib modules in Panels.

In the past, with Drupal 7 & Panels, you could access them via the "Form" section of "Panels > Add Content".
However, I am creating a new Drupal 7 site and I can no longer access Vertical Tabs from Contrib modules. Only the tabs from Code Drupal modules are shown.

Steps I have tried to overcome the problem:

1) I have made a fresh install with just Panels and Node Hierarchy.
I have made a second fresh install with just Panels and Xml Sitemap.
In both cases, Vertical Tabs from Contrib modules are not accessible.

2) I have tried installing Node Vertical Tab Elements. It too only gives access to core tabs (and not tabs added by Contrib modules).

3) I have tried upgrading my older Drupal 7 sites to the latest versions of Drupal 7. In these older sites, the Vertical Tabs from Contrib modules are still accessible, so I am not sure if this means a special setting is required to access the tabs. I have disabled all custom themes and modules on the site, so I know the tabs are not coming from custom code.

Any help would be most appreciated.

Sounds like this should work.

In your 1) scenario, where you restricted your installation to the minimum amount of modules -- you might have run into a change/bug with a module version which you intentionaly have upgraded. Try not to test with "most recent versions".

Because you phrased your experience as "in the past you could ...".


how to alter a hook_field_insert I am trying to find a way of altering the output of a hook_field_insert. In my exact example, I'm trying to hook into the link_field_insert hook, in the Link module:

/**
* Implements hook_field_insert().
*/
function link_field_insert($entity_type, $entity, $field, $instance, $langcode, &$items) {
  foreach ($items as $delta => $value) {
    _link_process($items[$delta], $delta, $field, $entity);
  }
}

and make a modification to the _link_process function, without actually having to hack the Link module. Is thi possible?

Just to have some background, what my end goal is to add a new form field on the node page for the user to enter link classes, and these classes would be autmatically applied to the link. I have already overridden the theme_link_field to add this form field and its value shows up in the $items array in the above function, so I just need to know how to override the above function.

you don't need to alter the hook. You can implement the hook. But in your case maybe you want to use theme_menu_link() instead
Customizing menu link output

also check https://api.drupal.org/comment/55298#comment-55298


Allow a user to manage his/her own users and be able to assign roles I need to give access to a specific user with a specific role to be able to give the user role but not the administrator

My case is that the website I'm building needs different kinds of admins and roles, for the role I need to find a solution is for a sub-admin this person should be able to add users and assign roles and I also want this person to only be able to manage the users he adds not all the users.

I found that by using flags and roles might be the best way I found this answer to the question "Give a specific user role the ability to give a user a role but not the 'administrator' role". My problem is that I'm not proficient in Drupal and I'm not sure what to add in this window https://pasteboard.co/H7E7rX9.png I'm trying to learn more about rules seeing that probably I'll be using more of this on my project

Thank you so much for your help.

Have a look at the Group module (commonly perceived as an alternative for Organic Groups).

Group allows for creating arbitrary collections of your content and users on your site, and grant access control permissions on those collections. It is available as of D7, and has a D8 version also. The Group module creates groups as entities, making them fully fieldable, extensible and exportable. Which also makes it integrate very well (out of the box) with commonly used modules such as Rules, Views, etc.

The way you described in your question how you imagine using the (great!) Flag module, translates more or less to "Is user X yes or no member of Group G?" combined with "What group roles does this user have". However, after you will understand / realize all the things you can do with the Group module (with zero custom code ...), you'll probably also understand that trying to do something similar with the Flag module, is going to take a lot of flags, and related Rules logic.

More info

Some more questions you may want to look at for more details:

How to configure access to courses for teachers and students?, which contains a sample configuration.
What are the various roles supported by the Group module?, which explains the various types of roles that can be used.
How to bulk assign existing content to a group created with the Group module?, a typical issue when adding this module to an existing site.
What are the features of the Group module versus Organic Group module?

Resources

Community documentation for the Group module.
Video tutorial "How to use the Group module in Drupal 8 to manage editorial access control to different areas of a web site".


Access Denied on file attachment when node state is Draft in Workbench I have a file attachment field defined in a content type I have under Workbench moderation. The file field stores the attachment in the private files folder.

PROBLEM:

When I create a node for that content type and view it in Draft mode I get a 403 access denied if I try to download the file attachment with any role other than admin.  If I publish the node I can download the file fine. Revert it back to Draft and I'm back to the 403 access denied.

I've tried enabling “Bypass moderation restrictions” for a role but that does not work around this error.

I really need a solution/workaround for this issue since I have a non-admin role that needs to be able review the node and the file attachment posted by users before they are published. I'm sure this is a fairly common scenario but I haven't been able to find any posts with a similar issue.

When using the private file system file_file_download() only checks access for files attached to the current revision of an entity (via file_get_file_references()).

This is to stop users who have access to view the node from viewing files attached to old revisions (that might contain out of date files), and other similar things.

If there are no current revisions that contain that file it returns NULL, which then in file_download() means that get access denied.

See a related drupal core issue: https://drupal.org/node/1453138
The D8 version of that issue is: https://www.drupal.org/node/1452100

In theory, you should be able to implement a hook_file_download() that checks all revisions by essentially copying file_file_download, but making file_get_file_references() return for all revisions.

The problem with that solution is it can introduce a security hole, which is that users who have access to view the published version of the node can also now view files attached to other revisions of the node, which depending on your use case may or may not be an issue but since you are using the private file system in the first place I assume it might be a problem.

To avoid that, you could then implement hook_file_download_access(), which does more complex access control than just calling node_access() like the node_file_download_access() function does.
In that hook you would want current revisions to run through node_access() and non-current revisions to use extra access control, like checking the users workbench permissions or node creation/editing permissions.


How to create an 'Add item' contextual link for views? I like the concept of contextual links in D7 and want to push it a bit further: I want views to have an 'Add item' contextual link, so the site administrator can easily add new items.

Of course I could add an 'Add item' button to the view's footer instead. But I need to show it only to users who have the appropriate permission to add items.

Is there an idiomatic way of doing it?

Checkout the Custom Contextual Links module. I haven't personally used it but it looks like it does what you're after. It also supports views as of 7.x-1.1.


Add class to menu link href tag? I know that using hook_menu_link I can add classes to the <li> tags but I need to add a class to the <a> tags within the <li> of a menu. I've looked and can't find a way.

Any ideas?

You can do it from hook_menu_link. You want to access the $vars['element']['#localized_options']['attributes']['class']

Something like this

$element = $vars['element'];
$element['#localized_options']['attributes']['class'][] = 'your-class';
$output = l($link_text, $element['#href'], $element['#localized_options']);

Then return the $output in the <li>. Be sure to account for $vars['element']['#below'] if you have a sub-menu.


Filter criteria works on first value I am working on a view where I need to show publications (a content type) in which authors (another content type) should be active (have a specific value for one of their fields).

I am using a relationship to add the fields for the node authors, and then add a filter criteria for checking if they are active or not. It is working in a way that is not what I want. It shows all the publications which has at least one active user (and maybe some other inactive users), but I want to have the ones in which all of authors are active.

What am I getting wrong here? could you please help me?

Step 1

To have such a list of authors that can be referenced, you should first (repeat: first) create a view (with the Views module) to create a list of all the authors that are allowed to be selected. And the display type of such view must be an Entity Reference display.

Step 2

Your select box field (to select from a filtered list of authors) should be field that looks like so:

Field Name = Anything you want, eg field_authors_list.
Field Type = Entity Reference, using these additional settings for it:

Target type = node
Number of values = 1, though something like "unlimited may do as well (not clear to me from your question).
"Mode" (within "entity selection") = Views: Filter by an entity reference view. However, before you can select an appropriate view at this point (which is eligible to do so), you first need to create a view with an Entity Reference display, or add such a display to an existing view. In your case, you should select the view created in "Step 1".
Pick any of the other options to define this field as you see fit.

Step 3

If the list of authors you can select (after completing the previous 2 steps) is not exactly what you want, eg "you want to have the ones in which all of authors are active, whereas active means 'have a specific value for one of their fields'" (as in your question), then refine/tune the view in step 1 so that the Views results do match with what you want the list to look like.


A change in the production site affects test and staging sites and vice versa I have a production site like www.example.com and I use 2 subdomains test.example.com and stage.example com for testing and staging purposes. Each of these 3 versions of the site uses it's own database. The user and password is the same for all 3 databases, but of course the database names differs. I have checked and double checked that the correct database names are set in the settings.php file for the 3 sites, respectively.

Nevertheless, when I do a content change in one of these 3 site versions, that same change becomes immediately visible in all 3 sites.

I have tried to turn off all my caching modules, like Boost and Memcache and Content.

EDITED:
I have now narrowed it down to a caching problem. If I flush all cache in the site that shows the wrong content, it reverts to the right content. So content changes ends up in the right database. But as I said, even though I have all caching turned off, and all caching modules are disabled, all content changes in one site are immediately reflected in the 2 other sites (until I flush all cache in these 2 other sites).

Does anyone have an idea about where to look? Some common caching in the server environment?

What you're describing can happen when you link several sites up to the same cache system, but give the same prefix for each of them in settings.php (or don't provide a prefix at all, which is essentially the same thing).

I'm not 100% sure, but disabling the memcache module might not stop it being used if you're declaring its use in settings.php, which you most likely will be.

It might not be the cause, but it definitely could result in exactly the situation you find yourself in. Check settings.php in each of the sites, and see what the state of those prefixes are. If this is the problem, providing different prefixes for each site will fix it straight away.


How to get facebook user id after login I am using Drupal for facebook module to login into my drupal site. How can i get facebook user id after user login to my site. I want to store user details and give a chance to edit his profile. I can able to track firstname and Lastname,Email But i can not able to track user id.

The mapping information is stored in the fb_user table in the database.

I'm not aware of any API functions the module provides for querying this data but I wouldn't be surprised if something exists.

If all you are doing is authentication I'd have a look at FBOauth module instead, it provides a similar table and makes the whole process a lot easier.


Conditions for using mail.css with drupal_mail() Problem

I'm trying to style an email sent with drupal_mail. Sometimes it works, other times it doesn't and I can't work out why.

I'm running mail system, SMTP and mimemail:

Mail system sets up: SMTP for sending and mimemail for styling.

In the mimemail options include stylesheets is disabled because it's found mail.css in my theme. Mime mail CSS compressor is enabled because people use hotmail and gmail.

Condition 1

User uses form to send email, this works as expected I receive a styled email in gmail.

$message = drupal_mail('module_1', 'notify', $email, language_default(), $params);

function module_1_mail($key, &$message, $params) {
    $title = check_plain($_SESSION['title']);
    $message['headers']['MIME-Version'] = '1.0';
    $message['headers']['Content-Type'] = 'multipart/mixed; text/html; charset=UTF-8; format=flowed;';
    $message['subject'] = t('Email subject plus ').$title;

    $message['body'][] = "Body text goes here";
    $message['params']['attachments'] = $params;
  }

Condition 2

The user uses another form which schedules a rule action which sends an email some time later. This doesn't receive any styling despite seeming identical for all intents and purposes.

$message = drupal_mail('rules_module', 'notify', $user->mail, language_default(), $params);

function rules_module_mail($key, &$message, $params) {
    $message['headers']['MIME-Version'] = '1.0';
    $message['headers']['Content-Type'] = 'multipart/mixed; text/html; charset=UTF-8; format=flowed;';

    $message['subject'] = t('Here is a (@location)', array('@location' => $params['location']));
    $message['body'][] = 'This is some body text';
  }

Could rules somehow affect the calling of a stylesheet? Am I missing something obvious?

The problem in my case was that the email being sent wasn't using the drupal_mail function but php send mail.

I run msmtp on my server to route mail and so rather than passing through drupal, the email was being sent directly through my server with none of the styling.


How to do path aliases for views like news/%? Let's suppose we have a view like news/%.
Where news is my content type, and % is tid of term id from vocabulary "categories".

Obviously that urls like news/3, news/5 etc. works great. But how to do the path aliases for this kind of urls, generated from this view?

I want like this:

news/% -> company-news/[term:name]
Example: news/3 -> company-news/accidents

(where [term:name] transliterated term name from original title, because my site not on english language)

P.s. the just using pathauto for taxonomy terms, and the view "taxonomy/term/%" does not suit, because one term is used by multiple content types, and therefore in multiple views.

That is quite a tricky one.

Two possible solutions:

1)
Use page manager, create a context for each content type, and then use this module to generate the aliases): https://www.drupal.org/project/page_manager_pathauto (note: no Drupal 8 version)

2) Add/remove/modify the aliases yourself with an update hook.  So when a node is updated, you create/update/delete the corresponding path aliases.


How does Drupal handle non Drupal sub directories? I have a question about how Drupal handles requests made to subdirectories of the Drupal root that aren't under Drupal control.

What I mean is lets say I have a Site directory as such:

My main site
     -- an HTML flat site
     -- includes
     -- sites
     -- ... Other drupal necessary files

My concern is: does Drupal load bootstrap on every server request made to its directory? For example, I go straight to mysite/anhtmlflatsite - does Drupal do any type of loading? Or does it just let the web server serve up the sub directory no Drupal love added?

I ask because right now when accessing these flat sites I'm noticing that some files in my includes directory are getting hit (we have them push messages to the error log so that's how I know they're getting loaded when I access these flat sites). Also whenever the Drupal install breaks so do the paths to these flat HTML nothing to do with Drupal sites as well.

Curiouser and curiouser... Anyone have any insight to what's down the rabbit hole?

Oh and I'm using Drupal 7

The default .htaccess file has these lines in it:

# Pass all requests not referring directly to files in the filesystem to
# index.php. Clean URLs are handled in drupal_environment_initialize().
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !=/favicon.ico
RewriteRule ^ index.php [L]

So Drupal will only attempt to take control of a path if the file or directory doesn't already exist. All requests to your flat HTML site should be served without Drupal getting involved.

Maybe you've got some 404s in your flat HTML site? If they point to a folder underneath the web root that might explain why Drupal is getting hit.


"drush sapi-i" command which calls drush_backend_batch_process() fails with "Output is empty" I am trying to integrate ElasticSearch with Drupal and till now everything seems to be working except that the command drush sapi-i crashes with the output:

> 'C:/xampp/htdocs/my-project/docroot/vendor/bin/drush' is not recognized as an internal or external command,
> operable program or batch file.

In ProcessBase.php line 172:

  Output is empty.

search-api:index [--limit [LIMIT]] [--batch-size [BATCH-SIZE]] [-h|--help] [-q|--quiet] [-v|vv|vvv|--verbose] [-V|--version] [--ansi] [--no-ansi] [-n|--no-interaction] [-d|--debug] [-y|--yes] [--no] [--remote-host REMOTE-HOST] [--remote-user REMOTE-USER] [-r|--root ROOT] [-l|--uri URI] [--simulate] [--pipe] [-D|--define DEFINE] [--druplicon] [--notify [NOTIFY]] [--xh-link XH-LINK] [--] <command> [<indexId>]

After debugging with drush sapi-i -d it seems the call to drush_backend_batch_process() causes the issue for some reason.

After checking the vendor/bin directory I noticed that the drush script exists but drush.bat or drush.cmd were missing, I mean, for some reason even though I executed the drush sapi-i command using Git-bash, Drupal was still trying to access the Windows type of the file (which didn't exist in the source I copied from Mac).
so creating the below file manually fixed the issue.

drush.cmd file:

@echo off
setlocal DISABLEDELAYEDEXPANSION
php "%~dp0../drush/drush/drush" %*

drush file:

#!/usr/bin/env sh

dir=$(cd "${0%[/\\]*}" > /dev/null; cd '../drush/drush' && pwd)

if [ -d /proc/cygdrive ]; then
    case $(which php) in
        $(readlink -n /proc/cygdrive)/*)
            # We are in Cygwin using Windows php, so the path must be translated
            dir=$(cygpath -m "$dir");
            ;;
    esac
fi

"${dir}/drush" "$@"

Note that the drush script's line ending should be LF (instead of CRLF which drush.cmd needs),
so in Git-bash simply cd to where your script is and run sed -i 's/\r$//' my-script-filename (if your editor can only save with CRLF).


How to implement a horizontal set of translation links for every node? I want to add a hardcoded translation block to my page.tpl.php, to link to a translated version of every node + a translated interface.

The Language Switcher Dropdown module did the trick, but I want a horizontal set of links and need something simpler.

Maybe Displaying and configuring a drop down using Language Switcher Dropdown helps to achieve what you're trying to do with this module anyhow.

If not then the answers to the question about How to theme language translation links in Drupal? may help to actually answer your qestion. Though that question is for D6, and hence its answers might need some review to also make it work in D7. Here is the relevant part of it that might do the trick:

$node = menu_get_object();
if ($node->links) {
  print theme('links', $node->links);
  }


Google OAuth Login Solutions? Can anyone recommend a Google OAuth solution for D8?

I've done some looking, the only real viable solution that I can find is the OneAll Social Login module. This would potentially work for us, but we don't necessarily need something with 35+ login options. There seem to be other modules out there, but either seem to be confined to D6/D7 or have very low usage stats.

I'll explain what we are attempting to do. We have a dashboard that our customers login to, they can then launch into their various services from there. We'd just like to provide the option to login & associate a Google account with your existing D8 account to streamline the process.

EDIT: @drastik provided links to the Social API Stack module and it works without any issue. This is exactly what we wanted.

It looks like the Social API stack is the solution going forward in D8:
https://www.drupal.org/project/social_api
https://www.drupal.org/project/social_auth
https://www.drupal.org/project/social_auth_google

Good luck!


Get nid inside preprocess function My goal is to have an additional region class, when region is rendered on my page--node--9
I am using this template_preprocess_region() function to do this.

But how i can get inside my function ID of page, region is rendered on?

From another implementation of the same hook I found out that the node is actually available through the following. Try it out.

  $node = $variables['node'];

From there you can get node id.


Commerce checkout - Update cart pane after user select a shipping option (ajax) I am working on a one page checkout and I'm trying to get the cart review pane updated with a shipping price while user selects a shipping option.

I have attached #ajax information to the shipping options, to update the cart review form when a shipping option is saved.

Modifying the commerce shipping ajax callback on checkout

if($form_id == 'commerce_checkout_form_checkout') {
  $form['commerce_shipping']['shipping_service']['#ajax']['callback'] = 'mshop_shipping_pane_service_details_refresh';
}

Ajax callback

function mshop_shipping_pane_service_details_refresh($form, $form_state) {
  // Update shipping form
  $commands[] = ajax_command_replace('#' . $form['commerce_shipping']['service_details']['#id'], render($form['commerce_shipping']['service_details']));

  // Update checkout cart review
  list($view_id, $display_id) = explode('|', variable_get('commerce_cart_contents_pane_view', 'commerce_cart_summary|default'));
  $commands[] = ajax_command_replace('.view-mshop-cart-shopping-cart-summary', commerce_embed_view($view_id, $display_id, array(arg(1))));

  return array('#type' => 'ajax', '#commands' => $commands);
}

The issue :
The AJAX is working, the updated cart review view is updated, but the shipping option is not applied.

My guess is that, as the form is only updated and not submitted, the order is not saved. So as the cart review's view is based on the order, and the shipping option is not saved yet in the order, it does not display the right shipping information in the cart review.

Any workaround?

EDIT:

Thanks to milkovsky comment I have been able to save the order with the shipping rate applied to the order. Then the cart review view displays correctly with the updated cart rate applied.

/**
 * Ajax callback: Returns the shipping details form elements that match the
 * currently selected shipping service.
 */
function mshop_shipping_pane_service_details_refresh($form, &$form_state, $checkout_pane, $order) {

  // Get order from form
  list($order, $checkout_pane) = $form_state['build_info']['args'];

  // Load up to date order
  $order = commerce_order_load($order->order_id);

  // Get selected
  $service_name = $form['commerce_shipping']['shipping_service']['#default_value'];

  commerce_shipping_service_rate_order($service_name, $order);

  // Delete any existing shipping line items from the order.
  commerce_shipping_delete_shipping_line_items($order, TRUE);

  // Extract the unit price from the calculated rate.
  $rate_line_item = $order->shipping_rates[$service_name];
  $rate_line_item_wrapper = entity_metadata_wrapper('commerce_line_item', $rate_line_item);
  $unit_price = $rate_line_item_wrapper->commerce_unit_price->value();

  // Create a new shipping line item with the calculated rate from the form.
  $line_item = commerce_shipping_line_item_new($service_name, $unit_price, $order->order_id, $rate_line_item->data, $rate_line_item->type);

  // Save and add the line item to the order.
  $new_line_item = commerce_shipping_add_shipping_line_item($line_item, $order, TRUE);
  commerce_order_save($order);

  // Update shipping form
  $commands[] = ajax_command_replace('#' . $form['commerce_shipping']['service_details']['#id'], render($form['commerce_shipping']['service_details']));

  // Update checkout cart review
  list($view_id, $display_id) = explode('|', variable_get('commerce_cart_contents_pane_view', 'commerce_cart_summary|default'));
  $commands[] = ajax_command_replace('.view-mshop-cart-shopping-cart-summary', commerce_embed_view($view_id, $display_id, array($order->order_id)));

  $commands[] = ajax_command_after('.main form', theme('status_messages'));

  // $commands[] = ajax_command_after('.'.$form['#attributes']['class'][1].':eq(0)',theme('status_messages'));
  return array('#type' => 'ajax', '#commands' => $commands);
}

You are right. Shipping rates are applied only after you submit the form (Click "Next").

On submit all your shipping rules(or flat rates) applied and order is saved with new line items (Shipping is implemented via custom line item type).

The calculation is executed in the commerce_shipping_pane_checkout_form_submit()

So you can try to execute this function (or some parts of it) in the ajax callback before the cart is updated.

Here is an example how to apply shipping rates if you are using using Flat Rate Module:
Adding shipping to order programmatically via module.


Edit node link in view redirects to false URL I have a view with a list of nodes and their associated edit links. The nodes can be categorised/filtered so I use an argument* in the view that I set manually on the content template of the pages to display the view (different pages should show different sets) -- there is no correlation between this argument and the path to the pages containing the view. This works fine except that every edit link in the view redirects to a path that is a combination of the page's internal path and some string identifier that depends on the page being shown but isn't the page's title. On node/6 the link looks like edit?destination=nodeIdentifierF6. I've confirmed the number at the end corresponds to the node's ID and it is always preceeded by a capital F. My guess is that Identifier is really meant to be % and that Views substitutes some argument I'm not sure where comes from.

Is there a way to fix this, or a different approach altogether (e.g. using filters in a way that allows me to control the node sets dynamically), short of creating a whole template for this minor annoyance?

*Actually there are two arguments plus the three from the Views Or module, but I'm assuming it doesn't consume arguments, and the other argument has a default value and shouldn't be used. Using filters would be more appropriate, as users shouldn't have control over what set of nodes to display anyway, but I couldn't find a way to adjust filters dynamically, and the alternative seems to be to create n idental views but for this filter. I am mentioning this in case it's important.

22/9 Update:
This appears to be related to drupal_get_destination(), which returns an encoded path (/ => %2F). For the view in question the %2 part must then be interpreted as an argument placeholder and substituted. I am no closer to a solution to the problem, unfortunately.

I ended up including the node ID and generating the edit link myself, with the catch that I can't hide the field for underprivileged users because it can never be empty (just prints an empty string in that case). It's an acceptable solution but I'd prefer to se the built-in method.


A module to add a field for display as a column in the administration area I would like to display a column with the email address to the listing of users in my site's administration area. does anyone know of a module that does this?

You can't easily extend that list directly.

The easiest way is to replace the default user list using Views and probably VBO.

See also Creating a userlist in Views (including custom user fields).


Load jquery action on link menu click/node load So what I would like to do is great a sliding door effect for my drupal site using jquery-ui action. Does anyone know of examples or a module for this?

Also I would like the action to execute on two triggers.
            -open close sliding door on "menu link to new node click"
            -close sliding door once node is loaded

I've seen example for what I want to do and I know that you can insert jquery-ui. All I need to know is where do I need to insert the jqurey-ui. Examples would be great!

It depends on what page you need to add the script, adding jquery_ui is fairly straightforward if you know which component it is.

You should add the following line in the template.php (changing the ui.autocomplete to what you need)

drupal_add_library('system', 'ui.autocomplete');

The following page is extremely useful https://drupal.org/node/171213

Update as described in comments

function MY_THEME_preprocess_html(&$variables) {
    if(arg(0)=='node' && arg(1) === 3)) {
        $node = node_load(arg(1));
        drupal_add_js('system', 'ui.autocpmplete);}
       }
    }


How to exclude a node from being indexed based on a field value? I would like to exclude some nodes from being indexed based on one field value (not content-type) on a drupal 7 installation, I can't find a hook letting me doing it, please help ! thank you

As said in the API, using hook_search_api_index_items_alter is not the best choice.
You should use hook_search_api_alter_callback_info

Example :

function mymodule_search_api_alter_callback_info() {
  $callbacks['exclude_some_nodes'] = array(
    'name' => t('Exclude some nodes'),
    'description' => t('Exclude some nodes from being indexed based on one field value'),
    'class' => 'SearchApiExcludeSomeNodes',
  );
  return $callbacks;
}

class SearchApiExcludeSomeNodes extends SearchApiAbstractAlterCallback {

  public function supportsIndex(SearchApiIndex $index) {
    return $index->getEntityType() === 'node';
  }

  public function alterItems(array &$items) {
    foreach ($items as $k => $item) {
      if($item->field_your_field['und'][0]['value'] == 'do_not_index') {
        unset($items[$k]);
      }
    }
  }

}

This will appear as an option in the UI of Search API, in the Data alterations section (admin/config/search/search_api/index/your_index/workflow)


breadcrumbs not working as expected My menu looks like the following:

defs menu is linked to def view, fghs menu is linked to fgh view.

abcs | defs | fghs

Now when I click on defs, a view gets opened.
Now my breadcrumb is the following:

Home >> defs >> def

def is the view. In this view there is a link to another view. When I click on this view, the breadcrumb is the following:

Home >> fghs >> fgh

But I want the breadcrumb in this format:

Home >> defs >> def >> fgh

How can I achieve this? I am using Bartik theme.

In the page.tpl.php file, I am using the code below:

<?php if ($breadcrumb): ?>
      <?php print $breadcrumb ?><?php if ($title != ""): ?>
&raquo; <?php print $title ?>
<?php endif; ?>
<?php endif; ?>

I suggest you use Custom breadcrumbs module for defining overriding breadcrumbs: it supports Token, which helps defining complex breadcrumbs (e.g. defining breadcrumbs from related taxonomy terms, etc.).

With this module, you can define custom breadcrumbs for the following entities: node, path, term, Views, vocabulary (on admin/structure/custom_breadcrumbs).
On admin/config/user-interface/custom-breadcrumbs, you can also set to append current page title by default too.

Its admin interface is really simple.

In your case, you should go to admin/structure/custom_breadcrumbs/views/add, set things like this (it's just an example):

Save, then go to admin/config/user-interface/custom-breadcrumbs, and check "Append page title", hit "Save configuration", ready.


Unable To See Admin Dashboard, How to Manually change the admin theme I started developing a custom drupal theme from scratch(http://www.codexworld.com/create-drupal-custom-theme-from-scratch/).

In appearance menu below disabled themes, there was a drop-down menu for admin theme with theme names and a checkbox. As a curious person when I set admin theme to my custom theme(i am developing) I was unable to see Website pages & the Drupal admin dashboard because theme is empty/under developement. How to get back the default admin theme?

Edit: After Using acrosman's answer(adding $conf['theme_default'] = 'bartik'; in settings.php) i can see pages but still unable to see admin panel because I am using that incomplete theme as admin theme

How to Manually change the admin theme in Drupal 7?

What I Found: drupal is a popular website cms but you can't change the admin theme very easily if you chosen a wrong theme as admin theme by mistake.

This is the easiest method to reset your admin theme in a Cpanel.

Update your settings.php to have:

// If your admin theme is Bartik.
$conf['admin_theme'] = 'bartik';

Warning with using $conf as you cannot set the theme via Appearance page anymore.

If you prefer SQL query method...

Access PHPMyAdmin.
Select the Drupal database and run this query.

UPDATE variable SET value='s:7:"garland"' WHERE name = 'admin_theme';

Where 7 is the total number of strings your theme has. Example, if your theme is adminimal. Then your query should be like this.

UPDATE variable SET value='s:9:"adminimal"' WHERE name = 'admin_theme';

Please see the documentation on Drupal.org.

Take note that if you are using Context module the $conf is not helpful as it will always respect the theme assigned via Context.

Hope this helps.


optimal way to remove unwanted js and css files from page I use drupal 6 and ubercart2. Loading of cart and checkout page takes a while so I am thinking about removing any js and css files which are not used on specific pages.
What would be the ideal way to do it? I know about js agregation but want to try the first approach.
Thank you very much.

The AdvAgg module can do this fairly easily. Syntax for this is different between 6.x & 7.x. This is the hook syntax for 6.x. Works very similar to hook_css_alter() & hook_js_alter() in Drupal 7. Using these hooks is how to do it in D7 BTW.

hook_advagg_css_pre_alter(&$css, $preprocess_css, $public_downloads) {
  // Remove css files.
}
hook_advagg_js_pre_alter(&$js, $preprocess_js, $public_downloads) {
  // Remove js files.
}


Migrating to Pressflow I am currently using drupal 7 for my site. I recently read about Pressflow for drupal and it seems to provide better performance compared to the regular drupal 7 version. I have a quite a few custom modules and if I have to migrate to pressflow later, do I have to modify the modules to support pressflow? Also, are there are any issues on migrating from drupal 7 to pressflow?

Pressflow 7 doesn't seem to contain any relevant performance improvements at this time.

Below is a diff from 7.10 to the pressflow/master branch on github, where pressflow is now maintained. (https://github.com/pressflow/7)

$ git diff -R pressflow/master
diff --git b/includes/bootstrap.inc a/includes/bootstrap.inc
index d63a59b..e5e7ab7 100644
--- b/includes/bootstrap.inc
+++ a/includes/bootstrap.inc
@@ -728,6 +728,22 @@ function drupal_settings_initialize() {
   }
   $is_https = isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) == 'on';

+  // Load environmental config, if present.
+  if (isset($_SERVER['PRESSFLOW_SETTINGS'])) {
+    $pressflow_settings = json_decode($_SERVER['PRESSFLOW_SETTINGS'], TRUE);
+    foreach ($pressflow_settings as $key => $value) {
+      // One level of depth should be enough for $conf and $database.
+      if ($key == 'conf') {
+        foreach($value as $conf_key => $conf_value) {
+          $conf[$conf_key] = $conf_value;
+        }
+      }
+      else {
+        $$key = $value;
+      }
+    }
+  }
+
   if (isset($base_url)) {
     // Parse fixed base URL from settings.php.
     $parts = parse_url($base_url);
@@ -2329,6 +2345,17 @@ function _drupal_bootstrap_database() {
 function _drupal_bootstrap_variables() {
   global $conf;

+  // Pressflow Smart Start
+  if (!empty($GLOBALS['databases']) && variable_get('pressflow_smart_start', FALSE)) {
+    try {
+      $result = db_query('SELECT s.name FROM {system} s WHERE s.name = :name', array(':name' => 'system'));
+    } catch (Exception $e) {
+      // Redirect to the installer if an essential table is missing.
+      include_once DRUPAL_ROOT . '/includes/install.inc';
+      install_goto('install.php');
+    }
+  }
+
   // Initialize the lock system.
   require_once DRUPAL_ROOT . '/' . variable_get('lock_inc', 'includes/lock.inc');
   lock_initialize();
diff --git b/sites/default/default.settings.php a/sites/default/default.settings.php
index f8894aa..08fc81b 100644
--- b/sites/default/default.settings.php
+++ a/sites/default/default.settings.php
@@ -487,3 +487,13 @@ $conf['404_fast_html'] = '<html xmlns="http://www.w3.org/1999/xhtml"><head><titl
  * Remove the leading hash signs to disable.
  */
 # $conf['allow_authorize_operations'] = FALSE;
+
+/**
+ * Smart start:
+ *
+ * If you would prefer to be redirected to the installation system when a
+ * valid settings.php file is present but no tables are installed, remove
+ * the leading hash sign below.
+ */
+# $conf['pressflow_smart_start'] = TRUE;

As this shows, there are only two actual changes, one allows to set $conf values from the environment and the other is a safety check when Drupal isn't installed properly. Both are probably only really relevant for their Pantheon hosting environment.

So, while the interview posted by @wiim is nice, it's two years old and nothing has really happened. So, you can IMHO save yourself the hassle of switching for now (of course, this might change).


Bootstrap theme - add or remove classes in $navbar_classes I'm using the bootstrap theme, by default in page.tpl.php the nav bar is outputted like so:

<header id="navbar" role="banner" class="<?php print $navbar_classes; ?>">

Where can I edit the $navbar_classes variable called in the header tag so I can add or remove classes?

function YOURTHEME_preprocess_page(&$vars) {
      //add news class
      $vars['navbar_classes_array'][] = 'new-class';
      //remove class
      unset($vars['navbar_classes_array'][0]);
      // you need change value 0 to value you want remove class
      // Default
      // 0  'navbar', 1 => 'container', 2 => 'navbar-default'

}

You can do it with

Override file page.tpl.php. You can copy file page.tpl.php in bootstrap/theme/system/page.tpl.php to new your subtheme and edit it. It is right way.
Or you can use function hook_preprocess_page(). You can write code in file template.php of your subtheme. That way you don't need change file page.tpl.php


How to override theme_file_widget? Is there any method to override this function theme_file_widget.

I tried to to do the following in my module.

function mymodule_file_widget($variables)

and also in my theme

function mytheme_file_widget($variables)

but did not work. I cleared the cache also. Is there any method to override this function?

The correct way to override the theme function is:

/**
 * Implements hook_theme_registry_alter().
 */
function mymodule_theme_registry_alter(&$theme_registry) {
  $theme_registry['file_widget']['function'] = 'mymodule_file_widget';
}

function mymodule_file_widget($variables) {
 //your code
}


Restrict access for a specific forum to a specific user role I am using Drupal 8 and the core Forum module.

I have several forums on a site.

I wish to restrict access for some of the forums based on the role of the user.

eg:

Forum A: 'Moderator' and 'Role A' can access ('Role B cannot access')
Forum B: 'Moderator' and 'Role B' can access ('Role A cannot access')

I cannot seem to find a way to do this and am having trouble finding a straight answer about how to do it online.

Taxonomy Access Control Lite is a good module to achieve this.

  This node_access module governs access to nodes based on the taxonomy
  terms applied to the nodes. A simple scheme based on taxonomy, roles
  and users controls which content is visible.

  As the name implies, this module shares some functionality with an
  earlier module called Taxonomy Access Control (TAC). If you are
  shopping around for an access control module to use, consider that one
  as well. See this module's README.txt for an explanation of "why yet
  another access control module".

I have implemented one of my site for same purpose.

You can also go for

Content Access and ACL modules.

  This module allows you to manage permissions for content types by
  role and author. It allows you to specifiy custom view, edit and
  delete permissions for each content type. Optionally you can enable
  per content access settings, so you can customize the access for each
  content node.

One more Option Using Group module.

  The Group module allows you to create arbitrary collections of your
  content and users on your site and grant access control permissions on
  those collections

  Out of the box, Drupal only allows a person to view, create or edit
  the different content types you create. However, you might want to be
  able to let them view or edit all content types, but only in a
  specific section of the site.


How to set custom markers with Openlayers? I'm trying to set my Openlayers markers to custom icons. I have looked at the Openlayers Examples, and I have added a new style of type Icon and then I have added an assets folder inside the Openlayers module directory. I then have set the path to the marker in the style settings tab.

The problem is that no matter how I configure the path, the marker doesn't show up in the style preview or on my map.  I have tried the full site path for the marker, I have tried the path from the drupal root, and I have tried the path from the Openlayers module folder. None of these work.

As always, any advice is appreciated.

To "set custom markers" (as in your question title), you may also want to look at the IP Geolocation Views & Maps module. Partial quote from its project page (especially note the last paragraph of it):

Despite what the name may suggest, IP Geolocation Views & Maps (IPGV&M) is first and foremost a mapping engine.
The module makes it very easy to create Views-based mapping solutions using the map renderer of your choice (Google, OpenLayers or Leaflet) with any location storage module of your choice, e.g.:

Get Locations,
Geofield,
Geolocation Field
Location.

This allows you to bring together modules and feature sets that without IPGV&M you would not be able to combine.
Like beautiful animated marker clustering on Google or Bing or Mapbox ... any of various map providers.
But more importantly IPGV&M adds some features you won't find as conveniently packaged elsewhere.
These include marker differentiation based on field values or ranges (2nd screenshot) with or without font icons, various centering options, super-imposing the current visitor's location, allowing multiple content types to be displayed on the same map, full screen button and mini-map inset (bottom screenshot), polygon support (Geofield), marker tags and tool tips and cross-highlighting of associated content on the page when markers are hovered (and vice versa).

Head over to its (impressive) project page for even more information about it (it would be way too long to include a quote of it all here). That project page also includes various screenshots.


List of CCK fields under a group field For a section of our site, we need to show fields, even if they are empty. A helpful suggestion has been to edit content-field.tpl.php and remove the following part.

<?php if (!$field_empty) : ?>
<?php endif; ?>

But I don't want all empty fields to show up; only a handful that are under a Field Group in my custom content type should be shown.

I'm looking for a way of saying, "Show all fields under group X in content type Y."

Does such a thing exist?

CCK uses theme_fieldgroup_fieldset by default to render field groups. The single argument to that function usually contains all the fields that belong to that field group (apart from a rendered representation of those fields). So if you could override how to theme your specific field group, you would be done.

One way is to override this function in your theme: add a function foo_fieldgroup_fieldset to your theme (if your theme is called foo). Note that this function is then used for all field groups. The function would have to decide on its own whether to show or hide empty fields. See Overriding themable output for more details.

A different way would be to use a template file for rendering field groups. You would have to implement hook_theme for this to work (either in your theme or in a module). Advantage of this is, that preprocess functions are executed before rendering the field group. Preprocess functions allow you to add template suggestions, so you could have a custom template for one field group and a default one for others.

Also: have a look at the Theme developer module. It tells you for each item on a Drupal page which theme functions, templates and preprocess functions where involved in the rendering and how you could override the output.


How can I add a link on the "Structure" admin page? I created a view page with the path being /abc and I want to add this link on Administrative page with a link in Drupal 8.

You can go to /admin/structure/menu/manage/admin and add this link.


how to use a view to node field based on url I have a content type A which has a node reference to another node (type B). I want to create a block (using views) to display the content of that node reference in a side block on its respective node page (type B).

I think this might be possible with either contextual filters or relationships, but as I have never used either, I'm not sure exactly how to do this. If I could use these, I imagine that I could use the url as a filter.

I am assuming, you have a node of type A, that refers to a node of type B through a node referance field "field_noderef" attached to node A. You want to display the details of node A when you visit node B.

Create a block type view. Filter as content type = A
Create a contextual filter "field_noderef", set a default value of "get NID from URL".
Display the block in node page of content type B *this part is important.


How can I programmatically create a block type? I want to create a block type that has a couple of fields, a template and attached JavaScript.
I want that the user in my site will be able to create blocks of this type just like they create a custom block: through /block/add/myBlockType.
I would like ideally to have it all done programmatically but I dont mind manually creating my block type though "admin/structure/block/block-content/types" or with configuration files.
The thing is I have been scraping google for two days already and I don't manage to figure out how to programmatically create a block type
And this that the information is not easily found on Google makes me think that instead I need to create my type with configuration and then apply my plugin on creation of a new block but im still not sure how to do that and what my plugin needs to extend.
How can I do that?

I had the same issue and I hope I have resolved it.
Your algorithm is next:

Create your own module
Create file <your_module>.install
There must be at least one hook hook_install (I have used two: hook_install and hook_uninstall)
Inside install hook:

create a new block type
create fieldStorageConfig
create fieldConfig
set component for form and view display

My code:
<?php

use Drupal\block_content\Entity\BlockContentType;
use Drupal\field\Entity\FieldConfig;
use Drupal\field\Entity\FieldStorageConfig;

function <your_module_name>_install() {
  $newBlockType = BlockContentType::create([
    'id' => <your_id>,
    'label' => 'Custom block type',
    'description' => "A custom block type",
  ]);
  $newBlockType->save();

  $blockId = $newBlockType->id();

  block_content_add_field($blockId, 'Icon', 'custom_block_icon', 'image', 'image', 'image_image');
  block_content_add_field($blockId, 'Count', 'custom_block_count', 'integer', 'number_integer', 'number');
  block_content_add_field($blockId, 'Description', 'custom_block_description', 'text', 'text_default', 'text_textfield');

}
function block_content_add_field(
  $blockTypeId,
  $label,
  $componentName,
  $fieldStorageType,
  $viewDisplayType = 'text_default',
  $formDisplayType = 'text_textarea_with_summary') {
    // Add or remove the body field, as needed.
    $field = FieldConfig::loadByName('block_content', $blockTypeId, $componentName);
    if (empty($field)) {
      $fieldStorage = FieldStorageConfig::loadByName('block_content', $componentName);
      if (empty($fieldStorage)) {
        $fieldStorage = FieldStorageConfig::create([
          'field_name' => $componentName,
          'entity_type' => 'block_content',
          'type' => $fieldStorageType,
        ]);
        $fieldStorage->save();
      }

      $field = FieldConfig::create([
        'field_storage' => $fieldStorage,
        'bundle' => $blockTypeId,
        'label' => $label,
        'settings' => ['display_summary' => FALSE],
      ]);

      $field->save();

      /** @var \Drupal\Core\Entity\EntityDisplayRepositoryInterface $display_repository */
      $display_repository = \Drupal::service('entity_display.repository');

      // Assign widget settings for the default form mode.
      $display_repository->getFormDisplay('block_content', $blockTypeId)
        ->setComponent($componentName, [
          'type' => $formDisplayType,
        ])
        ->save();

      // Assign display settings for default view mode.
      $display_repository->getViewDisplay('block_content', $blockTypeId)
        ->setComponent($componentName, [
          'label' => 'hidden',
          'type' => $viewDisplayType,
        ])
        ->save();
    }

    return $field;
}

Result: the new custom block type with 3 fields.


How to set a POST data in value in FAPI I'm trying to port a working FAPI module from  D6 to D7.
I'm passing a POST value to the form and then assigning using :

 $link = check_url(substr($_POST['file_link'], 0, 300));
     $form['anu_download_file_link'] = array(
        '#type' => 'value',
        '#value' => $link,
      );

But when form is submitted the form is built again but this POST data file_link is missing in the submit handler.

In D6 $form['#cache']=true was working fine which avoided recreating of the form but now in D7 it does not seem to work.

How can pass POST values to the submit handler?

We need to use in D7 :

$form_state['cache'] = TRUE;
$form_state['no_cache'] = FALSE;

instead of

$form['$cache']=TRUE in D6


drupal_render() is deprecated. What replaces it? I have a render array and I want to convert it to HTML and place it in a WYSIWYG field. What is the generally accepted way to do that since drupal_render() is deprecated?

It was replaced with the renderer service.

$render_service = \Drupal::service('renderer');

As mpdonadio and 4k4 have pointed out in the comments, to prevent metadata from bubbling up to the main request, you should execute this in a new render context. You can do so by using the renderPlain method, rather than the usual render method (unless you're returning this from a controller, in which case use renderRoot instead).

$rendered = $render_service->renderPlain($build);


Theming a custom data table from php code text format with Drupal 7 I have a working block of php code that runs inside a Drupal 7 Page:

<?php
$my_database= array(
  'database' => 'mydb',
  'username' => 'xxxxxx', // assuming this is necessary
  'password' => 'xxxxxx', // assuming this is necessary
  'host' => 'localhost', // assumes localhost
  'driver' => 'mysql', // replace with your database driver
);
Database::addConnectionInfo('database_db', 'default', $my_database);
db_set_active('database_db');
$sql = "SELECT tcol1, tcol2 FROM mytable LIMIT 10";

$result = db_query($sql);
$header = array('Col1', 'Col2');
$rows = array();
if ($result) {
  while ($row = $result->fetchAssoc()) {
    $row= array($row['tcol1'],$row['tcol2']);
  $rows[] = $row;
  }
}
db_set_active();
print_r($rows);
$output= theme('table', $header, $rows);
?>

This piece of code works fine and print_r() prints all the data I asked for.
The odd thing is that the theming fails totally, showing nothing. I have done some experimentation:

    $output= theme('table', $header, $rows);
    echo theme('table', $header, $rows);
    print theme('table', $header, $rows);

but all of them fail, showing nothing or disrupting drupal globally.
How can I show my data in a nice table? I want to avoid writing html code and instead rely on Drupal theming.

The format of arguments to theme functions changed in Drupal 7, instead of

$output = theme('table', $header, $rows);

you need to use

$output = theme('table', array('header' => $header, 'rows' => $rows));

or, using a render array,

$build = array(
  '#theme' => 'table',
  '#header' => $header,
  '#rows' => $rows,
);
$output = drupal_render($build);


Call multiple node forms using multiform_get_form() I am trying to call multiple node forms using multiform_get_form() a utility function by multiform module.Here is the code I am trying with

function custom_multiform_menu() {
  $items = array();
  $items['add/multiform'] = array(
    'title' => 'Add Spread',
    'page callback' => 'multiform_get_form',
    'page arguments' => array(array('article_node_form'), array('page_node_form')),
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );
  return $items;
}

I am not seeing any node fields on page add/multiform

Use your own 'page callback', and in this callback call module_load_include('inc', 'node', 'node.pages'); which is required for node forms


How to set translated variables' values from settings.php (or similar) When using the Variable translation module (part of the Internationalization suite), how can I set the value of a translated variable from the  site's settings.php file ?

Using the $conf in the settings.php works, but off course it can only be used when the value of the variable is the same in all languages.

I'm looking for a solution that could be used to achieve the same goal of the $conf in the settings.php file: defining the values of variable at execution without the need store the values anywhere else. One use case is to assign different values to variables depending on the execution environment (as set in an environment variable).

In settings.php

$conf['MODULE_i18n_variables'] = array('my_variable');
$conf['my_variable'] = 'default value';
$conf['my_variable__fr'] = 'french value';

And in a custom module

/**
 * Implements hook_init().
 */
function MODULE_init() {
  global $conf, $language;
  if (is_array($conf['MODULE_i18n_variables'])) {
    foreach ($conf['MODULE_i18n_variables'] as $variable) {
      if (isset($conf["{$variable}__{$language->language}"])) {
        $conf[$variable] = $conf["{$variable}__{$language->language}"];
      }
    }
  }
}

This work as long as other languages values are not used. For instance, a multi-language aware edit form for the variable will not reflect the enforced per language values.


Custom REST POST resource to accept JSON I am trying to build simple search autocomplete POST endpoint, that accepts JSON and outputs JSON, but I am having problems getting Drupal 8 to just accept plain JSON.

Currently I am getting a 404 error for that endpoint, even though it is enabled in REST UI and I have permission. If I add serialization_class with value Drupal\node\Entity\Node to the class comment, I get 415 error, because it expects a node. Okay, great. How do I actually make it accept JSON? Do I really need to make an Entity type just for my autocomplete search?

Here is the code I have in mymodule/src/Plugin/rest/resource/SearchAutocompleteResource.php.

namespace Drupal\MyModule\Plugin\rest\resource;

use Drupal\rest\Plugin\ResourceBase;
use Drupal\rest\ResourceResponse;
use Drupal\node\Entity\Node;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

/**
 * Provides a resource for search autocomplete.
 *
 * @RestResource(
 *   id = "mymodule:searchautocomplete",
 *   label = @Translation("MyModule: Search Autocomplete"),
 *   uri_paths = {
 *     "canonical" = "/api/v1/search-autocomplete",
 *     "https://www.drupal.org/link-relations/create" = "/api/v1/search-autocomplete"
 *   }
 * )
 */
class SearchAutocompleteResource extends ResourceBase {

  public function post($search = null) {

    return new ResourceResponse(array(
      'example' => 'return value'
    ));

  }

}

Up until Make serialization_class optional (#2419825) issue has been fixed for 8.2.x branch you couldn't get away without creating a custom serialization class which merely passes the provided data to satisfy the requirement for mandatory serialization.

If you need to make it work on Drupal <= 8.1, try the following:

Create a custom normalizer.
Expose it to the system as a service.
Use it as serialization_class for your Rest resource.

modules/mymodule/src/normalizer/JsonDenormalizer.php:

<?php

namespace Drupal\mymodule\normalizer;

use Drupal\serialization\Normalizer\NormalizerBase;
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;

/**
 * Class JsonDenormalizer
 *
 * @todo Remove this class once https://www.drupal.org/node/2419825 is fixed.
 */
class JsonDenormalizer extends NormalizerBase implements DenormalizerInterface {

  /**
   * The interface or class that this Normalizer supports.
   *
   * @var array
   */
  protected $supportedInterfaceOrClass = array(__CLASS__);

  /**
   * {@inheritdoc}
   */
  public function normalize($object, $format = null, array $context = array()) {
    return parent::normalize($object, $format, $context);
  }

  /**
   * {@inheritdoc}
   */
  public function denormalize($data, $class, $format = NULL, array $context  = array()) {
    return $data;
  }
}

modules/mymodule/mymodule.services.yml:

services:
  # can be removed once https://www.drupal.org/node/2419825 is fixed.
  serializer.normalizer.mymodule.json:
    class: Drupal\mymodule\normalizer\JsonDenormalizer
    tags:
      - { name: normalizer }

mymodule/src/Plugin/rest/resource/SearchAutocompleteResource.php:

/**
 * Provides a resource for search autocomplete.
 *
 * @RestResource(
 *   id = "mymodule:searchautocomplete",
 *   label = @Translation("MyModule: Search Autocomplete"),
 *   serialization_class = "Drupal\mymodule\normalizer\JsonDenormalizer",
 *   uri_paths = {
 *     "canonical" = "/api/v1/search-autocomplete",
 *     "https://www.drupal.org/link-relations/create" = "/api/v1/search-autocomplete"
 *   }
 * )
 */


Autocomplete textfield I've noticed that the autocomplete textfield widget has not been ported to Drupal 7.
I'm looking for a way to provide user with suggestion for already submitted values, but I don't want to create a free-tagging vocabulary, since I don't want a page with all nodes with a particular value.
What can I do? Has this feature been ported to a separate module like Node Reference?
I've tried Autocomplete Deluxe module, but it works only with terms, not with textfields.

The References module provides autocomplete text fields for user and node references.


Getting fatal error in drupal when open the site I am working on a site in which it was perfectly, but now its given this error

  Fatal error: require_once(): Failed opening required
  '/var/www/.../includes/sites/all/modules/context/plugins/context_condition_sitewide.inc'
  (include_path='.:') in /var/www/.../includes/bootstrap.inc on line
  3139.

Here we can see the path is changed .../includes/sites/..... where as the "include" and "sites" are on root folder.

So please guide me that how to solve this issue.

Install Context module using drush en "context".

Your site is not get /context_condition_sitewide.inc file or you may be accidently delete this module without disabling it from module list. Try reinstalling this module again.


jquery media not show player I'm trying to use jQuery Media, but it's not working.
I am getting the following error in Firebug:

  "NetworkError: 404 Not Found - http://
  demo.dolphin-sch.ir/nagara/fa/sites/default/files/mediaplayer/player.swf?file=http://demo.dolphin-sch.ir/nagara/sites/default/files/audio/12.mp3"

You can see the error on my website:

  http://demo.dolphin-sch.ir/nagara/fa/content/abc

First I enable jQuery Media (version 6.x-1.4-beta1) and jQ (version 6.x-1.2) and then upload the JW FLV Player to sites/default/files/mediaplayer/player.swf.  Next I change my template.php and create a filefield_file.tpl.php file.  Lastly, I set a media class .field-field-flash-file a, .filefield-file-audio a but it's still not working.

Can anyone help?

The two locations specified for sites/default/files are different in your example:

First part: http://demo.dolphin-sch.ir/nagara/fa/sites/default/files/mediaplayer/player.swf?file=

Second part:  http://demo.dolphin-sch.ir/nagara/sites/default/files/audio/12.mp3

I'd check your paths are set correctly everywhere.

EDIT:

This link works fine:

http://demo.dolphin-sch.ir/nagara/sites/default/files/mediaplayer/player.swf?file=http://demo.dolphin-sch.ir/nagara/sites/default/files/audio/12.mp3


Custom Atom feeds using Views I'm wondering if there's a way to make a view render an Atom feed with custom fields, that would output something similar to this:

<?xml version="1.0" encoding="UTF-8"?>
<feed xmlns="http://www.w3.org/2005/Atom" ... xml:lang="en-US">
   <title type="text">my atom feed</title>
   <subtitle type="text">my atom feed subtitle</subtitle>
   <id>the feed's url</id>
   <rights type="text">some copyright</rights>
   <updated>2013-06-14T02:29:00Z</updated>
   <author>
      <name>me</name>
   </author>
   <generator>my feed generator</generator>
   <link rel="alternate" type="text/html" href="my site's url" />
   <link rel="self" href="the feed's url" />
   <my:field1>value1</my:field1>
   <entry type="my_type_1">
      <id>an article's url</id>
      <title type="html">article title</title>
      <summary type="html">article summary</summary>
      <published>2013-06-14T01:16:00Z</published>
      <updated>2013-06-14T01:47:40Z</updated>
      <author>
         <name>someone</name>
         <uri>the guy's bio page url</uri>
      </author>
      <content type="html">full body content in &lt;strong&gt;html&lt;/strong&gt;</content>
      <my:numeric_field>2</my:numeric_field>
      <my:yet_another_custom_field>hi there</my:yet_another_custom_field>
   </entry>
   <entry> ... </entry>
</feed>

The views_rss module can do stuff like this (in fact, I've already accomplished a lot using its hooks to define the fields, and field formatters to do stuff like <author><name>name taken from a user reference field in the node</name><uri>the user's url</uri></author>, but I can't find a similar module that provides the same functionality for Atom feeds.

Is there such a module out there? I've tried atom and views_atom without success. If not, how hard would it be to implement it? I guess this would involve making a "views plugin", with which I'm not really familiar.

You don't need a module to do that. You can use .tpl files to wrap rows in <entry> tags, fields in their tags and so on. It may be a bit less intuitive and more exhausting at first, but in the long run you will get exactly what you ask for, without compromises modules call for.


Running a custom query alongside Drupal Registration Query Good afternoon all.
I would like to implement a custom query during the registration process of my registration. I've taken a look around online and can't find the information anywhere, so if anybody knows where the registration query is ran, so that I can add another query to it that would be awesome. Thanks in advance.
EDIT
The Query that runs alongside will go into a seperate game database, so alongside of the standard query it will also run
This was my old query, so maybe it can help show what I'm trying to run.

  $server= "****";
    $user= "****";
    $pass= "****";
    $gamedb= "****";

$link = mysqli_connect("$server", "$user", "$pass", "$webdb") or die( "Error:" . mysqli_connect_error());
$username = mysqli_real_escape_string($link, (string) $_POST['username']);
$email = mysqli_real_escape_string($link, (string) $_POST['email']);
$password = sha1((string) $_POST['password']);
$query="INSERT INTO user (`username`, `email`, `password`, `permissions`)
VALUES ('$username', '$email', '$password', '1')";
mysqli_query($link, $query) or die ("Error:" . mysqli_errno($link));
mysqli_close($link);

The use of the hook_user_insert() it is call when the user is created. Here is an implementation example:

    function hook_user_insert(&$edit, $account, $category) {
      db_insert('mytable')
        ->fields(array(
        'myfield' => $edit['myfield'],
        'uid' => $account->uid,
      ))
        ->execute();
    }

Depending on your case you might want to check other hooks like:

hook_user_insert()

hook_user_presave()

hook_user_update()