Order relationship in RESTful I'm using https://www.drupal.org/project/restful module. I can sort base entity using annotation:

/**
 * Class Things__1_0
 * @package Drupal\restful_thing\Plugin\resource\node\thing
 *
 * @Resource(
 *   name = "things:1.0",
 *   resource = "things",
 *   label = "things",
 *   description = "Export the things with all authentication providers.",
 *   authenticationTypes = TRUE,
 *   authenticationOptional = TRUE,
 *   dataProvider = {
 *     "entityType": "node",
 *     "bundles": {
 *       "course"
 *     },
 *     "sort" = {
 *       "field_weight": "ASC"
 *     },
 *   },
 *   majorVersion = 1,
 *   minorVersion = 0
 * )
 */

But when it comes to relationship, the related data isn't ordered the way I need.

Inside public_fields():

$public_fields['modules'] = array(
  'property' => 'field_modules',
  'resource' => array(
    'name' => 'modules',
    'fullView' => TRUE,
    'majorVersion' => 1,
    'minorVersion' => 0,
    'dataProvider' => array( //here I'm trying to override dataProvider values
      'sort' => array(
        'field_weight' => 'ASC'
      )
    )
  )
);

Is there any way to sort related data?

---edit---

I've also placed "sort" inside the annotation of the modules plugin, but It doesn't have effect too.

I've resolved the sorting problem with sorting data inside the formatter. Here's my code in case someone had similar problems.

<?php

/**
 * @file
 * Contains \Drupal\restful\Plugin\formatter\OrderFormatter.
 */

namespace Drupal\my_module\Plugin\formatter;

use Drupal\restful\Plugin\formatter\FormatterJson;
use Drupal\restful\Plugin\formatter\FormatterInterface;

/**
 * Class OrderFormatter
 * @package Drupal\restful\Plugin\formatter
 *
 * @Formatter(
 *   id = "order_formatter",
 *   label = "ORDER FORMATTER",
 *   description = "Output filtered data",
 *   curie = {
 *     "name": "dis",
 *     "path": "doc/rels",
 *     "template": "/{rel}",
 *   },
 * )
 */
class OrderFormatter extends FormatterJson implements FormatterInterface {

  /**
   * Content Type
   *
   * @var string
   */
  protected $contentType = 'application/json+sort; charset=utf-8';

  /**
   * {@inheritdoc}
   */
  public function render(array $structured_data) {
    $i=0;
    foreach ($structured_data['data'] as $v) {

      $structured_data['data'][$i]['unsortedThings'] = $this->sortBy($structured_data['data'][$i]['unsortedThings']);
      $i++;
    }
    return drupal_json_encode($structured_data);
  }

  public function sortBy($arr) {
    $results = [];
    foreach ($arr as $k=>$v) {
      $results[$k] = $v['weight']; //this is my sorting field
    }
    asort($results, SORT_REGULAR);

    foreach (array_keys($results) as $key) {
      $results[$key] = $arr[$key];
    }
    $results = array_values($results);
    return $results;
  }

}

You run this formatter by adding header to your request: Accept: application/json+sort; charset=utf-8


Sort Node Queries by an entity reference field within a field collection item I am trying to fetch a list of nodes of a particular content type, alongside their field-collection items. The code below works perfectly for my use case.

    function report_cards_get_term_data($type, $term, $session, $student_id, $class){
    $resarr = array();
    $query = db_select('node', 'n');
    $query->join('field_data_field_term', 'ft', 'n.nid = ft.entity_id');
    $query->join('field_data_field_session', 'dfs', 'n.nid = dfs.entity_id');
    $query->join('field_data_field_admission_number', 'rn', 'n.nid = rn.entity_id');
    $query->join('field_data_field_result', 'fr', 'n.nid = fr.entity_id');
    $query->join('field_data_field_class', 'cg', 'n.nid = cg.entity_id');
    $query->join('field_data_field_subject', 'cfs', 'cfs.entity_id = fr.field_result_value');
    $query->join('field_data_field_exam_score', 'ces', 'ces.entity_id = fr.field_result_value');
    $query->join('field_data_field_first_ca', 'cfc', 'cfc.entity_id = fr.field_result_value');
    $query->join('field_data_field_second_ca', 'csc', 'csc.entity_id = fr.field_result_value');
    $query->fields('cfs');
    $query->condition('n.type', $type);
    $query->condition('field_term_value', array('1st Term', '2nd Term', '3rd Term'), 'IN');
    $query->condition('field_session_target_id', $session);
    $query->condition('field_class_target_id', $class);
    $query->condition('field_admission_number_target_id', $student_id);
    $query->addExpression('cfc.field_first_ca_value + csc.field_second_ca_value + ces.field_exam_score_value', 'total');
    //$query->orderBy('cfs.field_subject_target_id->weight', 'ASC');
    $report_card = $query->execute();
}

However, i need to sort the result alphabetically by the entity reference name (taxonomy term) called "Subject". The entity reference is a field within the field collections. I know i can use "$query->orderBy()" but i can't get it to work. That's why it was commented out in the given code above.
Thank you for your suggestions.

Solved it myself. I added one more join,

$query->join('taxonomy_term_data', 'fee', 'cfs.field_subject_target_id = fee.tid');

Then order by

$query->orderBy('fee.name', 'ASC');

Then the result was ordered alphabetically by the taxonomy name.


Have users answer a question before viewing content I did some research but cant seem to wrap my head around having the ability to do this.

I have a couple content types that are currently open to everyone but I would like to collect some information from anonymous users before showing them the content.

I am thinking in some way to utilize webforms in a block and have the questions show up there, what im not sure is how to hide or blur out the content that they are trying to view until they answer the form, as well as how to keep that content open until their next visit.

I am sure you have all seen websites/blogs that do this, to make you register for the site.

Any guidance to how to accomplish this would be very appreciated.

I'm not aware of a module that does this out of the box. But depending on your details there are a few ways to try to solve this problem.

One solution would be to create your form using Webform or Entity form (assuming your on Drupal 7 a contact form could be used in Drupal 8), place that form in a hidden block on the pages in question. On page load use JavaScript to put the form into a lightbox and set some kind of CSS effect over the rest of the page. When the user completes the form set a cookie so that on the next page load they aren't bothered by the popup. This is a common solution used by News papers trying to enable paywalls but it often means users can bypass the effect by disabling JS.


How to save file to different server? I want to specify a different file system remote server path. So that if I upload a file then this should be served from different remote server. I am using Drupal version 8.

You'll need a custom Stream Wrapper, which provides read/write operations to your remote file system (those docs are for Drupal 7, but the concept, if not implementation, is identical).

Fortunately, for Drupal 8 someone's written a stream_wrapper_example module, which contains a lot of boilerplate code for re-use.

There are also a bunch of existing community-supplied stream wrapper modules, a Google search like "drupal stream wrapper modules" will list them all for you. Obviously whether or you can re-use any of those depends on exactly what you mean by "remote", and how you're implementing the connection.


Pathauto url of term for node? With Pathauto, is it possible to use the url of a node's term as a token?

In case it makes a difference im using the Taxonomy Menu module aswell. Thanks

UPDATE - The taxonomy is hierarchical. So if I have:

Food/Pizza/Margareta

Then if a node is tagged with 'Margareta' I need the path to be:

Food/Pizza/Margareta/node

Taxonomy terms are attached to nodes using term reference fields in Drupal 7. As such, you have access to the term reference field just like any other in the list of replacement tokens.

Look for fields related to the node with a description of "Term reference field", e.g.

EDIT:

To address your edit, I know it looks ridiculous but something like this will probably work (using field_school as an example):

[node:field-school:vocabulary]/[node:field-school:parent:parent:name]/[node:field-school:parent:name]/[node:field-school:name]

Here's another screenshot showing the extra data available for term reference fields in pathauto:


How do I generate a list of "standard" clean URLs? Is there a way to generate a list of "standard" clean URLs, like /user/login, `/admin/content/comment', '/comment/NN' ? Perhaps for core modules, or for a specified set of modules?

Those are paths in Drupal lingo. Clean URLs come from a server configuration that rewrites the path query parameter away (e.g. http://example.com/?q=user/login vs http://example.com/user/login ).

To get at the heart of your question, registered paths can be found in the menu_router table of your Drupal installation. There is no one standard set of paths since any module can register a path. Thus, the "standard" result will vary based on what type of install you have (e.g. minimal vs standard vs contrib installation profile) plus other configurations.

For example, this code snippet will dump the list of paths that the 6 core modules are registering.

  $implementations = module_implements('menu');
  $core = array('field', 'field_sql_storage', 'filter', 'node', 'system', 'user');
  $paths = array();
  foreach($implementations as $implementation) {
    if(in_array($implementation, $core)) {
      $paths = array_merge(array_keys(call_user_func("${implementation}_menu")), $paths);
    }
  }
  var_dump($paths);

However, you'll find the node paths will vary across your installation based on the your defined node types (e.g. node/add/NODE_TYPE ).


How to create a "pay per node" "pay to publish" type flow in Commerce 2? I'm experimenting with Commerce 2 and Drupal 8.

I want to set up a flow where people can pay for a node-- use cases like classified ad listing (pay per post), event signup (pay to register), and so on.

Here's what I did so far.

Create a content type classified ad.
Create a product 1 month of ad exposure.
Add an entity reference field on classified ad with the default value set to 1 month of ad exposure.  Set the display widget for this field to rendered entity. Hide this field with field permissions. (This allows the user to create a classified ad node and then see an Add to cart button for the correct product after saving.)

So far, so good.  But, with this configuration, the order doesn't have any information about the original node (content type: classified ad).   I need to know which node the purchase/order was made for because I want to publish that node.

So, I changed the default order type: I added an entity reference to content of type classified ad. But how do I populate this entity reference field with the correct node?  Or is there a better way to link the node for which the product was purchased with the order?

You need to create an order and an order item yourself and then add those values, I assume you need to do this from the context of your node anyway and not use a standard "buy this product" form.

A snippet from a project:

$order_item_values = [
  'type' => 'order_item_type',
  'title' => 'label',
  'unit_price' => new Price(...),
  ...
];
$order_item = $this->entityTypeManager()->getStorage('commerce_order_item')->create($order_item_values);
$order_item->save();

$order_type = $this->orderTypeResolver->resolve($order_item);

$stores = $this->entityTypeManager()->getStorage('commerce_store')->loadMultiple();
$store = reset($stores);

// Create the new order.
/** @var \Drupal\commerce_order\Entity\OrderInterface $order */
$order = $this->entityTypeManager()->getStorage('commerce_order')->create([
  'type' => $order_type,
  'store_id' => $store->id(),
  'uid' => $this->currentUser()->id(),
  'cart' => FALSE,
]);

$order->addItem($order_item);
$order->save();

$this->cartSession->addCartId($order->id(), CartSessionInterface::COMPLETED);

return $this->redirect('commerce_checkout.form', ['commerce_order' => $order->id()]);

You don't even need to use products, you can define an order item that just has a price and reference to your node. But you can also use products to define e.g. the length/price.


How are the default search results are sorted on D7? I have a basic search configured on my site. I wanted to know how is the default search results are sorted in drupal, is it by the number of words found on the content or based on date the content is created or something else. I know it can be altered using custom modules. But I am curious to know how default on works.

Drupal's defaul search result is sorting on the basis of:

Number of comments
Keyword relevance
Content is sticky at top of lists
Content is promoted to the front page
Recently posted

Under Content Ranking configuration (admin/config/search/settings) you can setup the influence of the above factors while searching.

Thanks,
ARUN AK


How to suppress default HtmlException? I need to turn off 404 & related Exceptions. Need to handle it in custom way.

I've implemented an EventSubscriber with listener for kernel.exception event.

But $event->setException() cannot receive NULL.

Any ideas?

This is the correct approach. Don't do all the work yourself, extend  DefaultExceptionHtmlSubscriber for 403/404 or HttpExceptionSubscriberBase for general exceptions.

As example see this question for access denied: How can we catch the acces denied exception in drupal 8

The most important thing is to use a higher priority than the core event you want to override.


a href links not showing url aliases I am using redirect module with Drupal 8 latest version. It is working fine when we open any node in url, it converts node to the path alias. But issue is with a href links. When we hover on any "a" link it is showing the node number not the path alias set for that node. After click on it is displaying again path alias in the url bar.

How we can display the alias on hovering any "a" href link ?

You can try Linkit. This will allow you to select internal links inside CKEditor and will convert them to aliases.

  Linkit provides an easy interface for internal and external linking with wysiwyg editors by using an autocomplete field. Linkit has by default support for nodes, users, taxonomy terms, files, comments and basic support for all types of entities that defines a canonical link template.


hook_custom_theme() works except if a user submits a user form with mismatched passwords. Then they get served the admin theme Title basically. My hook_custom_theme() has been working for ages and I only just realised the admin theme is being served for an error when saving a user form ie. mismatched passwords.

A snippet from the top of my function:

function custom_theme_change_custom_theme() {
    global $top_bar_color;
    $top_bar_color = '#2b3643';
    if (strpos($_SERVER['HTTP_HOST'], 'example.com') !== false) {
        switch (returnRoleForTheme()) {
            case 'old': $th = 'theme_1'; $top_bar_color = '#2b3643'; break;
            case 'young': $th = 'theme_2'; $top_bar_color = '#6dad19'; break;
            case 'kid': $th = 'theme_3'; $top_bar_color = '#6dad19'; break;
        }
    }
    return $th;
}

Any ideas on how to force the theme like for every other part of the website? Why would this page in particular revert to Adminimal?

hook_custom_theme()'s documentation says :

  The return value of this hook will be used on all pages except those
  which have a valid per-page or per-section theme set via a theme
  callback function in hook_menu(); the themes on those pages can only
  be overridden using hook_menu_alter().

so i guess that what you need here is having your custom rules ina  helper function that you call both in hook_custom_theme() and the theme callback of the error page from hook_menu_alter()


How to display additional fields in user profile? I have added three fields to user profile (field_firstname, field_lastname, field_user_gender) and I want to display them on user profile page. Default render($user_profile) displays values of those fields continuously, for instance: JohnMalkovichMale

How I can do this right? And how I can get names of fields?

This is just a CSS issue. Use developer tools/firebug to determine the class/id of the element wrapping each field, and add a CSS rule such as the following to your theme:

.field-wrapper-1, .field-wrapper-2 { display: block; }


How to pass field data from custom node type to webform block? I'm using the Webform module's block on custom content type.

The webform has some text fields and I want to pass some data from my custom content type fields to webform fields.

I tried to add a default value by using tokens but it didn't work ([node:custom_content_type_custom_field] is shown on the available tokens but didn't work).

How can I pass field data from current (custom) node to webform block?

The only way to do this is using a hook_form_alter against the webform block. Webform is a great module overall but when you step outside of what it provides out of the box it gets complicated. The hook_form_alter will need to be set to only modify that form based on the form ID that gets created when the form is built.

The code will be similar to this:

/**
 * Implements hook_form_alter().
 */
function yourmodule_form_alter(&$form, $form_state, $form_id) {
  if ($form_id == 'webform_client_form_103') {
  // Do your mods.
  }
}

NOTE: 'webform_client_form_103' will be replaced with your form id.


Term reference on node edit to ALL vocabularies I have about ten vocabularies and my content will be tagged with mostly one term of ANY of them.

It would be fine to let the editor choose the vocabulary on node edit form.

Is there yet a module or patch for that situation?   It would be the core taxnonomy module, right?

A workaround would be to mount all the ten vocs into the "11th", the root one. (They have been created as mindmaps and splitted for sake of overview and because I want to use taxonomy menu and keep each one small)

The Vocabulary reference module might help you, but it doesn't even have a dev release.

A more involved solution would require adding a term reference field for each vocabulary, then placing a "controlling" list field on top of them, with an allowed value for each vocabulary.

You could then dynamically show and hide the right term reference field using the Conditional Fields module.

The module handles required fields, so you would be sure that one term is always selected.


How can a view page work with multiple word term name I have user views page with path /members/%.
(url as members/term-name).It shows if I use CONTEXTUAL FILTERS with term id but I need url with term name. Anyway , go back to story:
academician,math, math teacher, math students are terms.
It shows all members if path is members/math  or members/academician. No problem with one word term name.
But it doesn't show any member if url is members/math-teacher or members/math-student.
So it works with math terms but not with math teacher.What am I missing ?

In views, the multi-word term is a well-known active issue

issue #1027458: Allow to use multiple arguments with spaces
issue #1940206: term name contextual filter separator
issue #1977854: Transform dashes to spaces does not work still a problem

Solution 1:
You can use pathauto module to set up automatic aliases for your taxonomy terms.
Solution 2:
From views:

Choose "Specify validation criteria" in settings of Taxonomy Term Contextual filter.
Then Choose Taxonomy Term in Validator field.
Choose your Vocabulary.
Choose Term name converted to term ID in Filter Value Type Field.
Please see attached screenshots for solution 2:

Solution 3:
In views, you can create path aliases for term IDs by using view_alias module.


removing the link in the listings title I have removed the title node module element from my listings and replaced it with a text field.  The problem is that the text field still works as a link.  How do I get rid of the link?

Shawn.  OK, I had a content type of "listing." There is a "title" field which has the field type as "node module element" which is automatically created as a field by the view for this page.  This field, the title, links to a page displaying the full content.  I had to remove this automatic linking. I downloaded a couple of modules to hide the title, and created a new text field to replace the title field, strange enough, this was also converted into linkable text. I then edited "node.tpl.php" to remove the


Code for view, and module name in path besides node id I am using this snip Stefan Lehmann gave me here to have a different image based on node, problem is it works fine with the id, but a couple of the nodes are views, and one is contact, how do I declare those?

<?php
$node = menu_get_object();
$menu_image = 'arrow_home.png';
if (!empty($node)) {
  $images = array(2 => 'arrow_home.png', 3 => 'arrow_formazione.png', 4 => 'arrow_workshop.png', 5 => 'arrow_raccontabito.png');
  $menu_image = isset($images[$node->nid]) ? $images[$node->nid] : $menu_image;
}
?>

<img src="/sites/all/themes/business/images/fz/<?php print $menu_image; ?>" />

This is the structure:

example.com/node/2 <<< snip ok
example.com/node/3 <<< snip ok
example.com/node/4 <<< snip ok
example.com/node/gallery <<< view name/path - what code do I need
example.com/node/contact <<< contact module - what code do I need

Thank you

In that same block of code, can do an arg() check.

$node = menu_get_object();
$menu_image = 'arrow_home.png';
if (!empty($node)) {
  $images = array(2 => 'arrow_home.png', 3 => 'arrow_formazione.png', 4 => 'arrow_workshop.png', 5 => 'arrow_raccontabito.png');
  $menu_image = isset($images[$node->nid]) ? $images[$node->nid] : $menu_image;
}
if (arg(1) == 'gallery') {
  $menu_image = 'arrow_gallery.png';
}
elseif (arg(1) == 'contact') {
  $menu_image = 'arrow_contact.png';
}

Note: This will only work as long as the URL structure stays the same.

Also, this code depends on where you are preprocessing the image. If you are using template_preprocess_node() the above will not work because those two pages, even though they are located at the node path, are not nodes.


How to debug / log comments when developing a custom module to fire when cron is run I am about to develop a custom module that will hook into a hook that is triggered when cron runs. Since the module will be activated during a cron run, i am not sure how to go about giving myself feedback as I develop. If I was working with javascript I could use console.log(myvar) to log information about variables etc.

If I was developing a module that ran on a page I could use the devel module and use dpm() in my module code.

However since this module will run with cron, dpm() doesn't seem like the best way of doing this.

From searching around I see that watchdog('error title', 'error message'); could have been a good way of doing this in Drupal 6.

What is the Drupal 7 way of logging messages during custom module development?

The function watchdog is also available in Drupal 7

Here is an exemple of how you can use it in your case :

watchdog('MyModule', 'My message, this is my node title : %node_title', array('%node_title' => $node->title), WATCHDOG_INFO, NULL);

If you want to use a translated string you can do something like this :

watchdog('MyModule', t('My message, this is my node title : @node_title', array('@node_title' => $node->title)), array(), WATCHDOG_INFO, NULL);

If you need to print an array, you can try something like this :

watchdog('MyModule', '<pre>'. print_r($node, TRUE) .'</pre>', array(), WATCHDOG_INFO, NULL);

You can watch the log in Reports -> Recent log messages (admin/reports/dblog) if the core module "Database logging" is activated.

Once your module is stable, you can remove the watchdog line.


Trying to use variable to pass a view argument/parameter I'm currently in the middle of trying to figure out a way to pass the value from a variable to be used as parameter/argument for my drupal view.

I have a contextual filter that currently configured on my drupal view to output only nodes based on the taxonomy term/ID. Instead of explicitly manually setting the parameters below.

{{drupal_view('view_one', 'block_1', 212, 210)}}

Is there a way I could use a variable to pass the parameters to my drupal view

 % for tags in node.field_filter_tags %}

    {% set tagid = tags.entity.id %}

{% endfor %}

{{drupal_view('view_one', 'block_1', tagid)}}

I tried it but it seems to show duplicates.

the first you install module Twig Tweak

In file yourtheme.theme

/**
 * Implements hook_preprocess_HOOK()
 */
function yourtheme_preprocess_node(&$variables) {
  $terms=[];
  foreach($variables['node']->field_tags->getValue() as $term){
    $terms[] = $term['target_id'];
  }
  $variables['node_terms'] = implode(',',$terms);
}

In file node.html.twig

{{ drupal_view('custom_view','article_block',node_terms) }}

Config Views CONTEXTUAL FILTERS in your views


hook_menu to change menu button item by checking group membership I am using Organic Groups and I have used this post to override the roles and permissions of OG Groups.

I need a hook to alter a button on my main menu that changes depending on whether the user is a member of a group (has any role in that group) or isn't a member of a group (and therefore hasn't got a role associated with his username)

The default button that always shows is 'add' when a user is associated with a group that button needs to be changed to 'remove' - with the according URL

I have created the following using this Drupal page:

function my_module_menu() {

    $items['link'] = array(
        'title callback' => 'change_link',
        'title arguments' => array(1),
        'page callback' => 'go_to’,
        'page arguments' => array(1),
        'access callback' => 'user_is_logged_in',
        'menu_name' => 'main-menu',
        );

    return $items;
}
function change_link($gid) {
  if(og_is_member('node', $gid)) {
    return 'Remove';
  }
  else {
    return 'Add';
  }
}
function go_to($gid) {
  if(og_is_member('node', $gid)) {
    drupal_goto('www.mydomainurl.com/remove');
  }
  else {
    drupal_goto('www.mydomainurl.com/add');
  }
}

As well as fixing the above code - what does the array(1) do in page and title call back? --> I just copied them as is from the Drupal API page... (Does it look for the 'gid' in the last 2 functions?

UPDATE: (if any user of the site are part of any group - regardless of role -  they will see only the 'remove' button if they aren't part of any group they will see the 'add' button.)

Here is a sample code close enough to your question. It may need some modifications to its parts in order to meet your needs, but more or less you got the idea.

/**
 * Implements hook_menu_alter().
 */
function foo_menu_alter(&$items) {
  $items['alter/%gid/path']['access callback'] = 'og_user_role_callback';
  $items['alter/%gid/path']['access arguments'] = array(1);
}

/**
 * Determine if logged-in user has access to menu or not.
 */
function og_user_role_callback($gid) {

  // Get OG role of the user. Could be 'member', 'non-member' or 'Group administrator'.
  global $user;
  $group_type = 'node';
  $uid = $user->uid;
  $member = og_get_user_roles($group_type, $gid, $uid, $include = TRUE);

  switch ($member) {
    case 'member':
      return TRUE;
    case 'non-member':
      return FALSE;
    case 'Group administrator':
      return TRUE;
  }
}


Access webform select list key from within rules I have a webform that needs to be sent via rules. That's all fine but I don't seem to be able to access the data key for a select list in my webform.

I can get the value like this:

[data:location-value]

But I need to key not tha value.

I tried (as a guess)

[data:location-key]

But that doesn't work.

Any ideas?

I used a work-a-round for this by using the translate option in Drupal.

I've set up the key as a value and translated the key to the value that I wanted.

This was used for a custom field, but it worked fine for me.


How to add a class to menu items that are not expanded (or don't have children) in the navigation Twig template? How do you add a class to menu items that are not expanded (or don't have children)?

    {% for item in items %}
      {%
        set classes = [
          item.is_expanded ? 'menu-item--expanded dropdown panel simple-dropdown',
          item.is_collapsed ? 'collapsed',
          item.in_active_trail ? 'active',
        ]
      %}
      <li{{ item.attributes.addClass(classes) }}>
        {{ link(item.title, item.url) }}
        {% if item.below %}
          {{ menus.menu_links(item.below, attributes, menu_level + 1) }}
        {% endif %}
      </li>
    {% endfor %}

Edit: Can anyone point me into getting the answer provided, implemented in my example?

Since Twig builds out the menu recursively the only way (I've found) to do this is to first check if the current item has any active children, and add a class to it once that is determined. So, before the li is posted, check if it has any children. Something like:

{% for child in item.below %}
  {% set children = item.below ? '1': '0' %}

  {% if children %}
    {# the current item has expanded/active children #}
  {% else %}
    {# the current item has no children #}
    {% set classes = classes|merge(['no_active_children']) %}
  {% endif %}

  <li{{ item.attributes.addClass(classes) }}>{{ link(item.title, item.url) }}
    {% if item.below %}
        {{ menus.menu_links(item.below, attributes, menu_level + 1) }}
    {% endif %}
  </li>
{% endfor %}

Hope that helps.


How to test a code where the config is involved as parameter? I'm new to OOP concepts, also PHPUnit Testing is new for me. I want to get the configuration in my testcase.

XYZFormResult.php

namespace Drupal\xyz\XYZFormResult;

use Drupal\Core\Config\ConfigFactory;
use Drupal\webform\Entity\WebformSubmission;

/**
* Class XYZFormResult.
*
* @package Drupal\xyz\formgroup
*/
class XYZFormResult {

    /**
    * Defines the immutable configuration object.
    *
    * @var \Drupal\Core\Config\Config|\Drupal\Core\Config\ImmutableConfig
    */
    private $config;

    /**
    * XYZFormResult constructor.
    *
    * @param \Drupal\Core\Config\ConfigFactory $config
    *   Inject ConfigFactory.
    */
    public function __construct(ConfigFactory $config) {
        $this->config = $config->getEditable('xyz.settings');
    }
}

XYZFormTest.php

namespace Drupal\Tests\xyz\Unit\XYZFormTest;

//use Drupal\Core\Config\ConfigFactory;
use Drupal\Tests\UnitTestCase;
use Drupal\xyz\formgroup\FormsGroupResult;
use Drupal\xyz\formgroup\XYZFormResult;
use Drupal\webform\Entity\WebformSubmission;

/**
* @coversDefaultClass \Drupal\xyz\formgroup\FormsGroupResult
* @group xyz
*/
class XYZFormTest extends UnitTestCase {
    /**
    *
    * @var \Drupal\Core\Config\ConfigFactory|\PHPUnit_Framework_MockObject_MockBuilder
    */
    protected $config;

    public function testxyz() {
        $this->XYZresult = new XYZFormResult($config);
    }
}

When I execute this XYZFormTest testcase, I need to pass a parameter for XYZFormResult(), how to pass config parameter?

If I pass any string in XYZFormResult(), I'm getting error this error:

__construct() must be an instance of Drupal\Core\Config\ConfigFactory, string given error

On a unit test, you can use getConfigFactoryStub():

namespace Drupal\Tests\my_module\Unit;

use Drupal\Core\DependencyInjection\ContainerBuilder;
use Drupal\Tests\UnitTestCase;

class MyModuleTest extends UnitTestCase {
  public function setUp() {
    parent::setUp();

    $config_map = [
      'my_module.settings' => [
        'setting_1' => 'value_1',
      ],
    ];

    // Get a stub for the config.factory service.
    $this->my_config_factory = $this->getConfigFactoryStub($config_map);

    $container = new ContainerBuilder();
    // Set the config.factory in the container also.
    $container->set('config.factory', $this->my_config_factory);

    \Drupal::setContainer($container);
  }

  public function testSomething() {
    $obj = new Something($this->my_config_factory);
    // ... asserts, etc.
}
}


Cannot Disable User Programmatically With user_cancel() I want to disable user using user_cancel method.

//A function that disables a user.
function myid_admin_disable_user(){
    try{
        $edit = array(
            'user_cancel_notify' => true,
        );

        $method = 'user_cancel_block';
        //5 is the user id of the account I want to disable.
        user_cancel($edit, 5, $method);
        echo true;
    }catch(Exception $e){
        echo false;
    }
}

After running the function above, I can still use the account which is supposed to be disabled. Why? Whats wrong in my code above?

Per the docs in user_cancel():

  Since the user cancellation process needs to be run in a batch, either
  Form API will invoke it, or batch_process() needs to be invoked after
  calling this function and should define the path to redirect to.

You need to invoke the batch API in order to trigger the result.

// Set the notify and cancel type options.
user_cancel(array(
  'user_cancel_notify' => TRUE,
  'user_cancel_method' => 'user_cancel_delete',
), 5, 'user_cancel_delete');

// Invoke the Batch API, disable drupal_goto(), and execute.
$batch = &batch_get();
$batch['progressive'] = FALSE;
batch_process();


Duplicate webform data to second database? I want to duplicate the results from the webform module to a second database.

Is there a convenient way to do that, or will I need to manually write all the queries to store and retrieve data?

I wouldn't try to tackle this at the Drupal level to be honest, it'll be a lot more trouble than it's worth.

If it was me I'd just add a trigger on the webform table that runs a stored procedure to copy the data into the second database.

There might be something you can do with Replication, but I'm not sure if it's granular enough to go down to the table level.


Disable taxonomy pages Are there any way to disable the taxonomy pages? I saw a question that restricts access to them (Original question).

But I dont want the "access denied" message to be displayed, I want to remove the pages completely.

If you don't need taxonomy you can always just disable the module.

If you still need the functionality but don't want the display pages to exist I guess you could implement hook_menu_alter() to remove them from the registry:

function MYMODULE_menu_alter(&$items) {
  unset($items['taxonomy/term/%taxonomy_term']);
  unset($items['taxonomy/term/%taxonomy_term/view']);
  unset($items['taxonomy/term/%taxonomy_term/feed']); // If you want to hide the feed as well.
}

I'd do some thorough testing after doing that though, I'm not sure if it would have any knock-on effects. Also if you're using the default taxonomy View for your taxonomy pages you'll obviously need to disable that as well.


Configuration changes that will not import? I have some configuration that will not import. If I run drush config-import --preview I see the changes to be imported; I hit 'y' to import. When I run the same command, the changes are still there?

My guess is that when I run this command the config files should say to the database: 'hey, be like me'. Then when I run it again, Drupal should ask 'are the config files and database the same?' - they should be if they were synced - and Drupal should say 'cool, nothing to do, they match'. Right?

Am I missing something - if not, what can I do? Thanks.

$ drush config-import --preview
 Collection  Config                                            Operation
             core.entity_view_display.node.page.search_result  update
             core.entity_view_display.node.page.search_index   update
             core.entity_view_display.node.book.teaser         update
Import the listed configuration changes? (y/n): y
The configuration was imported successfully.                                                                                [success]
$ drush config-import --preview
 Collection  Config                                            Operation
             core.entity_view_display.node.page.search_result  update
             core.entity_view_display.node.page.search_index   update
             core.entity_view_display.node.book.teaser         update
Import the listed configuration changes? (y/n):

From what I can see this is a problem with how drush generates the temp files to compare against. It looks like drush is generating files with any comments removed as well as not adding qoutes around yaml strings that needs to be escaped.

+  # Set the node type to location
   type:
     plugin: default_value
     default_value: location
+  # set the location type to park
   field_location_type:
     plugin: default_value
     default_value:
       tid: 1
+  # Create the mappings from soap to drupal fields.
   title: abbreviatedName
   field_location_active_facilityid: ID
-  field_location_address/address_line1: address1
-  field_location_address/locality: city
-  field_location_address/administrative_area: state
-  field_location_address/postal_code: zipCode
-  field_location_address/country_code: country
-  field_location_parking_direction/format:
+  "field_location_address/address_line1": address1
+#  "field_location_address/address_line2": address2
+  "field_location_address/locality": city
+  "field_location_address/administrative_area": state
+  "field_location_address/postal_code": zipCode
+  "field_location_address/country_code": country
+#  "field_location_address/langcode":
+#    plugin: default_value
+#    default_value: en
+  "field_location_parking_direction/format":
     plugin: default_value
     default_value: basic_html
-  field_location_parking_direction/value: parkingCapacity
+  "field_location_parking_direction/value": parkingCapacity


Hierarchical Select reset when I click add another item I have a custom content type that has an unlimited field. This field is from field collection type and it contains a field that is from taxonomy type and with a hierarchical select widget. When I want add a node of that type and choose a value for hierarchical select field and then click add another item the value of the hierarchical select will reset. What is the problem?

Temporarily I fixed it by rearranging the hierarchical select field at top and add another item field(image field) at the bottom of that field.

You can rearrange the field under Mange Fields.


How can I show a date in Urdu? I am working on printing dates in more than a language. With Drupal 7, I used the following code.
<span class="arabic-date">
 <?php
   $arrayurdudays = array('', '', '', '', '', '', '', '');
   print format_date(time(), 'custom', ' l , d F , Y', null, 'ur');
 ?>
</span>

With Drupal 8 and Twig, I tried more than one way and it didn't work for me.
I downloaded the Configuration Translation module, but it didn't work in my case; I read there is a way to print it inside a file (.theme), but I didn't understand the method well. I need it inside the header file.

In a Twig template, you can use the format_date() filter. For example, in the node template, the following code could be used to show (using a custom format) when a node has been created. (The following code is a simplified version of the code used from the Unami theme used with the Unami Demo installation profile, in node.html.twig.)
{% set created_date = node.getCreatedTime|format_date('custom', 'l, d F, Y', null, 'ur') %}

{% if display_submitted %}

      {% trans %}by {{ author_name }} {{ created_date }}{% endtrans %}

{% endif %}

I would rather avoid passing a language code to format_date() to let the filter use the language set for the page. Setting the language code would make the template file always use that, even if the page is using a different language code.
{% set created_date = node.getCreatedTime|format_date('custom', 'l, d F, Y') %}

{% if display_submitted %}

      {% trans %}by {{ author_name }} {{ created_date }}{% endtrans %}

{% endif %}

Note that when the custom format is using M for the month, the month name could be not correctly translated. See Date formats with abbreviated month name (M) are not translated using context for more details.


Panels -> Add content in panels gives AJAX HTTP-error When I'm trying to add Content to a panel page (just installed Panels), I get this error message:

An AJAX HTTP error occurred.
HTTP Result Code: 400
Debugging information follows.
Path: /panels/ajax/editor/select-content/panel_context%3Apage-panel%3Apage_panel_panel_context/middle
StatusText: Bad Request
ResponseText:
Runtime Error
body {font-family:"Verdana";font-weight:normal;font-size: .7em;color:black;}
p {font-family:"Verdana";font-weight:normal;color:black;margin-top: -5px}
b {font-family:"Verdana";font-weight:bold;color:black;margin-top: -5px}
H1 { font-family:"Verdana";font-weight:normal;font-size:18pt;color:red }
H2 { font-family:"Verdana";font-weight:normal;font-size:14pt;color:maroon }
pre {font-family:"Lucida Console";font-size: .9em}
.marker {font-weight: bold; color: black;text-decoration: none;}
.version {color: gray;}
.error {margin-bottom: 10px;}
.expandable { text-decoration:underline; font-weight:bold; color:navy; cursor:hand; }
Server Error in '/' Application.
Runtime Error
Description: An application error occurred on the server. The current custom error settings for this application prevent the details of the application error from being viewed remotely (for security reasons). It could, however, be viewed by browsers running on the local server machine.
Details: To enable the details of this specific error message to be viewable on remote machines, please create a &lt;customErrors&gt; tag within a &quot;web.config&quot; configuration file located in the root directory of the current web application. This &lt;customErrors&gt; tag should then have its &quot;mode&quot; attribute set to &quot;Off&quot;.
&lt;!-- Web.Config Configuration File --&gt;
&lt;configuration&gt;
&lt;system.web&gt;
&lt;customErrors mode=&quot;Off&quot;/&gt;
&lt;/system.web&gt;
&lt;/configuration&gt;
Notes: The current error page you are seeing can be replaced by a custom error page by modifying the &quot;defaultRedirect&quot; attribute of the application&#39;s &lt;customErrors&gt; configuration tag to point to a custom error page URL.
&lt;!-- Web.Config Configuration File --&gt;
&lt;configuration&gt;
&lt;system.web&gt;
&lt;customErrors mode=&quot;RemoteOnly&quot; defaultRedirect=&quot;mycustompage.htm&quot;/&gt;
&lt;/system.web&gt;
&lt;/configuration&gt;

Someone who has a clue? What can it be?

This worked for me: https://drupal.org/node/1036202

Posted by Kye on February 11, 2013 at 11:45am
I had the same problem today. Went through this and similar threads. We were hosting the site in IIS and the problem turned out to be URLScan, and colon in the URL plan. I had to do is exclude the colon rule and everything worked as expected.

C:\Windows\system32\inetsrv\urlscan\UrlScan.ini

; : ; Don't allow alternate stream access


Facebook Album fetcher I am using facebook album fetcher module. It shows an error message

  An unknown error occurred while trying to fetch the album (empty reply).

Can anyone tell me how to resolve this issue.

The author of the module Facebook Album Fetcher has already posted a reply to a similar/identical problem that was posted in drupal.org. The general idea is that if you have followed the 10 steps that are described in the module page, you should log in to your facebook account and make sure that the album that you are trying to fetch is actually public.


Administrative form to create new entities of a custom entity type I have created a custom entity type NOTE: it is based on an existing database structure and so ECK is not (according to Programming Drupal 7 Entities p. 84) able to deal with exposing an "existing database table[s] to Drupal".

I now need to create pages for users to create/edit/delete these entities themselves.

Surely there is something out there that allows me to just say "This is the entity type, this is the entity id, load all the columns in the database as $form fields and take care of it for me"?

EntityForm seems to me to want to make forms that are themselves entities.

entity_ui_get_form() seems to me to be about getting fieldable entities, but I'm trying to get the values as one can get by doing this...

$entity = entity_load('custom_entity', array($id));

...

$wrapper = entity_metadata_wrapper('custom_entity', $entity);

If this isn't something that can be done with only a few lines of code, what is the best approach? I got lost walking through the hook_menu() callbacks for node/add.

Thanks

As far as I can see, the Entity Creation Kit module provides these create/edit/delete forms out-of-the-box. Although you should probably redefine your entities with help of that module.

Otherwise, you can perhaps take a look at the ECK module source code and use the relevant parts for your custom module.


sort specific field last modified date I have content type named recipe, Recipe have some fields like name, image, description. And also have a Boolean field name editors picks. I want to get last checked 3 posts of editors picks field in a view. or i want to limit this field can check only in 3 post. How can i do this. Please help me

I searched for SORT CRITERIA to sort by last modified date there is a field named "Content revision: Updated date". This field helped me to sort by modified date.

Credits: @ismini (for posting the comments that helped me).


Where in the table is it stored that /drupal/foo is actually /node/47 in order to mass query to remove /drupal and just leave the /foo part? /drupal is broken on all the websites, but I want to go into the database and mass query to remove the /drupal and just leave the /foo part.

The table you want is {url_alias}.  The {url_alias.source}column is the internal path (eg node/123), the {url_alias.alias} is the alias itself.

Mucking with the database directly isn't recommended, though.  Your best bet is to use Pathauto and Globalredirect.  The first will allow you to set up patterns, the second will redirect nodes to the alias.

You then use the Delete Aliases (admin/config/search/path/delete_bulk) link and then Bulk Update (admin/config/search/path/update_bulk) to make the new ones.

If you must do this manually, I suggest looking into the what the Path include provides as an API, and using that.

Also be sure that you don't actually have a problem with a $base_url being set incorrectly in your settings.php


Allow users to edit own unpublished content I would like to provide users with role-A and role-B the ability to edit their own published and unpublished content. I've installed the Content Access Module and seems impossible to make this without coding. Does anyone know how to solve with code?

I am not sure about your exact requirement. If you want to list all contents created by current user with an edit link, my suggestion to make try with views.

Give Edit Own Content permission to your needed roles for all content types in Home » Administration » People » Permissions.
Create a view with content of all.
Add title in fields (or the fields you want).
If you want to give an edit link , add Content:Edit Link.
In views contextual filter add Content:Author uid = User ID from logged in user (Refer here).
Change format to Table (Only title and edit link is there this gives a nice formatting).

Hope this will help you.


connect apache solr to a custom search function I am having some trouble with creating a search module (dictionary) that uses apache solr.
The current module is connected to a solr instance from a different source that has a indexation from a postgresql database with it's own schema.

Now I'm in the process migrating all the content to nodes in Drupal and so far so good.
The thing now is that I need to change the search request from the current solr to Drupal apachesolr with its standard schema. Problem is that I am relative new to how solr works, but I do understand the basic structure.

Anyone that might be able to give me a hand or point me to some kind of documentation to how to do this?

I tried to change the query search quartiles from what i could find in the schema . The only thing keep getting when i do a search is "Your search yielded no results"

Here is the cod in the callbacks.inc file unmodified

<?php

function ne_norstedts_page($types) {
  $ret = '';

  $form = drupal_get_form('ne_norstedts_search_form', $types);

  // Render search form.
  $ret .= '
';
  $ret .= render($form);
  $ret .= '
';

  // Get search results and output them
  isset($_GET) ? extract($_GET) : '';
  if (isset($q) && isset($from) && isset($to) && isset($type)) {
    $query = array(
      'q'  => $nq,
      'fq' => 'type:norstedts AND subtype:' . $from . '-' . $to . '-' . $type,
      'start' => isset($page) ? ($page) * 10 : 0,
    );

    $result = ne_api_get_api_fetch('/search', $query);

    $title = '';
    foreach ($types as $t => $name) {
      if ($t == $type) {
        $title = $name;
        break;
      }
    }

    $ret .= theme('ne_norstedts_results', array('result' => $result['result'], 'title' => $title));
  }

  return $ret;
}

/**
 * Gets text for a single word for ajax
 */
function ne_norstedts_ajax_load_word() {
  $url = isset($_GET['url']) ? $_GET['url'] : '';
  if ($url) {
    $result = ne_api_get_api_fetch($url);
    if (isset($result['text'])) {
      echo drupal_json_encode($result['text']);
    }
  }
  exit;
}

and here is my modified version of it

<?php

function ne_dictionary_page($types) {
  $ret = '';

  $form = drupal_get_form('ne_dictionary_search_form', $types);

  // Render search form.
  $ret .= '
';
  $ret .= render($form);
  $ret .= '
';

  // Get search results and output them
  isset($_GET) ? extract($_GET) : '';
  if (isset($q) && isset($from) && isset($to) && isset($type)) {
    $query = array(
      'q'  => $nq,
      'fq' => 'site:' . $from . '-' . $to,
      'start' => isset($page) ? ($page) * 10 : 0,
    );

    $result = apachesolr_search_search_page('/search', $query);

    $title = '';
    foreach ($types as $t => $name) {
      if ($t == $type) {
        $title = $name;
        break;
      }
    }

    $ret .= theme('ne_dictionary_results', array('result' => $result['result'], 'title' => $title));
  }

  return $ret;
}

/**
 * Gets text for a single word for ajax
 */
function ne_dictionary_ajax_load_word() {
  $url = isset($_GET['url']) ? $_GET['url'] : '';
  if ($url) {
    $result = apachesolr_search_search_page($url);
    if (isset($result['text'])) {
      echo drupal_json_encode($result['text']);
    }
  }
  exit;
}

You dont need a module for this. Activate your solr module, index your content and the core drupal search will be replaced by the solr search.
There is nothing else you need to do. From then on, every search you make using the domain.com/search/site url will be automatically directed to solr.

It is just a matter of setting the right options in the solr module.


Access Damp over LAN I have installed Drupal. I followed a tutorial in Lynda.com that uses Acquia Dev Desktop, and then the core Drupal inside. (http://www.lynda.com/tutorials/73655-2.html)

I'm not sure if it is the best way to install Drupal. Anyway, it works. But now I need to access to the web from another laptop that is in another room. I can't.

When I see the web in the original mac, I have: http://nameofproject:8082/

From a second mac, to access to the Drupal web installed, I tried and it doesn't work:

http://IPnumber:8082/(This drives me to the generic Acquia Drupal site)
http://IPnumber:8082/nameofproject
http://IPnumber/nameofproject:8082/
http://IPnumber/nameofproject/

If you have a web server installed on your local network, and you type the IP address in the URL (e.g. IPaddress:port/nameofproject), you should get your Drupal site.
The fact that when you just type the IP, and the port you get the default server page means that your router settings are already working.


New content doesn't appear in database I have the strangest thing going on here: I just created a new content type ('jobs'), and a new job (its node ID is 1706), but for some reasons there is no node that node ID in the database; even when I search for type = jobs, I get no result.

What could be the cause why I'm getting no results?

If the content was created it's also there in the database. Most obvious reason for you not finding it, would be silly mistakes, like a typo in the search, or you looked in the wrong database (either created the node the wrong place or looking in the wrong database).

It's not possible to have a node in a drupal site that doesn't exist in the database unless you believe in fairies ;)


field collection items are not in panels Im trying to use Panels to display a Field collection but it looks like it is not in the overlay (see screenshot). How can I display the field collection in my panels?

I think the method depends on what you are trying to achieve by doing this.

You could write a plugin for panels to make it recognise field collections.
It looks like Fieldable Panels Panes might help.
You could use mini-panels to wrap the fields (part of panels)
You could just put the fields up individually

Hope this helps, without your intended use-case in your question it is difficult to provide a meaningful answer.


How to add Table of Contents in a PDF? I am using the Drupal Print module to create downloadable PDF from my site. This works very well indeed. But I would like to have a table of contents in the left region of the downloaded PDF.

For example say, I have Introduction, Chapter2..., these things need to be displayed on the Left side region of my PDF. I had a look at the print module to see whether I can do this with configuration but it didn't work

Any help is appreciated.

Thanks in advavce.

It's not clear exactly what you are doing (eg are each of your chapters a node?) however you may be able to use the core book module for this. However it sounds like you are going to need something like Views PDF to get the formatting you need.


Building a view programmatically fails when filtering specific nids but not others I am quite stuck with this, so I hope you can help me out…

I have a view which filters (contextual filter) by 'nid'. I have two 'filter criteria's (view ui):

Published
Node type

I want to embed that view in a page programmatically through an Ajax call. I have discovered it sometimes returns the correct node and sometimes not. It depends on the specific node so for example it always retrieves the node nid = '4' and it never does for nid = '35'

Trying to figure out where the problem comes from I have tried few things. For example: I have tried to embed the view using panels, just for testing, using arguments for the contextual filter. It always work (always retrieve the correct node) this way. But when I call the view programmatically from a form building function (the one I use inside 'drupal_get_form()'), it just work with some nodes (some values of nid).

I am using devel for debugging and, when the view doesn't returns results,

$view->build_info['fail'] = TRUE

Here is the way I call the view:

$view = views_get_view('proyecto_en_arquitecto');
$view->init();
$view->set_display('block_1');
$view->set_arguments('35');
$view->execute();
dpm($view);  //Here is where I can see the building process fails

I am lost as I don't have a clue of why it just works with some nodes…

I hope you can point me to the right direction.

Thanks in advance for your help and let me know if you need further information.

The argument to the $views->set_arguments() function should be an array containing the arguments, even if only one, so, try:

$view->set_arguments(array(35));

or

$view->set_arguments(array($nid));

instead of passing the value in directly.

As to why it was working before sometimes, I am betting it was working with nids 1 thru 9 only, because there, for example, if $nid='4', $nid[0]=='4' is also true, but if $nid='35', $nid[0]=='35' is false (it is '3') but I leave this to another discussion, but look up "php strings as arrays" if you want to delve into it further.  This Strings as Arrays Q&A gives a brief description/introduction.


move $messages div to inside the form tag I would like to move the $messages div for any webform type away from a div but instead add it inside the  tag. I've started with THEME_preprocess_page(&$variables) in my template.php but I am stuck because the $variables doesnt set which element (or id/classes) the $messages should be placed in. Any suggestions/help would be appreciated. Thanks!

Copy your webform-form.tpl.php from the contrib webform module folder (under templates) to your themes templates folder and make the modifications there.

Default code:

if (isset($form['preview_message'])) {
  print '
';
  print drupal_render($form['preview_message']);
  print '
';
}


Profile fields export/import I have many user profile fields created at admin/config/people/accounts/fields in my drupal 7 local (offline) site. I would like to transfer all fields configuration to my online drupal site.
Is there any way to do this like views export/import feature? I don't want to re-create all fields in my online site.

The Features module can export content types, fields, views and allow you to import into another Drupal site.

The features module enables the capture and management of features in Drupal. A feature is a collection of Drupal entities which taken together satisfy a certain use-case.
Features provides a UI and API for taking different site building components from modules with exportables and bundling them together in a single feature module. A feature module is like any other Drupal module except that it declares its components (e.g. views, contexts, CCK fields, etc.) in its .info file so that it can be checked, updated, or reverted programmatically.


Multiple Submit in a Drupal Form I want a list of the input of my saved database table with buttons to delete or view the content and want to redirect it in the submit function.

With this code snipped i get only the submitted input value of the buttons, but every time is the $form_state['values'] array filled with the 1st form values. Is that the right way or need I another solution?

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

    global $user;
    $uid = $user->uid;
    $utime = $user->timezone;

    $query = db_select('mytable', 'm');
    $query->condition('m.uid', $uid, '=');
    $query->fields('m', array('fid', 'uid', 'name', 'created'));
    $query->range(0, 50);

    $results = $query->execute()->fetchAll();

    if($uid) {
        switch ($delta) {
            case 'myblock':
                $block['subject'] = '<none>';
                $block['content'] = _block_content($results);
            break;
        };
    };
    return $block;
}

function _block_content($items) {
    $output = array();

    foreach($items as $item => $item_value) {
        $output[$item] = drupal_get_form('mymodule_form', $item_value);
    };
    return $output;
}

function mymodule_form($form, &$form_state, $i) {

    global $user;
    $uid = $user->uid;
    $utime = $user->timezone;

        $form['value-'.$i->fid] = array( //EDIT
            '#type' => 'value',
            '#value' => $i->fid,
        );
        $form['view-'.$i->fid] = array ( //EDIT
            '#type' => 'submit',
            '#value' => t('view'),
            '#name' => 'view-'.$i->fid,
        );
        $form['delete-'.$i->fid] = array ( //EDIT
            '#type' => 'submit',
            '#value' => t('delete'),
            '#name' => 'delete-'.$i->fid,
        );

    return $form;
}

function mymodule_form_submit($form, &$form_state) {
   dpm($form_state);
   $form_state['rebuild'] = TRUE; //EDIT
}

The dpm output without 'form_build_id' 'form_token' 'form_id' in both,
1st example:

input =>
    view-3 => view
    value3 (NULL)

values =>
    value2
    view-2 => view
    delete-2 => delete

2nd example:

input =>
    view-3 => view
    value3 (NULL)

values =>
    value3
    view-3 => view
    delete-3 => delete

It should be because the way you're generating the form is wrong, form element should be as below:

<?php
function mymodule_form($form, &$form_state, $i) {
  $form['value_' . $i->fid] = array(
    '#type' => 'value',
    '#value' => $i->fid,
  );
  $form['view_' . $i->fid] = array (
    '#type' => 'submit',
    '#value' => t('view'),
    '#name' => 'view_' . $i->fid,
  );
  $form['delete_' . $i->fid] = array (
    '#type' => 'submit',
    '#value' => t('delete'),
    '#name' => 'delete_' . $i->fid,
  );

  return $form;
}
?>

Each element name in $form array should be unique. Check Drupal Form API reference guide for more details. The value, view and delete doesn't contain any form element data like #type, etc. Please check the value of $form_state['values']['op'] in your form submit handler to understand which one is called.


Change field input type on node edit form I'm looking to change the input field widget on my form, but still accept the same value at the end of it.

I have an integer field, and I only want them to be able to select certain integers which are relative to another field in the system. Normally I would just make an integer list field, and change the safe value to the words I want them to pick. eg:

1 | Red
2 | Blue
3 | Green

However the list is constantly growing so I couldn't manually set it. I've also tried using an Entity Reference field with an Entity Reference view for the values, but I've found that it creates an error when used in conjunction with a Field Collection field in the same node form, so I'm running out of ideas.

I've written some code to give me an array of the values, keyed by the integer number I want on a per node basis which is working, but what I want is to change the input widget from a textfield to a dropdown of my allowed values, but still accept the integer key value when it's submitted.

Try this in a custom module...

/**
 * Implements hook_form_FORM_ID_alter().
 */
function MODULE_NAME_form_YOUR_FORM_ID_alter(&$form, &$form_state) {

  // Replace the next 5 lines with your logic to set the array of values
  $options = array(
    1 => 'Red',
    2 => 'Blue',
    3 => 'Green',
  );

  $form['FORM_ELEMENT_ID']['#type'] = 'select';
  $form['FORM_ELEMENT_ID']['#options'] = $options;
}

Replace MODULE_NAME, YOUR_FORM_ID and FORM_ELEMENT_ID with your module name, form id and form element key respectively.


Programmatically update node image field (using URI of the image) and get URL in twig I am trying to update a node image field programmatically. I currently loading the node like this:

$node = Node::Load(1);

have the URI if the image that I want to set. I have tried this but no luck:

$node->set('field_image_head', array('#uri' => $imageUri));

How do I now update the node image with an image URI?
The twig will need to get the URL from the image field like so {{ file_url(node.field_image_head.entity.fileuri}}

You have to create a file for the image first before you can add it to the node.

use Drupal\node\Entity\Node;
use Drupal\file\Entity\File;

  $node = Node::load(1);
  $uri = 'public://image.jpg';

  // check first if the file exists for the uri
  $files = \Drupal::entityTypeManager()
    ->getStorage('file')
    ->loadByProperties(['uri' => $uri]);
  $file = reset($files);

  // if not create a file
  if (!$file) {
    $file = File::create([
      'uri' => $uri,
    ]);
    $file->save();
  }

  $node->field_image[] = [
    'target_id' => $file->id(),
    'alt' => 'Alt text',
    'title' => 'Title',
  ];

  $node->save();


Getting all nodes that have a specific term id using EntityFieldQuery I have been using the following line to get all the nodes with a term id

taxonomy_select_nodes($tid);

But now I want to sort the output by weight (field_audio_weight - field I created).
How can I achieve the same output using EntityFieldQuery ?

Something like:

$query = new EntityFieldQuery()
  ->entityCondition('entity_type', 'node')
  ->fieldCondition('field_taxonomy_reference', 'tid', TERM_ID)
  ->fieldOrderBy('field_audio_weight', 'value', 'DESC');

$results = $query->execute();

Check these articles for more information:

https://www.phase2technology.com/blog/entityfieldquery-let-drupal-do-the-heavy-lifting-pt-1/

https://www.phase2technology.com/blog/entityfieldquery-let-drupal-do-the-heavy-lifting-pt-2/


How do I copy a "purchase limit" field from a product to a product line item I am working with Drupal Commerce and am trying to copy a field on the product named "copy limit" to the line item when it's added to the cart so that I can access it in shopping cart form view when a user views his/her cart.

I am not sure of the best way to go about this.

I am using Commerce 7.x-1.0 and Drupal 7.7.

You'll need to add a "copy limit" field to the line item first. If you just want to use the standard "product" line item that will work. Add a "copy limit" field at admin/commerce/config/line-items/product/fields

Then you need a rule that says:

Event: "After adding a product to the cart"

Condition: Entity has field: Entity:commerce_product, Field: field_copy_limit
Condition: Entity has field: Entity: commerce_line_item, Field: field_copy_limit

Action: Set a data value. Data: commerce-line-item:field-copy-limit, Value: commerce-product:field-copy-limit

You may then want to add the copy limit to your cart view.

However, If you really want to just validate that the amount in the cart is less than or equal to the copy limit, you may want to do something like this:

Set up as above. The display settings on your product display node add to cart field must be set to "combine like products"
Add a rule like this:

Events:
* After adding a product to the cart
* After saving a new commerce line item
* After updating an existing commerce line item

Conditions:
* Entity has field: Parameter: Entity: [commerce-line-item], Field: commerce_product
* Entity has field: Parameter: Entity: [commerce-line-item..., Field: field_copy_limit
* Data comparison: Parameter: Data to compare: [commerce-line-item:quantity], Operator: is greater than, Data value: [commerce-line-item:commerce-product:field-copy-limit]

Actions:
*  Set a data value: Parameter: Data: [commerce-line-item:quantity], Value: [commerce-line-item:commerce-product:field-copy-limit]
* Show a message on the site: Parameter: Message: No more than [commerce-line-item:quantity] "[commerce-line-item:line-item-label]" may be ordered, so your order has been set to [commerce-line-item:quantity] items.

I put an export of this last rule at http://dl.dropbox.com/u/7350603/stackexchange/commerce_limit_items_in_cart.txt


How do I check Organic Groups group permissions from a custom module? I'm trying to show or hide a button based on if a user has permission to post content to a group or not, but I don't seem to be able to call the og_user_access function from my custom module.

I've tried calling it directly while loading the module file:

module_load_include('module', 'og');
$allowed = og_user_access('group', $group->nid, 'create resource content');

Doing this crashes the page with no Apache error just a watchdog error of:

  Error: Class name must be a valid object or a string in entity_get_controller() (line 8066 of /data/home/rsdev/www/content/lnsres.rsdev.ca/web/includes/common.inc).

I've also tried using module_invoke like so:

$allowed = module_invoke('og', 'og_user_access', 'group', $group->nid, 'create resource content');

Calling the module like this doesn't crash the page, but it also doesn't return anything and if I add some dpm() calls in the contrib module function I notice it's not even being called. Doing some reading about module_invoke appears like it's mostly used to call hooks, which I don't think og_user_access is, so I'm not sure if that's even the correct path to take.

How should I check group permissions in OG from my custom module's code ?

EDIT: This is not a duplicate of Display data basing on the group permission
because I'm not trying to use a permission I created. Also the only answer in that question doesn't work for me because as I explained, I can't call og_user_access without an error.

if your group entity is a node which I'm guessing it should be change your code to:

$gid // your group's node id.
$allowed = og_user_access('node', $gid, 'create resource content');


$language variable causes a lot of notices as non-object I get a lot of notices on my site.

f.e.
Notice: Trying to get property of non-object in drupal_lookup_path() (line 77 of /home/srv/www/mysite/includes/path.inc).

Notice: Trying to get property of non-object in template_preprocess_html() (line 2497 of /home/srv/www/mysite/includes/theme.inc).

and many other.
And also warning:
Warning: Attempt to assign property of non-object in template_preprocess_html() (line 2497 of /home/srv/www/mysite/includes/theme.inc).

I don't know how to fix this. Thanks to all for help.

For your issues you can refer

these links have given some patch for these notices

https://www.drupal.org/node/1907684
https://www.drupal.org/node/1104822
https://www.drupal.org/node/1853170


Run JavaScript after Ajax Call I have a form file:

namespace Drupal\h_scheduler\Form;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use \Drupal\node\Entity\Node;

class DayAddEntries extends FormBase {

  public counter = 0;

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'hs_day_add_form';
  }

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

    $form_state->setCached(FALSE);

    $form['#attached']['library'][] = 'h_scheduler/form_actions';

    /*...More fields....*/

    /* Special */
    $form['specials'] = array(
      '#type' => 'fieldset',
      '#tree' => TRUE,
      '#title' => t('Specials'),
      '#prefix' => '
',
      '#suffix' => '
',
    );

    if ($this->counter) {
      for ($i = 1; $i <= $this->counter; $i++) {
        $form['specials']['special'.$i] = array(
          '#type' => 'fieldset',
          '#title' => t('Special ') . $i,
          '#tree' => TRUE,
        );
        $form['specials']['special'.$i]['field'] = array(
          '#type' => 'number',
          '#title' => t('Every'),
          '#title_display' => 'before',
        );
        $form['specials']['special'.$i]['field'] = array(
          '#type' => 'textfield',
          '#title' => t('Prefix'),
          '#title_display' => 'after',
        );
      }
    }
    $form['specials']['operations']['#type'] = 'actions';
    $form['specials']['operations']['add_special'] = array(
      '#type' => 'button',
      '#value' => $this->t('Add special'),
      '#ajax' => array(
        'callback' => '::ajaxAddSpecial',
        'wrapper' => 'specials',
      ),
    );

    /* Not working */
    $form['specials']['operations']['remove_special'] = array(
      '#type' => 'button',
      '#value' => $this->t('Remove special'),
      '#ajax' => array(
        'callback' => '::ajaxRemoveSpecial',
        'wrapper' => 'specials',
      ),
    );

    /* Submit */
    $form['actions']['#type'] = 'actions';
    $form['actions']['submit'] = array(
      '#type' => 'submit',
      '#value' => $this->t('Save'),
      '#button_type' => 'primary',
    );

    $this->counter++;

    return $form;
  }

  /**
   * Increments the number of specials to have
   */
  public function ajaxAddSpecial($form, FormStateInterface $form_state) {
    return $form['specials'];
  }

  /**
   * Decrements the number of specials to have
   */
  public function ajaxRemoveSpecial($form, $form_state) {
    $this->counter -= 2;
    return $form['specials'];
  }

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

    /* Do stuff */

  }
}

jQuery:

jQuery(function($) {
  $('#edit-specials .fieldset-wrapper .fieldset-wrapper, #edit-regular .fieldset-wrapper').addClass('entry-wrapper').each(addStyleClasses);

  function addStyleClasses() {
    console.log('hi');
    $(this).children('.form-item')
      .addClass(function() {
        var regex = /form-item-\S+-(\S+)/;
        return regex.exec($(this).attr('class'))[1];
      })
      .not('.every').wrapAll('
');
  }

});

I'm able to add a new "special" item, but when I do it appears wacky.

This is because I've styled the form using a jQuery function that adds classes and wraps elements. However, that function does not run when the form['specials'] is rebuilt.

My question, how do I run a JS function after an ajax call?

This has a solution on Stackexchange here already, but:

This would be your full javascript file:

(function ($, Drupal) {
  Drupal.behaviors.myModuleName = {
    attach: function (context, settings) {
      // I am doing a find() but you can do a once() or whatever you like :-)
      $('#element', context).find('.sub-element').each(function () {
        // Do your thing here
      });
    }
  };
})(jQuery, Drupal);

Note on the question's js: I would say when calling a function like your addStyleClasses() it would be more reliable to explicitly pass your target element in the function call than using $(this) in there.


Why some twig templates have no file name suggestions I have enabled twig debug. The following source snippet shows that there are some templates has no any suggestions such as views-view.html.twig:

Latest Articles

The question is: why those templates has no suggestions like others? Is there any way to have suggestions for them or even any way to replace them with another templates files for specified place such as, hypothesis name of course,  node--article--teaser--view-views

You can use the theme hook given to create your own theme hook / template suggestions or see additional suggestions that are not showing up in Twig debug, this happens occasionally. (I wonder if this is a bug?)

For example, the theme hook here you are targeting is views_view.

If I do:

function MYTHEME_theme_suggestions_views_view_alter(&$suggestions, $vars, $hook) {
  kint($vars);
}

... If the name of my view is "News" and it's a page display, I see in the theme area printed out in kint:

views_view__news__page_1
views_view__page_1
views_view__news__page
views_view__page
views_view__news

You can take any of these and replace the udnerscores with dashes and then add .html.twig and you should be good to go.

e.g. views-view--news--page-1.html.twig

Resources:

function hook_theme_suggestions_HOOK_alter
Drupal 8 Theming Tutorial: How to Craft Custom Theme Hook Suggestions and Templates


Unable to go to administration pages (access denied) It seems I have some problems to access some functions. When I try to run my website
I have these errors:

  warning: call_user_func_array() expects parameter 1 to be a valid callback, function 'views_access' not found or invalid function name in D:\SVN\lancaster\Dev\drupal\includes\menu.inc on line 452.
warning: call_user_func_array() expects parameter 1 to be a valid callback, function 'views_access' not found or invalid function name in D:\SVN\lancaster\Dev\drupal\includes\menu.inc on line 452.
warning: call_user_func_array() expects parameter 1 to be a valid callback, function 'views_access' not found or invalid function name in D:\SVN\lancaster\Dev\drupal\includes\menu.inc on line 452.
warning: call_user_func_array() expects parameter 1 to be a valid callback, function 'views_access' not found or invalid function name in D:\SVN\lancaster\Dev\drupal\includes\menu.inc on line 452.
warning: call_user_func_array() expects parameter 1 to be a valid callback, function 'views_access' not found or invalid function name in D:\SVN\lancaster\Dev\drupal\includes\menu.inc on line 452.
warning: call_user_func_array() expects parameter 1 to be a valid callback, function 'nodereference_autocomplete_access' not found or invalid function name in D:\SVN\lancaster\Dev\drupal\includes\menu.inc on line 452.
warning: call_user_func_array() expects parameter 1 to be a valid callback, function 'views_access' not found or invalid function name in D:\SVN\lancaster\Dev\drupal\includes\menu.inc on line 452.
warning: call_user_func_array() expects parameter 1 to be a valid callback, function 'views_access' not found or invalid function name in D:\SVN\lancaster\Dev\drupal\includes\menu.inc on line 452.
warning: call_user_func_array() expects parameter 1 to be a valid callback, function 'views_access' not found or invalid function name in D:\SVN\lancaster\Dev\drupal\includes\menu.inc on line 452.
warning: call_user_func_array() expects parameter 1 to be a valid callback, function 'views_access' not found or invalid function name in D:\SVN\lancaster\Dev\drupal\includes\menu.inc on line 452.
You are not authorized to access this page.

I tried to check if all my modules were enabled, but I can't log in as administrator in my site too. When I do it, I get the following error:

  Forbidden
  You don't have permission to access / on this server.

I recommend you to do the following:

backup your database
truncate drupal cache tables using phpmyadmin ui or from mysql command line
truncate role_permission table using phpmyadmin ui or from the mysql command line
try to login using super administrator, the user with id 1
if nothing change with you, try to install another drupal project and see if you get the same error messages; maybe you have an issue with your php version or configuration.


How to use tokens in php code of the rules module? I'm using Ajax_comments to add comments on nodes without having to reload the page on save. Now the "node history" doesn't get updated which throws off the "new comment" count.

I tried to create a rule to update the node history on "comment save". Seems like my only option is to execute PHP code. How do I combine PHP code with tokens to get something like this:

if ([current-user:uid]) {
   db_merge('history')
     ->key(array(
       'uid' => [current-user:uid],
       'nid' => [comment:node:nid],
     ))
     ->fields(array('timestamp' => [site:current-date]))
     ->execute();
  }

It turns out that the above code works when I turn of the Ajax Comments module. With that module, it throws an internal server error.

I reported it as issue.

This hook does the job now:

function hook_comment_insert($comment) {
  //dpm($comment);

  if ($comment->uid) {
   db_merge('history')
     ->key(array(
       'uid' => $comment->uid,
       'nid' => $comment->nid,
     ))
     ->fields(array('timestamp' => REQUEST_TIME))
     ->execute();
  }
}


Adding extra attributes to webform input element I am looking to run javascript for a textbox on a webform. I am looking to add an extra attribute to my webform, but I am not sure how the webform is rendered . I was able to do that for my cck form using hook form alter but unable to do that for a webform.

Simply I have

<input type="text" maxlength="128" name="submitted[school_name_cancer]" id="edit-submitted-school-name-cancer" size="32" value="" class="form-text required" />

But I would like

<input type="text" maxlength="128" name="submitted[school_name_cancer]" id="edit-submitted-school-name-cancer" onkeyup="lookup(this.value);'" size="32" value="" class="form-text required" />

Thanks.

see this Form API Quickstart Guide http://drupal.org/node/751826 to review how to build forms, know how a form is builded:

  The Drupal Form API provides sophisticated form techniques and also
  allows for almost unlimited possibilities for custom theming,
  validation, and execution of forms. Even better, ANY form (even those
  in core) can be altered in almost any way imaginable--elements can be
  removed, added, and rearranged.

if your javascript is for validate fields of your form, I guess that this answer (related with validations of fields) could be useful How do I create custom content types in drupal?


Understanding `file_usage` table I am trying to understand the Drupal database schema because I need to access the database via MySQL by another system and I do not have access to the original Drupal developer of the site nor do I know Drupal well at this point (I did work with it 8 years ago) and it will be much easier to access with MySQL than to set up a server to have to host a PHP-based API or similar.

file_usage

In the file_usage table there are two (2) field module and type and using a GROUP BY query this is what I get:

module | type
-------|-------
 file  | node
 imce  | file
 user  | user

So it is pretty obvious that module means that entry was added by either the file, imce or user modules, right?

My questions are:

What does node, file and user mean in this context?
Is file/node effectively the same as imce/file, or is it
something different?
Does user/user mean it is a file associated with the user?
Further file_usage has an id column; can I assume:

That nid for file/node and imce/file?
And uid is for user/user?
Or something else?

NOTE: I do not have access to the working Drupal system, I only have access to the database.

So it is pretty obvious that module means that entry was added by either the file, imce or user modules, right?

Right, it's just the name of the module that added the record.

  What does node, file and user mean in this context?

They're arbitrary strings used by each module to identify the "type" of file usage the current record relates to. A single module might keep to track of files in several different contexts, so this is important.

  Is file/node effectively the same as imce/file, or is it something different?

They're different. file/node is for usage of files attached to a file field on a content type; imce/file is for tracking files uploaded and (potentially) inserted into a WYSIWYG.

  Does user/user mean it is a file associated with the user?

It doesn't have to necessarily, just because it's called user/user, but in this case yes, it does.

  Further file_usage has an id column; can I assume:...

Yes, that assumption is correct. The ID can relate to anything at all though, not just an entity that lives inside Drupal, it's up to the module using the table to be able to resolve which object/item is being referred to from the data in that table.


The most searched keyword of the default search? Is there a way, or a module, to get the most searched keyword of the site's default search?

You can check the "Top Search Phrases" report at "/admin/reports/search". This will give you a count of the search phrases used. It doesn't make it out by individual keyword, but at least gives you an idea of what people are searching for.


How to take the node reference field from views I have added images through image content type and tagged the node to article content type nodes using node reference , while getting the article credentials through views , i cant figure out how to take the images from the tagged node reference field through views .

some option only avail to get the node reference field in views .
1)Title.
2)Title link.
3)Full content.
4)Print.

and two more which is not helpful for me .

Here i need to get a image from image content type which is tagged in article content type through node reference .

Anyone help for this as soon as possible.

What you do is set up a relationship, as the image itself isn't the node reference, rather a field in that node.  So, you go into Views and after setting it up to grab your article fields, you then set up a relationship, and there, you select that node reference field from your article type.  Then, in fields, you go and select that image field, and there, you use that relationship.  What this does is go and grab that image content type's node id from your article and then using that node id, grab the image field out of it for display.


How to restrict anonymous users to a single product and quantity 1 using Commerce and Rules? I have a slightly unusual use case in that I want to allow authenticated users to order multiple products and use the shopping cart but I want to limit anonymous users to purchasing products individually (no changing quantities, no adding multiple products to the cart).

I am using Commerce and Rules on Drupal 7.  Because I do not want anonymous users to access the cart, I want to redirect them to the checkout page if they attempt to access the cart (I know this is not the most foolproof method, but it is sufficient for my purposes).

I tried creating a rule triggered on the event Content is viewed with the condition Path has URL alias of cart.  However, this rule is not triggered; when I add a Path redirect action and then visit the cart path, I am not redirected.  What event should I use in Rules to do the redirect?  Or is there some better way to do this?

These rules can be used to restrict number and quantity of products available by role.

They can be imported in Rules admin.

Restrict to single product:

Basically, before adding to cart, if anonymous, remove existing products from cart. The effect is only the latest product is added to the cart.

{ "rules_single_product_order" : {
    "LABEL" : "Single product order",
    "PLUGIN" : "reaction rule",
    "REQUIRES" : [ "rules", "commerce_cart" ],
    "ON" : [ "commerce_cart_product_prepare" ],
    "IF" : [
      { "user_has_role" : {
          "account" : [ "site:current-user" ],
          "roles" : { "value" : { "1" : "1" } }
        }
      }
    ],
    "DO" : [
      { "commerce_cart_empty" : { "commerce_order" : [ "commerce_order" ] } }
    ]
  }
}

Restrict quantity to 1:

On order presave, if anonymous, loop over the line items and set quantity to 1

{ "rules_restrict_quantity_to_1" : {
    "LABEL" : "Restrict quantity to 1",
    "PLUGIN" : "reaction rule",
    "REQUIRES" : [ "rules", "entity" ],
    "ON" : [ "commerce_order_presave" ],
    "IF" : [
      { "user_has_role" : {
          "account" : [ "site:current-user" ],
          "roles" : { "value" : { "1" : "1" } }
        }
      }
    ],
    "DO" : [
      { "LOOP" : {
          "USING" : { "list" : [ "commerce-order:commerce-line-items" ] },
          "ITEM" : { "list_item" : "Current list item" },
          "DO" : [ { "data_set" : { "data" : [ "list-item:quantity" ], "value" : "1" } } ]
        }
      }
    ]
  }
}

Anon can still view the cart, but they will be restricted to one product and quantity of 1 - a preferable solution here. You could also show a message about the benefits of registering, if required.


Move primary tabs to the shortcuts bar I am using drupal7 and the admin menu overlay (in seven). And I'm always apalled by the primary tabs appearing in view mode. They are messing up the layout for the editors / admins, and they're usually not in style with either the site design or the overlay design.

I was just wondering .. is there a pretty way to move the primary tabs ('edit' et al) to the admin overlay shortcuts bar - 'if the overlay is visible and you are in view mode'

Perhaps there are two answers:

remove the primary tabs from the content, if the overlay is visible and you are in view mode
add the primary tabs to the shortcuts bar,    if you are in view mode

Any hints ?

*-pike

The easiest way would be to use the http://drupal.org/project/admin_menu module.

It has an option to move the tabs into the admin menu bar.
Set it by going to the admin menu settings page (admin/config/administration/admin_menu) and checking the "Move local tasks into menu" option.

For users gien access to the admin menu, you should remove access to the drupal toolbar module, or they will have 2 toolbars.

You could even disable to toolbar module and just use admin menu.

If you want to keep using the toolbar module instead of the admin menu module, you can remove the tabs from the page.tpl.php file in your theme and then print them elsewhere.

I don't know off the top of my head how you would go about doing that though.


Rules, User registration, loop through other users with condition, set field value to 0 My configuration is the following :

Using D7

I have a node type called Items.

User with a node id entity reference field to this node can be affiliated to one of these nodes, four of them..

(So there is (x) Users who are affiliated to Node A, (x) Users to Node B.. C and so on..)

When registering new user has a "field_current_owner" (on/off), set by defaut
And choose his affiliation to one of these four nodes.

I want to make a rule that cycle through  other users affiliated to the same "node id reference" to have their "field_current_owner" switch off.

I am a bit confused with rules components.. someone could shade some light on my problem ?

Should i made a component which turn any user with id different (negate) than registered user with condition regisetred has same node id reference
trigger event get field i/o to "off" ?

I am a bit confused, then when i make a rule with my component fields previously inputed, how can I make it cycle through my user list ?

I am a bit in the mist with this module, can someone please give me hand ? Even a hint ?

Thanks by advance

Assuming your Rules event is User Updated and you don't have hundreds / thousands of users referencing each of the nodes,

Use the Action: Fetch Entity by Property [User>Entity Reference Field] and give it the Entity Reference of the Updated User. This will give you a list called Entity Fetched.

Create a Loop using Entity Fetched
Add an action to the Loop (on the right) and Set a Data Value: [List Item>Field>Not Current Owner]
Under the loop, Set a Data Value: [Updated User>Field>Current Owner]

That will save each user that references the node.

If you don't want that because of performance etc.,

You would create a Rules component and send each List Item in Step 2 above.
Then in that rule component, have a condition that checks the user's Current Owner field is set to True, and have an action to set it to false.
Do step 3 as above in the main Rule to set the current user as owner.


Save a managed file with cURL I want to save a managed file from an external site. Previously, I've used this code:

$managed = TRUE; // Whether or not to create a Drupal file record
$image_file = system_retrieve_file($product['img'], 'public://product-img-' . time() . '.jpg', $managed);
if ($image_file) {
  $file = file_load(db_query('SELECT MAX(fid) FROM {file_managed}')->fetchField());
  $item['field_image']['und'][0] = (array) $file;
}

However, it's throwing 403 errors for me so I decided to use cURL in my PHP code to get this image:

$ch = curl_init('http://g02.a.alicdn.com/kf/HTB15eliFVXXXXbKaXXXq6xXFXXXa/Original-Blackberry-Z10-Dual-Core-4-2-TouchScreen-2GB-RAM-16GB-ROM-8MP-Camera-Blackberry-os.jpg');
$fp = fopen('test.jpg', 'wb');
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_exec($ch);
curl_close($ch);
fclose($fp);

With cURL, it works correctly, and I can get the image. How can I save this data as a Drupal managed file?

file_save_data() will take the contents of a file and place into a location specified by a file URI. In your example, you can take your downloaded test.jpg, retrieve its contents, and have file_save_data() do the rest.

// Assuming same cwd where curl & fopen was executed.
$image_file = file_save_data(file_get_contents('test.jpg'), 'public://test.jpg', FILE_EXISTS_REPLACE);

// test.jpg will be placed/overwritten into your managed file system.
// $image_file contains the Drupal file object.


How do I extend the schema of an existing config_object? Module A defines the following schema in module_a.schema.yml.
module_a.settings.api:
  type: config_object
  label: API settings
  mapping:
    store:
      type: string
      label: Store code
    credentials:
      type: mapping
      label: Credentials
      mapping:
        username:
          type: string
          label: Username
        password:
          type: string
          label: Password

Module B extends the Module A configuration form and defines additional schema properties in module_b.schema.yml.
module_a.settings.api:
  mapping:
    additionl_one:
      type: mapping
      label: Additional one
      mapping:
        additionl_one_sub:
          type: label
          label: Additional one sub

The definition from module_b.schema.yml isn't picked up by Drupal. I'm checking with config_inspector and proving it by the fact that the new properties can't be translated.
Available articles/tutorials out there are doing the same thing but seems like this is either outdated or never worked:

https://www.drupal.org/forum/support/post-installation/2019-02-06/add-a-new-custom-field-to-site-infomation-form-in-drupal8

http://www.jaypan.com/tutorial/drupal-8-extending-core-configuration-extending-core-forms-and-overriding-core-routes#comment-33507

Use hook_config_schema_info_alter().
function module_b_config_schema_info_alter(&$definitions) {
  $definitions['module_a.settings.api']['mapping']['additionl_one'] = [...];
}


The condition for the 2 fields sort criteria the problem is this.
I have the representation of 2 fields ordered by
1. Discount - open for all users
2. weight
I need to sort was originally on 2 field - weight and if one is already busy 1 field - Discount, then sorting is conducted by him and 2 field-weight was not used, how can I achieve this?

I think possible to accomplish this if 1 field - Discount add independent the default value is not sorted, just outputs the data views, but how do I set the value of 3 in the sort of the same type as the group filters arbitrary value -Any-.
When I do the idea to 1 field value - Discount will not be involved and receive the following 2 field - Weight.
But how do I do this? After all, when you create a sort field has 2 radio buttons - ASC and DESC.

The problem has been solved using the Better Exposed Filters module.

  The Better Exposed Filters module replaces the Views' default single- or multi-select boxes with radio buttons or checkboxes, respectively. Description fields and Select All/None links can be added to exposed filters to make for a better user experience.


Drupal custom tabular View Use Case: I have two differnent Content Types, A and B, each with a taxonomy fields 'State'.

Content Type A has two nodes, with California and South Dakota selected.

Content Type B has two nodes, with Alabama selected in both nodes.

The requirement is to created a tabular View that would look like this:

So within the Views interface, how do I create this?

http://filedb.experts-exchange.com/incoming/2015/04_w17/909525/view.jpg

I think the Views Aggregator Plus module can be of help. Among others it has possibilities to tally and enumerate views fields, so I think you can make the summary table you're asking for.

The module description is as follows:

  In addition to what Views and Views Calc do, this module:

  enumerates group members
  produces tallies, i.e. textual histograms
  aggregates on Views PHP code-snippet evalutations
  can filter out result rows on regexp patterns
  gives you sorting on Views' Math expressions
  can process Webform submissions
  lets you add your own custom aggregation functions

  ... and it puts summary statistics at the bottom of your aggregated
  table as well!


Duplicate breadcrumbs but they're not in the $breadcrumb variable? I'm trying to remove this duplicate breadcrumb but I don't see what's generating it. Any ideas?

This was an easy one: turn off custom breadcrumb modules...


Add cutom body class when view is not return any results I know how to add additional class by preprocess function but I need to combine it with the view. So the new custom class should be added if my view returns 0 results. It looks like I can't use hook_views_pre_build because there's no vars for page elements. Any thoughts how to achieve it?

Might be a little over-kill, but it's the first thing that comes to mind without having to build a custom view in code (which is cleaner imo). I am referencing Views 2 only, might be different in 3.

Create an empty view page, strip it of everything if you'd like, it just needs to exist.
In the view you are using, for the no results behavior, choose to include the empty view.
Using the Context module, add the condition that if the empty view is shown on the page to execute. In the reactions area, add Theme HTML which will allow you to enter in your custom css class to the body tag.


Setting up an features server? I've found dev seed's article on this issue: http://developmentseed.org/blog/2009/sep/03/5-minute-feature-server/

Is it the same process for Drupal 7?

I don't think there is a D7 of the feature server but you can host your D7 specific features on a D6 feature server.


Possible Ways to Style a View (Block) What are the possible ways one can style a View (Block) in Drupal 7? I have a View outputting to a Block on a Drupal 7 site that has custom styles which I need to copy; however, I cant seem to find where they are located.

The possible ways are:

1) using a CSS file, ex: style.css (located in your /sites/all/themes/YOURTHEME/css folder)

.block { border: solid red; }

2) using jQuery, ex: style.js (located in your /sites/all/themes/YOURTHEME/js folder)

$('.block').css({"border":"solid red"});

3) using a template file, ex: block.tpl.php or view.tpl.php (located in your theme's /sites/all/themes/YOURTHEME/template folder)

<style>
.block { border: solid red; }
</style>

4) Inside the view, if they add a header or footer of text area or unfiltered text and then put inside the header/footer:

<style>
.block { border: solid red; }
</style>

or

<script src="myScript.js"></script>

5) Using the CSS Injector module

6) Using the JS Injector module


Access Denied when Menu CallBack Function is Called I am trying to call a function after the user clicks on an ajaxified link below.

$form['link'] = array(
  '#type' => 'item',
  '#markup' => l(t($record->studid),'myid_print/callback', array('attributes' => array('class' => 'use-ajax'))),
);

Below is my hook_menu function:

function myid_print_menu()
{
    $items = array();
    $items['myid_print/callback'] = array(
        'page callback' => 'myid_print_user_page_callback',
        'access callback'    => 'myid_print_user_access',
        'file' => 'myid_print.pages.inc',
        'type' => MENU_CALLBACK,
    );
    return $items;
}

function myid_print_user_access()
{
    return TRUE;
}

myid_print.pages.inc file:

function myid_print_user_page_callback()
{
    return 'Successful';
}

The above code throws the error below:

Where am I missing?

Your AJAX request is calling the path /drupal-7.34/myid_print/callback on the server. The path registered on your Drupal instance (assuming you're running under the drupal-7.34 directory) is /drupal-7.34/print/callback. Hence, the error you're seeing.

If you want to pass an argument to your print callback, you should do this.

$items['print/%/callback'] = array(
    'page callback' => 'print_user_page_callback',
    'page arguments' => array(1),
    'access callback'    => 'print_user_access',
    'file' => 'print.pages.inc',
    'type' => MENU_CALLBACK,
);

function print_user_page_callback($id)
{
    return 'Successful printing '.$id;
}

Read more on hook_menu() if you'd like to understand more how module's can register paths.