How do I get rid of a staged configuration import? I have a staged import that I can't apply and I would like to get rid of it and be clean in my configuration management screen.
How do I get rid of the staged import? Can I go to sync folder and delete the .yml files and the export the current configuration again?
I am extremely nervous about breaking the site.
I know it is saved in the db but I don't want to go in and delete it from there either, unless that is an option.
I wont be able to apply any other import because of this staged one sitting here.

If you export the configuration again current configuration files should be deleted and new ones will be created with the configuration hold in your database.

Anyway you should make a backup first, just in case. You can use drush for this. Use drush archive for a complete backup (including files):

drush ard

Use drush sql-dump to backup only the database:

drush sql-dump > /patch/to/new/file/with/db-dump


How do I add rate widget to certain content type? I have a certain content type I want users to be able to rate. I decided to go with the rate module, since I want to be able to change the value of each star.

My problem is I don't know how to add the certain rate widget to a content type. In widget settings there are no checkboxes in the "Node types" option. Screenshot below.

I cannot find a clear reason for why this happened. The best answer I can give to someone with the same problem (doesn't seem to be a common problem at all) is to start over with a clean Drupal install.


Integrating the Webform module in a page I want to have a form that will take end user inputs (text, sentence, text of multiple values and an image upload of png or jpeg format).

These inputs would be later stored in database and would be retrieved using views mysql module and displayed in webpage.

I tried to integrate the Webform module in my page, but it didn't work well with images while displaying through a view. It displays numbers instead of images (actually this is the place where I am facing issues).

Is there any ways that I can fix this, or do I need to build a module from scratch?

You can achieve this goal using Entityforms module.Using this module you can take input of text as well as image like webform. This module can be integrated with rules and data export etc. for sending mail and downloding submission as like webform.

There are a lot of advantage over webform but it is different form webform.

For more info go through module documentation.


Fields from custom nodes into Webform I have some nodes like this http://sprachzentrum.com.ar/cursos/curso-intensivo-de-alem%C3%A1n-nivel-a21-agosto-2011 and webforms and want to insert titel and day field as an option in the webform.

So that the user can choose from different levels

thanks of course! My question was: I have a node with an titel and some customer fields like level an time an I ask myself if its possible tu render the listbox automaticaly so that i will a options like:

1| [custom-field-level-1] [node-title-1] [custom-field-time-1]
2| [custom-field-level-2] [node-title-2] [custom-field-time-2]
3| [custom-field-level-3] [node-title-3] [custom-field-time-3]

So for each node from a certain type I will get an option on my webform

For both level and date (I understand these are session, so a range of date), you can add some "select list" in order to let the user select between the available options.
Do you have troubles adding this ? Can you make your question a little clearer regarding what you want and what causes you difficulties ?

Select the "listbox" option and it will produce:

Edit June, 23:

so you have a Content Type named "webform_info" with some fields "field_level" and "field_time".
the idea is to implement a hook_form_alter (in a custom module) to retrieve these fields and put them in the webform

    <?php
    function custom_form_alter(&$form, &$form_state, $form_id) {
      //you need to set up a custom module to store this.
      //use devel with dsm($form); to figure the name of each field
      if ($form['#id'] == 'webform-client-form-123') {
        //delete the array of options from the webform field, they start by "con_"
        $form['submitted']['con_level']['#options'] = Array();
        $form['submitted']['con_level']['#options'][''] = '- Select one level/time -';
        $i = 1;

        //retrieve the nodes of the type webform_info
        $result = db_query("SELECT nid FROM {node} n WHERE type = 'webform_info' AND status = 1");
        while ($row = db_fetch_array($result)) {
          $node_level = node_load($row['nid']);
          $form['submitted']['con_level']['#options'][$i] = $node_level->field_level[0]['value'] . $node->title . $node_level->field_time[0]['value'];
          $i++;
        }
      }
    }
    ?>

Doing node_load can be pretty heavy if you have a great number of nodes, so you might want to use the CCK table structure, have a look at another answer to adapt the code.
Code is for D6 but should give you some insights to apply this to D7 if needed.


What is the correct way to send a node list to the REST API? In Drupal, we can create nodes with the core module "RESTful Web Services". There is a lot of documentation about creating one node with one request, the Drupal documentation provides the following example:

curl --include \
  --request POST \
  --user klausi:secret \
  --header 'Content-type: application/hal+json' \
  --header 'X-CSRF-Token: <obtained from http://example.com/rest/session/token>' \
  http://example.com/entity/node?_format=hal_json \
  --data-binary '{"_links":{"type":{"href":"http://example.com/rest/type/node/article"}},"title":[{"value":"Example node title"}],"type":[{"target_id":"article"}]}'

We want to import 25.000 nodes on a regular basis and worry that this could take really long if we use a separate request for each node.

It should be possible to send a list of nodes. Drupal's REST web service uses the Serializer Component from the Symphony framework. The Symphony docs say that it includes the serialization of lists of nodes. Passing a list to the REST web service should simply look like this.

curl --include \
  --request POST \
  --user klausi:secret \
  --header 'Content-type: application/hal+json' \
  --header 'X-CSRF-Token: <obtained from http://example.com/rest/session/token>' \
  http://example.com/entity/node?_format=hal_json \
  --data-binary '[{"title":[{"value":"Title 1"}],"type":[{"target_id":"article"}]},{"title":[{"value":"Title 2"}],"type":[{"target_id":"article"}]}]'

When I send this data, I get this response.

  Could not determine entity type bundle: type field is missing.

t seems that the serializer does not recognize that I send a list.

What is the correct way to send a node list to the REST API?

Solution 1: Custom Endpoint

Unfortunately, entities are expected to be created one by one when using RESTful web services. You can create your own web service endpoint by writing a custom module and there, you can create support for creating multiple nodes with a single request. However, you'll still have to use batches of say, 50 nodes per request for things to work smoothly. This is more of a push import.

You might also want to try the jsonapi module to see if supports importing multiple operations in a single request.

Solution 2: Migrate API

Have you considered Drupal's migrate API instead? With migrate, you can import nodes from a remote XML / JSON document with a simple drush command which you can setup as a part of cron on your server. You can update existing items and create non-existing items. Migrate will also create nodes one by one, but it will be much faster than REST requests because it will not involve 1 HTTP request per node. This is more of a pull import.


Drupal 8: How to properly add a settings widget to a node add/edit form and save the value? So I reviewed the code in the core book, menu_ui, and path modules, and they all seem to handle adding a settings widget in a vertical tab differently.

The book module uses a method called addFormElement(), which is called within a hook_form_BASE_FORM_ID_alter() hook.

The menu_ui module is similar, but uses hook_form_BASE_FORM_ID_alter() directly.

Path seems to use a method called formElement(), and I'm not even sure where/how this method is used at the moment.

The real question I have is, how does one actually process the form setting and save it to the database? I have tried to find an example, but I'm at a loss.

Is there a help page with examples like the ones I found for adding an admin settings page?

If not, is there a recommended approach to displaying/saving a value in a vertical tab on a node add/edit form?

I'm going to take a stab and show how I solved it, but I'm still curious to know if there's a better way.

In a nutshell, I used hook_form_BASE_FORM_ID_alter(), hook_node_submit(), and hook_ENTITY_TYPE_insert() or hook_ENTITY_TYPE_update() in the .module file.

Then I have a class called HierarchyManager that does all the heavy lifting that the D7 .module and .inc files used to do. It's listed as a service named "nodehierarchy.manager".

Lastly, I have a class called HierarchyOutlineStorage that handles the database inserts and updates. Quite a bit of that code was copied directly from D7.

In my .module file:

/**
 * Implements hook_form_BASE_FORM_ID_alter() for node_form().
 *
 * Adds the hierarchy form element to the node form.
 */
function nodehierarchy_form_node_form_alter(&$form, FormStateInterface $form_state, $form_id) {

  // Load the node object associated with this form
  $node = $form_state->getFormObject()->getEntity();
  $account = \Drupal::currentUser();

  // Optional but keeps the .module code cleaner IMO
  $hierarchy_manager = \Drupal::service('nodehierarchy.manager');

  // Do your permission checks here
  $has_permission = ...;
  if($has_permission) {
    $form = $hierarchy_manager->addHierarchyFormElement($form, $form_state, $node, $account, $collapsed);
  }
}

/**
 * Implements hook_node_submit().
 */
function nodehierarchy_node_submit(NodeInterface $node, $form, FormStateInterface $form_state) {
  // Here the node object gets updated with the form value to be used later
  // If you aren't sure about the $form_state, download/enable devel and add
  // dsm($form_state->getValues()) to show all available values
  if (!$form_state->isValueEmpty('nodehierarchy_parents')) {
    $node->nodehierarchy_parents = $form_state->getValue('nodehierarchy_parents');
  }
}

/**
 * Implements hook_ENTITY_TYPE_insert() for node entities.
 *
 * Save the form settings
 */
function nodehierarchy_node_insert(NodeInterface $node) {
  $hierarchy_manager = \Drupal::service('nodehierarchy.manager');
  $has_permission = ...
  if ($has_permisson) {
    $hierarchy_manager->hierarchySaveNode($node);
  }
}

/**
 * Implements hook_ENTITY_TYPE_update().
 */
function nodehierarchy_node_update(EntityInterface $node) {
  $hierarchy_manager = \Drupal::service('nodehierarchy.manager');
  $hierarchy_manager->hierarchySaveNode($node);
}

In the HierarchyManager.php file:

public function addHierarchyFormElement(array $form, FormStateInterface $form_state, NodeInterface $node, AccountInterface $account, $collapsed = TRUE) {
  // Insert $form array here
  $form['hierarchy'] = array(...);
}

public function hierarchySaveNode(&$node) {
  // Do all your processing here, then insert or update dB record
  $isNew = ...
  if ($isNew) {
    return $this->hierarchyOutlineStorage->insert($item);
  }
  else {
    return $this->hierarchyOutlineStorage->update($item->hid, $item);
  }
}


Drupal Menu Translation Not Functional I am working on internationalization.
My site's first language is english, with a spanish translations.

I am using Drupal 7, with
Internationalization 7.x-1.10

I have everything but menu translation working.
The tutorials I am reading about menu translation say to create a new menu,
and before you submit your new menu go to the "Multilingual Options"
section, which lets you set the translation for this menu.

Mine is missing this "Multilingual Options" setting.

Despite this I tried to translate the menu's links by viewing the links for the menu and clicking on "translate"

When I add links to the menu, and click translate on those links, I get an "access denied" exception.

Does anyone know why this might be happening?

Go to /admin/structure/menu/manage/main-menu/edit and click "Translate and Localize. Menu items with language will allow translations. Menu items without language will be localized. "


How do I fill the authors name in a term reference field? Content type stock contains the term reference field field_producer. What is the rule for Rules in order to fill this field with the node author name on creation?

In detail

The form looks like:

-- Content type Stock (stock)

---- field Producer (field_producer); of field type Term reference; of widget Autocomplete term widget (tagging); number of values: 1; Vocabulary: Producer

The goal is:

When a user creates a node of the type Stock, his user name should automatically be filled/(pre-)populated in the field Producer.

Why Rules:

Since tokens aren't working for the autocomplete term reference field and a text field isn't available, rules might be a workaround. I've tried Prepopulate, Entityreference prepopulate, and other modules, but none of them supported the aim.

Where I am struggling with Rules:

Event: After saving new content, Restrict by type Stock
Condition: Entity has field, Data selector node:field-producer, Field Value field_producer
Action: Set a data value, Data (to be modified) node:field-producer, Value (to set for the specified data): HERE REMAINS THE PROBLEM. I can't choose node:author or other tokens that display the user name. I get the restriction: "Data types: Select data of the type Taxonomy term."

That's why I am not able to successfully create this rule.

What am I doing wrong? How should this rule look like?

... I can't choose node:author or other tokens that display the user name. I get the restriction: "Data types: Select data of the type Taxonomy term."

1. Switch to the direct input mode

You should click the Switch to the direct input mode button (near the bottom left), which looks like this:

After clicking that button, it will bring up a selection list of the available terms (= possible values) that you can use in your taxonomy field.

2. Example

Consider this example, in Rules Export format, of a rule (actually a Rules Component, but the idea is the same) to illustrate how such Rules Action to "Set a data value" should look like and which will set the value of the term reference field field_sample_tags to term id = 31:

{ "rules_replace_a_term_field_by_another_term_field" : {
    "LABEL" : "Replace a term field by another term field",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : { "node" : { "label" : "Node", "type" : "node" } },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_sample_tags" } },
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_demo_tags" } },
      { "data_is" : { "data" : [ "node:field-demo-tags" ], "value" : "1" } }
    ],
    "DO" : [
      { "data_set" : { "data" : [ "node:field-sample-tags" ], "value" : "31" } },
      { "drupal_message" : { "message" : "Term updated in node with id = [node:nid]" } }
    ]
  }
}

Some more details to explain the above prototype:

It uses a node as a parameter (to execute the Rules Component).
These are the Rules Conditions:

check if the entity (= node) has a field field_sample_tags.
check if the entity (= node) has a field field_demo_tags.
check if the value of the field field_demo_tags corresponds to the term we want to replace (in this example, the term has id = 1).

These are the Rules Actions:

Set the value of field field_sample_tags equal to the term with term id = 31 (which is the term in the vocabulary for which we want to add the term reference).
Display a message on the site (only used for demo / testing).

3. Improvement - Pick the existing term that fits

Your question doesn't say "How to pick the appropriate term (i.e. its term id) to be used to perform the 'Set a data value' for a given node author (how can you derive that term id from the data about the node author)?".

If you only have a few node authors (say "Xin" and "Pierre"), you could use the Conditional Rules module to improve that Rules Action to 'Set a data value', so that the value to be used for the term id depends on the value of the node author.

4. Open question

Your question doesn't say "What should happen if no term exists yet for a specific node author?". If such scenario is impossible in your site, then you're lucky (and good to go). Otherwise you'll have to further improve the Rules logic you're implementing to:

get the appropriate (new) term created on the fly.
go find out what the term id is for the newly created term.
improve the Rules Action to 'Set a data value' to actually use the term id of this newly created term.

If you wonder how to do that (also), use this link ... 3 times (one for every bullet).


How to incorporate AMP in an existing theme? Is there a way to incorporate AMP into my Porto Theme?

The AMP project for Drupal has three parts. The AMP module, the AMP PHP Library, and the AMP Theme work together to provide valid AMP markup for nodes with AMP-enabled content types at paths with ?amp at the end of the URL.

From the AMP module page:

  The AMP module is designed to convert Drupal pages into pages that comply with the AMP standard. When the AMP module is installed, AMP can be enabled for any node type. At that point, AMP content becomes available on URLs such as node/1?amp or node/article-title?amp.

  The AMP PHP Library analyzes HTML entered by users into rich text fields and reports issues that might make the HTML non-compliant with the AMP standard. The library does its best to make corrections to the HTML, where possible, to make it more compliant with the AMP HTML standard.

From the AMP Theme page:

  The AMP Theme is designed to produce the very specific markup that the AMP HTML standard requires. The AMP theme is triggered for any node delivered on an ?amp path.

Some additional reading, an article describing the three in more detail on the official AMP blog: AMPing up Drupal.


How to create suggestions conditionally (by block type/bundle) override system templates in Drupal 8 For example, I want to override image template (image.html.twig) to change how it outputs images from

to

But I require to override only those images, that are rendered inside specific block type (called "bundle" in Drupal terms) b_partner_images.

There is a hook_theme_suggestions_alter(array &$suggestions, array $variables, $hook) hook, that allows to create suggestions based on some conditions, but the problem is that $variables does not contain anything more than image tag attributes - no objects or identifiers, so I see no way to create condition based on some identifiers or block (bundle) name.

How to create file name suggestion for system templates (such as image) to override image output based on block type or any other identifier?

Currently, I have only found a workaround using image-formatter override

Create a file name suggestion hook for theme in themename.theme:

function themename_theme_suggestions_alter(array &$suggestions, array $variables, $hook) {
    switch ($hook) {
        case 'image_formatter':

            /**
             * @var Drupal\url_image\Plugin\Field\FieldType\UrlImageItem $item
             */
            $item = $variables['item'];
            $config = $item->getFieldDefinition();
            switch ($config->getTargetBundle()) {
                case 'b_partner_images':
                    $suggestions[] = 'image_formatter__b_partner_images';
                    break;
            }
            break;
    }
}

Create a template file image-formatter--b-partner-images.html.twig:

It works, but not as beautifully, as I would like.

PS: I used that specific hook_theme_suggestions_alter format, because I have more than one suggestions hook, and I put them inside this single function, so I can add more conditions with ease.


Dont want horizontal scroll bar for views I am using a view called "exhibit" with multiple fields.
I am getting a horizontal scroll bar since the view have multiple fields.
But I don't want the horizontal scroll bar.

How can I achieve this.

You can use css like this:

overflow-y: scroll;
overflow-x: hidden;


Exist a Drush command to update all the contents? We have a client who was adding content to a separated dev server, the dev server is whitelisted only and doesn't allow incoming/outgoing connections to a lot of services.

The client was adding videos with the video embed field module, which automatically generates a static file on our server.

The firewall config means that this error was produced

Warning: file_put_contents(temporary://fileTjnJTX): failed to open stream:      "DrupalTemporaryStreamWrapper::stream_open" call failed in      file_unmanaged_save_data() (line 1898 of /var/www/user/includes/file.inc).
The file could not be created.

When editing and saving the content drupal tries to regenerate the image if none is available Our sysadmin is working the firewall configuration to allow the connections, but we was wondering if there is any easy way/drush commands/mysql statment to update all content,

You can take a look inside the module Drush Entity because in this module you have the command entity-update:

drush @drupal.d7 entity-update node 53 --fields=title

If you want to improve the command to work in all nodes you can read this post:

How to adapt the name of a custom Drush command?

EDIT:

If you want to learn about Drush alias (@drupal.d7) you can go to: Drush Aliases: What, Why and How


Entityfrom spam protection module without captcha Is there a module which I can use with entity forms without needing captcha field?

You may be looking for Hidden CAPTCHA.

Even though you need the CAPTCHA module for this, Hidden CAPTCHA module will not display any captcha field and you don't absolutely need to have a human enter a text, number, etc.


Why does drupal_session_start fail after a user clears cache then logs back in? I'm writing a document management module which has come pretty far and is almost ready for a final review and release, but I've found a really strange authentication issue that is requiring a gross work around.

Several actions in my module are handled via AJAX. I need to authenticate my user when I run the AJAX protocol. I also need to get the drupal core functionality so I'm using the following code:

// Bootstrap Drupal
define('DRUPAL_ROOT', dirname(dirname(dirname(dirname(dirname(__FILE__))))));
require_once( DRUPAL_ROOT . '/includes/bootstrap.inc');
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

// Validate the user
_drupal_session_read($_POST['sid']);
drupal_session_start();
if ( ! user_access('manage documents') ) {
    die('Access denied');
}

$_POST['sid'] contains the value from session_id() or $user->sid. They should be the same thing, but if I clear my cache, log back in, go to the page, and run any AJAX action, I will get permission denied on the first request every time. My ugly work around is to send a "checkin" action that just triggers the access denied because once it happens once, it doesn't happen again.

Can anyone explain to me why this code would behave this way?

Thanks!

For D6, following lines will work to get the session values

require_once './includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

If you are using D7 user Drupal's built-in ajax framework.


Loop through entities chosen by Views Bulk Operations I successfully created a new action using hook_action_info() and a corresponding hook_action(). However, I want to find the method which loops through the elements chosen by Views Bulk Operations, as I wanted to combine some pages for a pdf.

What method loops through the entities chosen by VBO?

Quoting the VBO Development guide, you can use the aggregate option to get a list of all chosen entities.

  implement hook_action_info()

  aggregate (optional): boolean. If TRUE, all selected objects' IDs
  (oids) will be packed in an array and passed as the first argument to
  the action function, instead of passing each object one by one. This
  is useful to implement aggregate functions that perform a single
  operation on the whole selection set.

Note this guide is only for D6. I have created a D7 version but could not add an aggregate example yet.

However, in your hook_action_info() implementation, set aggregate to TRUE (defaults to FALSE) and VBO will send a list of entity IDs (for you to perform additional related tasks).


how to have a another page.tpl.php file in drupal with different regions and blocks? Well, here is the problem. In my site I want to create a plain template and add my own regions and my own blocks. So when the user visits for example www.example.com/register-now the blocks will be different from the main page. I dont like disabling the blocks because when you open Firebug the blocks can be still be seen.

So I have read in this article that you have to create a new .tpl.php file.  So in my case I created the page__register-now.tpl.php file. and put that under drupal/sites/all/themes/ninesixty/ directory.

Then I opened the template.php file and tried the below code:

function ninesixty_preprocess_page(&$vars, $hook) {
  $path=drupal_get_path_alias();

  if($path == 'register-now'){
    $variables['theme_hook_suggestion'] = 'node__register';
  }
}

If your path to the register page is www.example.com/register-now then you only need to name the page template file appropriately and Drupal should do the rest, you shouldn't need to add anything to template.php.

From what you've written, the name of the page template file is wrong. It needs to be renamed to: page--register-now.tpl.php (notice the underscores turned to dashes).

After you rename the file (usually after adding any additional template files), make sure to clear all caches from admin/config/development/performance.

EDIT: If your page is a node, you can't use the Alias path in the template file, it actually has to be the internal path to the node, e.g. page--node--123.tpl.php where 123 is your node's ID.

  The rest are based on the internal path of the current page. Do not confuse the internal path to path aliases which are not accounted for.

See here


Re-import nodes daily using feeds and hook_cron My requirement is to import nodes daily night after deleting all the contents in that node type.

I enabled the cron settings in feeds module as 1 day and tried to write hook_cron() to delete all nodes.

function my_module_cron() {
  $results = db_select('node', 'n')
              ->fields('n', array('nid'))
              ->condition('type', 'ars', '=')
              ->execute()
              ->fetchCol();
  if (!empty($results)) {
    node_delete_multiple($results);
  }
}

But the doesn't seems to be deleted. I think this might be because of the user access problem.

I also want to know will the delete occurs before re-importing. How to order the cron jobs or shall I run the import via code after deleting the nodes.

There is no need to do that manually.

Under Settings for Node Processor just select Replace Existing Nodes.

For further details you can check https://www.ostraining.com/blog/drupal/feeds/ which explains the steps in detail.

There is a field called GUID. Make sure that you set it to an appropriate value so that nodes will be updated(deleted and reimported). If the GUID in your site matches to that of the import then current nodes will be deleted(irrespective of whether they were created manually or imported) and the nodes from your news source will be reimported.


Is it possible to use features or some other technique to compare two sites? I have a virgin copy of Open Outreach running alongside a copy where I've made configuration changes such as site name and configurations of various modules. Is it possible to use Features or some other technique to discover and document changes I've made?

If you are using Drupal 8, yes you can. But if you are using Drupal 7 I doubt you can yet do it. There is a backport of Configuration Manager to Drupal 7, which might make it possible.

The reason I said you can't do it in Drupal 7 is that the settings are saved in database and it is very difficult to make a comparison of the databases for settings. So if you have already made the changes and don't have a log, I would suggest exporting individual features using Features Suit of Modules.

You can checkout my presentation http://www.slideshare.net/gokulnk/features-15841090 for related Features modules which will make your work easier.

As a suggestion next time you want to keep a journal of your configuration changes please use Journal Module which should serve you well to keep track and document your changes.


How to print specific fields in a view? I have 3 content types:

Country
Destination
Attraction

Each attraction has an entity reference poiting to Destination.
Each destination has an entity reference poiting to Country.

I need to create a view in a block, published on all content types Country that lists all Destinations within that country and the number of attractions within each Destination.
For example, France destinations are Paris and Marseille. Paris has Eiffel Tower, Louvre and Pont Neuf as attractions. Marseille has Chateau d'If and Panier as attractions.
In my country node I should be able to print:
Paris (3)
Marseille (2)
I only need the title and that particular number, with links on title going to their specific nodes.

How could that be achieved? I was thinking about aggregation but I have tried to do so and failed. Thank you!

try:

under Advanced Tab, create a relationship. the type will depend on your field names exactly, but if the view is for the country, you should be able to find the destination and attraction fields available.

the new related fields should show up now in your Fields list and you can add them to the view

For the count, try the following:

Entity Reference Count
or
Entity Reference Calc
or take a look at this on SO


Change the images URI values within an array In a custom module of services 3.x Drupal 7 that queries the database, I get the values of the URIs of some images within some nodes.

This is part of module:

$res = db_query("SELECT node.nid AS nid, node.title AS title, body.body_value AS body, fm.uri AS uri
FROM {node} node
INNER JOIN {field_data_body body} ON body.entity_id = node.nid
INNER JOIN {field_data_field_header_image header} ON header.entity_id = node.nid
INNER JOIN {file_managed fm} ON fm.fid = header.field_header_image_fid
WHERE ((node.status = '1') AND (node.type IN ('tiendas')))
ORDER BY nid DESC");

foreach ($res as $cupon) {
$resultados[] = $cupon;
}
return resultados;

And this the json returned by the web services:

[
 {
  "nid": "6",
  "title": "Negron Beach Bar",
  "body": "
Este es el descuento de Negron
\r\n",
  "uri": "public://negron.png"
 },
 {
  "nid": "5",
  "title": "PizaPuck",
  "body": "
Este es el descuento de PizaPuck
\r\n",
  "uri": "public://pizapuck.png"
 }
]

But I need the full url. Not the URI. The json should look like this:

 {
  "nid": "5",
  "title": "PizaPuck",
  "body": "
Este es el descuento de PizaPuck
\r\n",
  "uri": "http://example.com/site/default/files/pizapuck.png"
 }

If I use this from below I get the url I need (in $path), but I have to put the URI value by hand:

$uri = "public://pizapuck.png"; //by hand
if ($wrapper = file_stream_wrapper_get_instance_by_uri($uri)) {
$path = $wrapper->getExternalUrl();
}

How can I do to replace every URI value inside the array? I need to extract every value of URI, replace it with the path value, and put it back into the array? I understand this is basic and simple, but my knowledge of php, pdo, ppo and mysql are quite poor. Any help on this matter thank you in advance.

I think you will have success with

file_create_url("public://pizapuck.png");

so

for ( $i = 0; $i < count($resultados); $i++){
  $resultados[$i]['uri'] = file_create_url($resultados[$i]['uri']);
}

would loop through your results and change them. (untested code typed directly in here).


Breadcrumb per content type per role, bootstrap theme I need to display a breadcrumb per content type and per role. What the best way  to do it. I've tried a lot of module and none fit my needs.

I tried overwritting breadcrumb in template.php as follow, and it's not working :

function local_breadcrumb($variables) {
  $output = '';

  global $user;
  /** Breadcrumb for hsrehab_admin **/
  if(in_array('hsrehab_admin', $user->roles)) {
   if ($vars['node']->type == 'patient_sheet') {
     // Build Breadcrumbs
     $breadcrumb = array();
     $breadcrumb[] = l('Dashboard', '');
     $breadcrumb[] = l('Manage Patients', '/admin/manage-patients');
     $breadcrumb[] = l(drupal_get_title(), base_path() . request_uri());
     }
   }

  // Determine if we are to display the breadcrumb.
  $bootstrap_breadcrumb = bootstrap_setting('breadcrumb');
  if (($bootstrap_breadcrumb == 1 || ($bootstrap_breadcrumb == 2 && arg(0) == 'admin')) && !empty($breadcrumb)) {
    $output = theme('item_list', array(
      'attributes' => array(
        'class' => array('breadcrumb container'),
      ),
      'items' => $breadcrumb,
      'type' => 'ol',
    ));
  }
  return $output;
}

You can create a theme template for each content type, then add the breadcrumb logic in there and output the modified breadcrumb there. Here's a great DO resource for theming and how to use template files. In a nutshell, you can clone your default page.tpl.php and rename it page--patient_sheet.tpl.php and inside this template you can run and output the breadcrumb logic.


Anonymous user edited data as draft/revision in drupal 6 I have a problem(may be only for me).  My requirement is anonymous user or registered user if they like to make a modification in a node they should be permitted but the modifications made by them should be saved as draft until the admin approves them.

Please let me know how this can be achieved.

You can accomplish this with the Workflow module.  You probably also need the Revisioning, Module Grants and Rules modules.


Diagnosing drush sql-sync problem Broadly, I'm having problems running drush sql-sync so that I can get a local copy of my dev database. I was getting an "The external command could not be executed due to an application error ... code: 255)" type thing.

To diagnose the problem more specifically, I ran drush @local sql-conf and got

 Array
    (
        [driver] => mysql
        [database] => soa
        [username] => drupaluser
        [host] => 127.0.0.1
        [port] => 33066
    )

When I then ran drush @dev sql-conf I got

Permission denied (publickey,password).

Running drush @dev sql-conf -s results in

Simulating backend invoke: ssh -o PasswordAuthentication=no git@dev.sub.mysite.com 'drush  --invoke --simulate --root=/var/www/dev --uri=http://default  sql-conf   --site=sub --env=dev 2>&1' 2>&1

Permission denied (publickey,password).

This means the issue isn't with Drush, it's that the server that matches up to your @dev alias doesn't have your SSH public key set up to allow you access. Either your public key hasn't been added to the ~/.ssh/authorized_keys file or the permissions on that file (or the ~/.ssh/ directory) have the wrong settings.


Give permissions to a specific role to edit specific terms I have a vocabulary (Foods) with these terms.

Meet
Fruits

I want every user with the Gardner role to be able to edit the description of Fruits only. How can I do that?

This is just an example, on my site I have several terms, and I need specific users roles to edit specific term descriptions.

https://www.drupal.org/project/private_taxonomy does what I need, but I already have the taxonomy terms and I don't know how to change the ownership.

The access callback for a term edit page is taxonomy_term_edit_access($term). You need to replace it with a custom one in order to allow gardeners to access the page for fruit terms.

/**
 * Implements hook_menu_alter().
 */
function MODULE_menu_alter(&$items) {
  $items['taxonomy/term/%taxonomy_term/edit']['access callback']
    = 'MODULE_term_edit_access';
}

/**
 * Access callback for taxonomy edit term page.
 */
public function MODULE_term_edit_access($term) {
  if (MODULE_term_is_fruit($term) && user_access('edit fruits terms')) {
    return TRUE;
  }
  return taxonomy_term_edit_access($term);
}

/**
 * Returns whether or not a term is a fruit.
 */
function MODULE_term_is_fruit($term) {
  // ... implement fruit detection here ...
  foreach (taxonomy_get_parents_all($term->tid) as $parent) {
    if ($parent->name == 'Fruit') {
      return TRUE;
    }
  }
  return FALSE.
}

/**
 * Implement hook_permissions().
 */
function MODULE_permissions() {
  $permissions['edit fruits terms'] = array(
      'title' => t('Edit fruits terms'),
      'description' => t('Allows the user to edit Fruits terms.'),
  );
}


Let New Users Connect with Twitter OAuth only (not Facebook) I would like to let new users register with a Twitter OAuth for new' signups' to my project so not really wishing for Facebook implementation as yet. There seems to be a range of subjects & options via Drupal.org etc, but I'm simply looking for a quick and easy 'out of the box' solution to getting this going without having to waste lots of time trying to figure out which route to go. I already have a Twitter account so just need a pointer to best 'free' option geared towards Twitter for signup purposes to my projects. Thanks.

You can look into HybridAuth Social Login

  This module integrates HybridAuth library into Drupal and allows your
  users to login and register using:

  Facebook Twitter Google LinkedIn Foursquare Yahoo Windows Live MySpace
  AOL OpenID Github, LastFM, Vimeo, Disqus, Instagram, Viadeo, Identica,
  Tumblr, Goodreads, QQ, Sina, Murmur, Pixnet, Plurk, Skyrock, 500px,
  Vkontakte, Mail.ru, Yandex, Odnoklassniki, Twitch.tv, Steam and more

You can select which all social logins you want to enable. So if you are just looking for twitter you can enable that alone.


How do I get parameters from form redirect? I've made a form and I'm trying to get the submit result into a redirect page with URL api:

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

    $metier=$form_state->getValue('metier');
    $position=$form_state->getValue('position');

    //$form_state->setRedirect('recherche.resultat',array('param'=>'test');

    $url = new Url('recherche.resultat');
    $url->setOptions(array('param'=>'test2'));
    $url->setRouteParameters(array('param'=>'test2'));

    $form_state->setRedirectUrl($url);

    drupal_set_message("envoyer");

}

I set two options :

$url->setOptions(array('param'=>'test2'));

and

$url->setRouteParameters(array('param'=>'test2'));

The form redirect me and this is my controller :

public function resultat()
{
    $request = \Drupal::request();
    $url = Url::createFromRequest($request);
    kint($url);
    kint($url->getOptions());
    kint($url->getRouteParameters());
    return array('#markup'=>t('test'));

}

The two methods :

    kint($url->getOptions());
    kint($url->getRouteParameters());

are empty

This is my routing :

 recherche.resultat:
  path: '/resultat'
  defaults:
    _title: 'resultat'
    _controller: '\Drupal\recherche\Controller\ResultatRechercheController::resultat'
  requirements:
     _permission: 'access content'

The parameters are in the URL and I can get them with $_GET but how can I get with the URL API?

Ok i got it by this way :

So i have 2 parameters from my form to pass to my controller :

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

    $metier=$form_state->getValue('metier');
    $position=$form_state->getValue('position');

    $url = \Drupal\Core\Url::fromRoute('recherche.resultat')
          ->setRouteParameters(array('metier'=>$metier,'position'=>$position));

    $form_state->setRedirectUrl($url);

}

The key is in the YAML routing, you need to build your path like that for get parameters ( name of parameters need to be same as your route, see previous function (submitForm)) :

recherche.resultat:
  path: '/resultat/{metier}/{position}'
  defaults:
    _title: 'resultat'
    _controller: '\Drupal\recherche\Controller\ResultatRechercheController::resultat'
    metier: ''
    position: ''
  requirements:
     _permission: 'access content'

And in my controller for get my parameters :

Class: ResultatRechercheController

 public function resultat($metier, $position)
    {

        kint($metier);
        kint($position);

        return array('#markup'=>t('la premiere spécialite est @specialite',array('@specialite'=>'test')));

    }

And the URL is clean :

  localhost:8888//monsite.com/resultat/{metier}/{position}


What is the difference between user_is_anonymous() and user_is_logged_in()? What is the difference between the two functions? When should one be used instead of the other?

The functions are essentially opposites.

The only real difference is the user_is_anonymous() function has an additional check for $GLOBALS['menu_admin'] to allow menu admins to be able to administer menu links that are visible to anonymous users only.

It's used by drupal_valid_path() as well as the menu_overview_form() function:

function drupal_valid_path($path, $dynamic_allowed = FALSE) {
  global $menu_admin;
  // We indicate that a menu administrator is running the menu access check.
  $menu_admin = TRUE;
  if ($path == '<front>' || url_is_external($path)) {
    $item = array('access' => TRUE);
  }
  elseif ($dynamic_allowed && preg_match('/\/\%/', $path)) {
    // Path is dynamic (ie 'user/%'), so check directly against menu_router table.
    if ($item = db_query("SELECT * FROM {menu_router} where path = :path", array(':path' => $path))->fetchAssoc()) {
      $item['link_path']  = $form_item['link_path'];
      $item['link_title'] = $form_item['link_title'];
      $item['external']   = FALSE;
      $item['options'] = '';
      _menu_link_translate($item);
    }
  }
  else {
    $item = menu_get_item($path);
  }
  $menu_admin = FALSE;
  return $item && $item['access'];
}


Relationship between node and taxonomy term using migrate_d2d_ui I used Migrate 7.x-2.6-rc1+30-dev and Migrate_d2d_ui 7.x-2.1-beta1 module to upgrade my "Drupal 6" website to D7, everything went fine but the node-to-taxonomy relation seems to have got lost. How to relink the relation in the imported data ?

Below is the snapshot from setting form:

This didn't work for me: https://drupal.org/node/2063203

If you're getting values from the d6 db, but it is not mapping properly you can likely use public function prepare($node, $row) {...} on your migrate object to map the taxonomy terms from the d6 site to the d7 version. Off the top of my head I don't know how that looks, but that is where I would start. prepare !


Access MailChimp forms I currently have a form that it is fully loaded from my Mailchimp Account. I configured it for display as a page using mailchimp configuration page (admin/config/services/mailchimp/signup). Then when I was trying to access it with no admin permissions I got Not authorized to access this page message.

Giving Access all Mailchimp Signup Pages permission to anonymous users fix this problem but it specify that have security implications and I think it is a wrong solution.

I searched all the drupal interface and was not able to find it on either side (Content, contact forms, etc...). This element it's only present on signup forms list (admin/config/services/mailchimp/signup) and there isn't any permissions configuration.

Recently found a FAQ from Drupal Mailchimp módule here
It says:

  Q: How do I create anonymous signup forms on the site as either a page
  or a block?

  A: Head to this path admin/config/services/mailchimp/signup/add, fill out the form and
  click on “Block”, “Page”, or both Display Modes.

  Block - ...

  Page - enter a path for which you’d
  like the signup form to appear, and click “Save”. In order to make
  SignUp pages available to anonymous users, head over to where
  permissions are assigned (admin/people/permissions), and check the
  appropriate boxes next to the permission marked “Access all Mailchimp
  Signup Pages.”

So this means that I should ignore that warning.


How to get a list of all Groups sorted according to latest comment created on any of the Group Content belonging to that Group? I wrote the following custom query to get a List of Groups sorted according to latest comment created on any of the Group Content belonging to that Group (not on the group itself) .

However this query does not return the list of Groups for which there is no Group Content OR any comment on any of Group Content is created.

SELECT DISTINCT   group_view.nid AS group_nid,
                  group_view.created_date AS group_created_date,
                  discussion.nid AS discussion_nid,
                  comment.created AS comment_created_date,
                  comment.created_date AS comment_created_date
  FROM `node` AS group_view
      LEFT JOIN `og_membership` AS group_map
          ON group_view.nid = group_map.gid
      LEFT JOIN `node` AS discussion
          ON group_map.etid = discussion.nid
             AND group_map.entity_type = 'node'
      LEFT JOIN `comment` AS comment
          ON discussion.nid = comment.nid
  WHERE group_view.type = 'group'
  ORDER BY comment.created DESC

What changes do I need to make in this query to include a list of Groups with no comments

I do not want to use views.

I have not tested a query as I don't have data to test.But I hope the following query will work for you.I am matching comment created date with fetched latest comment by using sub query.

SELECT DISTINCT   group_view.nid AS group_nid,
                      group_view.created_date AS group_created_date,
                      discussion.nid AS discussion_nid,
                      comment.created AS comment_created_date,
                      comment.created_date AS comment_created_date
      FROM `node` AS group_view
          LEFT JOIN `og_membership` AS group_map
              ON group_view.nid = group_map.gid
          LEFT JOIN `node` AS discussion
              ON group_map.etid = discussion.nid
                 AND group_map.entity_type = 'node'
          LEFT JOIN `comment` AS comment
              ON discussion.nid = comment.nid
      WHERE group_view.type = 'group' and (comment.created=SELECT max(c.created) AS latest
      FROM comment c
      WHERE  (c.nid = node.nid)
      GROUP BY c.cid)


Is it safe for me to use _taxonomy_title_get_title() implemented by a third-party module? I have installed the Taxonomy Title module 7.x-1.5 in order to change the grey content title on top of certain taxonomy pages. The module added a new field (Term page heading) where I add my custom titles. The title is changed as expected. Now I also need to use that same custom title in certain nodes, so I need to find out how to get the value added in that field.

After a look at the module code, I tried using _taxonomy_title_get_title($tid), which works. Is it safe for me to use this function?

Drupal adds a underscore to its function to mean they are for internal use only, and modules/themes should not depend upon them. For example, in Drupal 8, the theme() function was renamed _theme() as reported in theme() renamed to _theme() and should not be called directly, which also states:

  It has been renamed to _theme() and is for internal use only.

Then, it was removed.

Third-party modules follows the same naming convention: If the function name starts with an underscore, they don't want they use that function. This doesn't mean the function is necessarily going to be removed, but the maintainers could remove it at any time, even passing from version 7.x-1.5 to version 7.x-1.6.

So, if by safe you mean sure that the code I am writing will not need any change, then I would say no.
You could eventually write your own code that uses just safe functions made available from that module, using _taxonomy_title_get_title() as starting point; otherwise, you need to check your code is still working when updating that module. Depending on your specific use, you could also use tokens; the module defines [term:title] which is set using the function you are calling.

/**
 * Implements hook_tokens().
 */
function taxonomy_title_tokens($type, $tokens, array $data = array(), array $options = array()) {
  $replacements = array();
  $sanitize = !empty($options['sanitize']);

  if ($type == 'term' && !empty($data['term'])) {
    $term = $data['term'];

    foreach ($tokens as $name => $original) {
      switch ($name) {
        case 'title':
          $title = _taxonomy_title_get_title($term->tid);
          if ($title) {
            $replacements[$original] = ($sanitize) ? check_plain($title) : $title;
          }
          else {
            $replacements[$original] = $term->name;
          }
          break;
      }
    }
  }

  return $replacements;
}

See also Call to undefined function _taxonomy_title_get_title(); it is for the version 6.x of the module, but users are essentially saying that, passing from version 6x-1.3 to 6.x-1.4/6.x-1.5, they get an error about the function _taxonomy_title_get_title() being not defined. (In fact, it was renamed _taxonomy_title_get().) Since the development snapshot doesn't call _taxonomy_title_get_title(), I get they are talking of other code.


How to export menu per role permission in features module? I added custom permission in my menu using menu_per_role module. I want to export the permission configuration that I made in my menu. using features module my question is how can I export my menu permission configuration. is features module support exporting configuration came from menu_per_role module? I also tried to check it in strongarm but I can't see it.

I ended up using this module roles_for_menu this module exactly what I need, it allows me to export the configuration in features.

Features module support it.


Drupal 7: adding html (image) to view's exposed filters fields im having a little trouble theming the output of a view's exposed filter.

I have a node reference field, and in the exposed filter i want to show it as a checkbox list with, instead of the title of the referenced node, the image (that is a field, obvious).

Im doing the same thing for the node_edit form:

    // This function is called via #process fapi key
function _mytheme_theme_pittogrammi(&$element)
{
    $lang = isset($element['it']) ? 'it' : 'und';

    foreach($element[$lang]['#options'] AS $nid => $label)
    {
        $pittogramma = node_load($nid);
        $image_field = _dwork_field_get_value($pittogramma->field_image);

        $image = 'title .'" title="' . $pittogramma->title .'" />';

        $element[$lang]['#options'][$nid] = $image;

        $element[$lang][$nid] = array(
            '#label' => $image
        );
    }
    return $element;
}

and it works perfeclty; For the view_exposed_form i hat to make a little change in the function (becose the lang is not present), but is almost the same:

function _mymodule_theme_pittogrammi_view_form(&$element)
{
    foreach($element['#options'] AS $nid => $label)
    {
        $pittogramma = node_load($nid);
        $image_field = _dwork_field_get_value($pittogramma->field_image);

        $image = 'title .'" title="' . $pittogramma->title .'" />';

        $element['#options'][$nid] = $image;

        $element[$nid] = array(
            '#label' => $image
        );
    }
    return $element;
}

And this works somehow, but the problem is that the image HTML looks like is passed throught htmlspecialchars() or something like, and rendered as text.

Im wondering why and why only on view's exposed form...

How can i change this behavior?

Solved: I am using BEF module (Better Exposed Filters) that, in row 532 of better_exposed_filters.theme used to check_plain even the label.

Commenting that line do the trick, knowing that youre raping someone'else module (but this is the only way i found since there is no an option to dont check_plain the label)


How can I change the front-page title when front page is not /node? I changed the site's front page from /node to another page. However, now the title of the front page is page name | site name. To clear up any confusion, by "title," I mean the phrase entered between the HTML <title> tags.
I tried this SO answer, but it had no effect. How can I declaratively change the name of the site's main page?

You can use the Metatag module. It has a section for front page metatags, where you can set the title.


How to show a description when a select box item has been selected On my "node/add" form I have a "topic" taxonomy term field a user has to select. I would like to be able to display a description about a selected text next to the box, see red box in screenshot:

I'm sure there are CSS/javascript hacks out there, just wondering if there is a "Drupal way" for doing this?
Cheers

This isn't strictly theming, but the following works for me:

Put the following in a custom module:

function tax_desc_menu() {
  $items = array();

  $items['termdescription/%'] = array(
    'title' => 'Term description callback',
    'page callback' => 'tax_desc_get_description',
    'page arguments' => array(1),
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  );

  return $items;
}

function tax_desc_get_description($tid) {

  if (!is_numeric($tid)) {
    return drupal_json_output('Select a term');
  }

  $term = taxonomy_term_load($tid);

  $description = $term->description;

  return drupal_json_output($description);

}

This is simply a menu hook that calls a function.  You will be calling this menu link to get the description data for the taxonomy term.  The second function takes the term ID that will be passed in the ajax call, and gets the term object.  From that, it pulls the description set using the standard taxonomy term description.

Next, you'll need to add the following javascript and reference it in your module .info file:

(function($){
  Drupal.behaviors.taxdescGetDesc = {
    attach: function (context) {

      $(".page-node-add-article #edit-field-tags-und").after('
Select a term
');

      $(".page-node-add-article #edit-field-tags #edit-field-tags-und").click(function(){
        $.ajax({
          cache: false,
          type: 'POST',
          url: "/termdescription/" + $(this).val(),
          context: document.body,
          dataType: "json",
          success: function (json){
            $('#mycontainer').html(json)
          }
        })
      })
    }
  }
})(jQuery);

You'll probably want to change the ID's and classes that I've used, as I've just used a standard article type for this.

This Javascript will put a div with the ID of mycontainer below the select box (this can be styled/positioned with CSS so it matches your image).

when you click the select box, the term description will populate the div created earlier called mycontainer.

Just in case, your .info file will look like the following:

name = taxonomy description
description = taxonomy description from list

core = 7.x

scripts[] = tax_desc.js


Hook_form_alter for changing field labels doesn't work of user registration page Can anyone tell me why this isn't working (in the below code, or other factors preventing the insert by the hook)?   I don't get an error message or page, the field labels are simply not overwritten...

I created my own module with the following hook on Drupal 8.5.7:

function MYMODULE_form_alter(&$form, Drupal\Core\Form\FormStateInterface $form_state, $form_id){

  if ($form_id == 'user_register_form') {

    $form['field_user_first_name']['widget']['0']['#title'] = 'First Name';
    $form['field_user_last_name']['widget']['0']['#title'] = 'Last Name';
    $form['field_user_phone_number']['widget']['0']['#title'] = 'Phone Number';
    $form['field_user_country_of_residence']['widget']['0']['#title'] = 'Country (of residence)';
  }
}

Simple Solution just change ['0']['#title'] by [0]['value']['#title'].

/**
 * @param $form
 * @param \Drupal\Core\Form\FormStateInterface $form_state
 * @param $form_id
 */
function MYMODULE_form_alter(&$form, Drupal\Core\Form\FormStateInterface $form_state, $form_id){
    if ($form_id == 'user_register_form') {
        $form['field_user_first_name']['widget'][0]['value']['#title'] = 'First Name';
        $form['field_user_last_name']['widget'][0]['value']['#title'] = 'Last Name';
        $form['field_user_phone_number']['widget'][0]['value']['#title'] = 'Phone Number';
        $form['field_user_country_of_residence']['widget'][0]['value']['#title'] = 'Country (of residence)';
    }
}

This solution a little bit complicated.
After i test your code, i did some search, i found this Post say

  It is apparent that we modify any form in drupal by implementing hook_form_alter(). But there are cases when even the hook_form_alter() cannot offer a solution in altering the form fields.

I tried to use hook_element_info_alter as it suggested to alter fields.
In your case Here is the code bellow.

/**
* Implements hook_element_info_alter().
*/
function MYMODULE_element_info_alter(&$type) {
  if (isset($type['textfield'])) {
    $type['textfield']['#process'][] = 'MYMODULE_process_textfield';
  }
}

/**
* Process Callback Function
*
* Callback to process the User fields.
*/
function MYMODULE_process_textfield($element) {
  //- get the current route name
  $route_name = \Drupal::routeMatch()->getRouteName();
  if ($route_name == 'user.register' && isset($element['#array_parents'][0])) {
    switch ($element['#array_parents'][0]) {
      case 'field_user_first_name':
        $element['#title'] = 'New first name label';
        break;
      case 'field_user_last_name':
        $element['#title'] = 'New last name label';
        break;
      case 'field_user_phone_number':
        $element['#title'] = 'New phone numbe label';
        break;
      case 'field_user_country_of_residence':
        $element['#title'] = 'New country of residence label';
        break;
    }
  }
  return $element;
}

Note : all the four fields should be of type textfield Text (plain), otherwise you should add another process to other type, see the example in the article for password_confirm type.


How to stop Privatemsg showing user role in 'To' field With the module Privatemsg (v7.x-1.3) the 'To' field will show the username and then their role in brackets when composing a new message with the user id passed in the url:

/messages/new/567

I've searched the code but cannot seem to find where the role is being added so that I can disable it. Does anyone know?

Inside the privatemsg module, in hook_menu search for $items['messages/autocomplete'] this is where the menu defines the auto complete path.

Search for privatemsg_autocomplete function where the output is defined.

UPDATE:

To remove just the role, here is a patch for that. Here is a thread on drupal that shows how this has progressed https://drupal.org/node/1852746


Possible to use OR in contextual filter? I know with standard filters in Views I can select "AND "OR" etc. for multiple fields but I don't see this option for contextual filters.

I think there is a module for that, Views Contextual Filters OR.

  The module provides a views plugin which modify query to support OR
  conditions for contextual filters.

  How does it work?
  The handler is replaced in views which is used by
  default. A new option will appear in settings page query. If the
  option is enabled the query will be rewritten using operator OR.


Caption box on my slideshow jumps when you refresh cache When you access my site for the first time, the caption box on the slideshow starts lower by about 50px then adjusts itself to the correct position. Pressing Ctrl-F5 also recreates the problem.

Is there a way I can set a breakpoint within the CSS or Drupal so I can step through to find whats causing the problem? Also, any clues whats causing the problem?

thanks

website: www.terrafirmasouth.co.uk

This is a css problem, sorry. If I add position:absolute to my pagers block then the jumping stops, however, my pager block then appears under the text below the slide and the pagers cant be clicked on. I will follow up on stack overflow for css queries.


Tag/Label an image in an image field with Taxonomy terms? Is it possible to tag images as you upload them on to a node in a multiple values image field?

Image a node with a set of 3 images:
image_1.jpg (tagged with: red)
image_2.jpg (tagged with: blue)
image_3.jpg (tagged with: red)

And another node with 2 images:
image_A.jpg (tagged with: red)
image_B.jpg (tagged with: green)

What I'm aiming to do is to be able to pull all the images tagged with the tag "red" in a view.

RED IMAGES
image_1.jpg (tagged with: red)
image_3.jpg (tagged with: red)
image_A.jpg (tagged with: red)

Is there a module that performs this?
Images have to be uploaded into the image fields. They cant be uploaded as nodes.

I would suggest using a field collection for this.  This creates a collection of fields that you can add and do exactly what you are looking to do.


The site crash when add a server I'm trying to use Search_api_solr and search-api.
I install the required modules and run the solr server and create a core.
But when I'm trying to add a server to my drupal 8 site, an error appears
Solarium\Exception\UnexpectedValueException: Neither collection nor core set. in Solarium\Core\Client\Endpoint->getBaseUri() (line 299 of /var/www/html/vendor/solarium/solarium/src/Core/Client/Endpoint.php).

I try to change the following block in Endpoint.php file to my data but it's not working.

protected $options = [
        'scheme' => 'http',
        'host' => 'xx.xx.xx.x',
        'port' => 8983,
        'path' => '/solr/',
        'collection' => null,
        'core' => 'my_core',
        'timeout' => 5,
        'leader' => false,
    ];

also, should the host include the http:// or only the ip address?
However, I try all above with no luck.
Any advice. Thanks in advance.

Collection is required in solr configuration. You'll need to create a collection you want to use for your site. Create using below command or by user interface of solr, then use the same name for the collection.

  sudo su - solr -c "/opt/solr/bin/solr create -c COLLECTION_NAME -n
  data_driven_schema_configs" // Only for ubuntu

Replace COLLECTION_NAME with the name of your collection you want.


Drupal Database Relationships I would like to know why there are no relationships been built between tables in Drupal Database.

I was just going through the Drupal database structure and wondering why haven't any relationship been created.

any explanation would be appreciated. one of the main thing that i was reminded was that, mysql database engines could be a limitation.

Quite a vast topic among many reasons:

MyISAM doesn't support foreigns keys and Drupal used this as a default engine until D7 (which now use InnoDB as default if available).
Schema now support foreign keys so you can benefit from this in documentation.
Enforcing FK in Drupal would be quite a challenge (Damien Tournoud - one of Drupal most prolific core contributor - stated: Drupal is far from being able to use foreign keys properly).


How to limit the maximum length of the title of a node? I have a content type with a title that shouldn't be more then 10 characters long. This title field is read only.

What is the recommended way to limit the length of that title to 10 long?

Try Maxlength module to do this.

  Maxlength allows you to set maximum length of any field on any form
  making use of the form API. This includes fields created using the UI.
  (Example: any text field on a node) In D6 Maxlength allows you to set
  maximum lengths to the body, title and CCK textfields of any content
  type (node).

  When the maximum length is enforced for a field, while editing content
  of that type some Java Script will countdown how many characters are
  left, also if the Javascript is turned off, it falls back to form API
  validation.

Automatic Nodetitles : I haven't try this. Try once, hope this module solve your issue.

  "auto_nodetitle" is a small and efficient module that allows hiding of
  the content title field in the form. To prevent empty content title
  fields one can configure it to generate the title by a given pattern.


Blocks not visible when I log out In Administration -> Structure -> Blocks I have defined Search box region with search box block and Left sidebar region with navigation block. These blocks are visible when I'm logged in but when I log out the blocks disappear?

Do you where is the fault?

I have an idea where could be the problem. There are two files with page template - page.tpl.php and page--front.tpl.php.

thank you

You need to grant permission to search content. Peoples > permission > Use search checkbox


Does anyone knows a good menu module? I'm looking for a menu module which would show a menu tree like:

Menu level 1 (Container)
    |-------Menu level 2
    |-------Menu level 2
    |-------Menu level 2
    |-------Menu level 2
    |-------Menu level 2
Menu level 1 (container)
    |-------Menu level 2
    |-------Menu level 2
Menu level 1
Menu level 1 (container)
    |-------Menu level 2
    |-------Menu level 2
    |-------Menu level 2
Menu level 1

It'd be the best if it would be dynamic, but that doesn't really a must.
So anyone knows a Drupal 7 module which is capable of doing this?

Superfish is pretty configurable. You can use classic drop downs or try a mega menu


How do I programmatically log in a user with a POST request? Do anyone have a working REST Login on Drupal 8?
This is what I tried.
POST /user/login HTTP/1.1
Host: 8.d8.local
Content-Type: application/x-www-form-urlencoded
Accept-Encoding: http://nikhilmohan.in
Cache-Control: no-cache

name=test&pass=password&form_id=user_login_form

It returns me HTML instead of JSON.

Staring from 8.2, Drupal supports json endpoints for Cookie authentication. You don't need to post the form anymore

curl --header "Content-type: application/json" --request POST \
  --data '{"name":"admin", "pass":"admin"}' \
http://drupal.d8/user/login?_format=json

Output will look like

  {"current_user":{"uid":"1","roles":["authenticated","administrator"],"name":"admin"},"csrf_token":"wBr9ldleaUhmP4CgVh7PiyyxgNn_ig8GgAan9-Ul3Lg","logout_token":"tEulBvihW1SUkrnbCERWmK2jr1JEN_mRAQIdNNhhIDc"}

Change record: https://www.drupal.org/node/2720655

Other authentication methods: https://www.drupal.org/docs/8/core/modules/rest/using-other-authentication-protocols


Make a field theme function work on empty fields I am using a field theme function in my template.php file to override a field.

Everything works fine, but the function only seems to run if my field has content. If my field is empty, it does not run. How can I get the function to run all the time?

Here is the code I am using. The function checks a value in theme_settings.php and then alters the output of the field accordingly.

function THEMENAME_field__field_call_to_action_button(&$variables) {
 // kpr($variables);

    //Load the value of CTA to determin which text to use
    $field_cta_option = field_get_items('node', $variables['element']['#object'], 'field_call_to_action_setting');
        $cta_option = $field_cta_option[0]['value'];

    //Assign theme/node settings to variables for easy access
    $cta_link_main      = theme_get_setting('cta_main_node');
    $cta_link_secondary = theme_get_setting('cta_secondary_node');
    $cta_link_custom    = theme_get_setting('cta_main_node');
    $cta_text_main      = theme_get_setting('cta_main_button_text');
    $cta_text_secondary = theme_get_setting('cta_secondary_button_text');
    $cta_text_custom    = $variables['#items'][0]['value'];
    switch ($cta_option) {
        case 'cta_main':
            return ctabutton($cta_link_main, $cta_text_main);
            break;
        case 'cta_secondary':
            return ctabutton($cta_link_secondary, $cta_text_secondary);
            break;
        case 'cta_custom':
            return ctabutton($cta_link_custom, $cta_text_custom);
            break;
        case 'cta_none':
            return "";
            break;
    }
}

You may want to change the way you are theming the information, for example by overriding node.tpl.php, but if you really want the field function to be run even when the field is empty, you can do it by modifying the node before it gets displayed:

function THEMENAME_preprocess_node(&$variables) {
  if($variables['type'] == 'mynodetype' && !isset($variables['content']['FIELD'])) {
      $variables['content']['body'] = array(
      '#theme' => 'field',
      '#field_type' => 'FIELDTYPE',
      '#field_name' => 'FIELDNAME',
      '#items' => array(),
      '#bundle' => 'mynodetype',
      '#label_display' => 'hidden',
      '#entity_type' => 'node');
  }
}

This will make sure the field is passed to your theme field function, even if it is empty.

To get the values to use for FIELDNAME and FIELDTYPE you can print out the contents of $variables['content'] on a page where the field is not empty.

Again, it might be better to override the theme of the entire node in this situation.


Add class to table in render array I am looking to add a class to a table that I am creating.

I have the code:

$build['table'] = array(
  '#theme' => 'table',
  '#header' => $header,
  '#rows' => $rows,
);

I want to add a class to this table.  I don't have any templates for the view of this table, so I don't really want to have to create a tpl.php for it, but I will if I have too.

Here is description of all parameters that you can pass to theme_table() function http://api.drupal.org/api/drupal/includes%21theme.inc/function/theme_table/7

To add classes for table tag use this code:

$build['table'] = array(
  '#theme' => 'table',
  '#header' => $header,
  '#rows' => $rows,
  '#attributes' => array (
    'class' => array('class name goes here'),
  ),
);


Show whole taxonomy tree starting from current term I'm trying to show taxonomy tree starting from current term.
Like this when you are in taxonomy term1 page.

  -term1 (this is the term1 page where we are now)
  --term2
  --term3
  ---term4
  ----term5
  ----term6
  -----term7
  -----term8

And if we are for example term4 page then it will show starting from term4:

  ---term4
  ----term5
  ----term6
  -----term7
  -----term8

I have used Views Tree to but I have not found proper way to "filter" to show right terms when you are for example in term4 page.

All I can get is to show first child level like:

  --term1
  ---term2
  ---term3

It should show whole tree starting from current term - as deep as the tree goes.

Take a look at Taxonomy Menu Block Module

  Taxonomy Menu Block allows you to make blocks containing unordered
  lists that represent the structure of your vocabularies, creating a
  menu out of your taxonomies (without using Drupal's menu system).


Node edit form with entity reference - show more than just the title in the autocomplete box I have three content types: application, organization, and organization_note. Application has an entity reference to organization and organization has an entity reference to organization note.

The application edit page has an autocomplete field for organization. When a user selects an organization which has a note, I would like the display to be different somehow, ideally a reminder to check the organization's notes.

This question is very similar to this one (unanswered).

I'm at a loss here, and I don't really even know if this is possible. How would I go about doing this? (This is Drupal 7, by the way.)

You can do this by creating an entity reference view.

Firstly, create a new view that displays the content type 'organization'. Do not add a page, but rather add an 'Entity Reference' display.

Your view should now have a format of 'Entity Reference list'. Now add a relationship to organization_note, and then add the fields that you would like to see in the autocomplete list. When that is done click on settings in 'format', and select the field that you want to search on when typing in the autocomplete. This normally would be title. You can also rewrite the field values to your liking as you would probably need to for your use case, though I would leave title standard.

Now go back to the field settings for 'application', and edit the settings for the entity reference field to organization. In the 'Mode' for the 'Entity Selection' section, select 'Views: Filter by an entity reference view'. This will open a new select from which you select the view you created above.


Module weight not being respected in order of execution Trying to do something fairly simple, using the Panopoly distro.

Basically, I'm trying to implement hook_wysiwyg_editor_settings_alter(). Within the Panopoly distro, the panopoly_wysiwyg module also implements the hook.

So if I have this structure,

/profiles/panopoly/modules/panopoly/panopoly_wysiwyg
/sites/all/modules/contrib/wysiwyg_button_order
/sites/all/modules/custom/my_module

No matter how I set the module weights, the hook fires in the order

sites/all/modules/contrib
sites/all/modules/custom
profiles/panopoly/modules/panopoly

Within the directory, execution is in alphabetical order. I've tested this by moving my_module into sites/all/modules/contrib and profiles/panopoly/modules/panopoly.

Is this a bug in Drupal? Am I missing something? I've tried to use hook_module_implements_alter() but that doesn't fire at all.

If I call modules_list(), it shows the modules in the expected order, but the hook doesn't fire in that order.

Any ideas?

The module weight can be updated in multiple ways

1) Using the Module Weight module which gives you an option to change the order of modules. This module allows only reordering of non core modules
2) Directly updating the weight field in the table "system". Refer to this link for more details.

Lesser the weight the module floats on the list and gets executed early


How to restrict moderators to only access a limited set of users? I have 2 user roles: Moderator and Company. Each Moderator has a set of companies; for example:

Moderator A owns Company d, e, anf f
Moderator B own Company g, h, and i

When moderator A logs in, I want that moderator can only see Company d, e, and f. I want to use a view.

How can I achieve this? How can I restrict each moderator to see those companies (which, I repeat, are user accounts) they own?

If moderators are creating the Company nodes themselves, you will probably be best off with the Content Access module.

If Company nodes are created by administrators, you could use the Node access user reference field to reference the moderators. They would then get the necessary view permissions.

Let me know if I missed your question.


How to modify the subfields of a custom field in hook presave I have a custom field in a custom module that consists of 4 varchar type values. Each of these subfields are called 'prefix', 'suffix', 'body' and 'header'.
In the hook presave, I want to modify only one of them, 'prefix', however, I can't do it:
function custom_field_entity_presave(Drupal\Core\Entity\EntityInterface $entity) {
  switch ($entity->bundle()) {
    case 'custom_object':
      //This seems to modify all de field instead only the subfield 'prefix'
      $entity->set('field_multifield', ['prefix' => '55555']);
      break;
  }
}

As @sonfd commented you could get the field content as array:
$values = $entity->get('field_multifield')->getValue();

modify this array
$values[0]['prefix'] = '55555';

and then replace the entire field content:
$entity->set('field_multifield', $values);

Much easier though would be accessing a single property directly:
$entity->field_multifield->prefix = '55555';


How to allow users to edit a specific field of content? I have a taxonomy list connected with a content type. I want to give all authenticated users to access the content edit page but only see and access the taxonomy field section so users can participate in making the site more organized and accurate.

Is there a way to only show 1 field to users and allow them to edit just that one field?
If so, how do i show a link on the content page to the edit page? (example: "Click here to edit/add tags"  - This link would then go to the /node/2343/edit link)

My idea comes from many video sharing sites where people can add/edit "categories" or "tags" if the user has permission to do so. These sites usually have a little "+" symbol next to the categories which then opens the category check list for that piece of content for editing.

You can set permissions for fields who can edit or not
Please have a look into this module

Field Permissions

  The Field Permissions module allows site administrators to set field-level permissions to edit, view and create fields on any entity.


views... display random node on click I'm trying to create a view that's like a randomizer like this: http://www.celebritynetworth.com/richest-celebrities/snooki-net-worth/.

I'm not sure out I could activate the view on a click of a button.  Then the view would have to display totally random nodes from the terms I've filtered it to display.  Would anyone know how I could do this?  Thank you.

First, it is important to note that true randomizing is an expensive operation.  The method involving Views will work with little effort, but if the site experiences very heavy traffic it could tax your database server to a point where it collapses.

The easiest way to accomplish this would be to create a View displayed as a block and filter by the appropriate content type.  Use a "Global: Random" sort to randomize the content and configure the paging options to show only one result.  Make sure you are displaying "fields" and not full nodes, then add the node title as a field.  It should be configured by default to link to its content, but verify this in the field's settings.  Instead of displaying the title of the page, you will want to display the text "Random" which can be accomplished by using the "Rewrite the output of this field" setting.  Then you can place the block where you want and style the link via CSS to look like a button.  Clicking on the button will then take you to a seemingly random node.

For a more scalable solution, you might want to move away from Views and leverage JavaScript for the randomizing.  On the backend you would queue up a handful of nodes and have JavaScript decide which one to display, thus taking the randomizing task off of the database.  It will be limited to the handful of nodes you pre-select, but your database will thank you in the long run.


What is a variant in Page Manager? I am trying to follow this tutorial, but it does not explain the concept of variant very clearly. It does not provide a definition of it.

Can someone clarify this concept in plain English? What are the practical cases where you would use variants?

I've never been forced to define it before, but here's an attempt at it.

"A variant is a specific response to a request on a Page", in the Page manager. Mostly, using Panels, this involves the rendering of a node or other full page, but not always.

While there are some similarities to "Views displays", unlike Displays, Variants have no inheritance between each other. All variants on any particular Page has the same basic access rules if any, and starts of with whatever context-objects that Page manager derives from the URL, but are not aware of eachother in any way. Based on selection rules, they are evaluated from top to bottom. The first selection rule to return TRUE, gets picked.

A common example is to separate two different content/node-types from each other, allowing you to render them entirely differently. Since each variant may pick its own layout, and place fields/forms/etc in an arbitrary way, the "Article" and "Blog" types may look entirely different. In this case the variants would correspond to node-article.tpl.php and node-blog.tpl.php.

There are various other "Responders" available for Variants that don't involve the use of Panels, such as Contextual administration and plain HTTP Response codes, but I believe this answer is long enough as it is.


How to list nodes with at least one field empty? Is there any module or built-in function to check if all the node fields are filled with some values, and list nodes that fails this check?

EDIT: In short, I just want to get the list of nodes having any of their field empty.

Use Views module.

Create a view, then add a filters  Content: field_name (empty) - one for each field. Change operator from AND to OR and done, you have a list of nodes with at least one field empty.


Where is the $content of a page build? I would like to add something to my $content variable to add on my node template file, but where is this variable composed? I assume it's in the template.php file but what specific function composes the content of the $content variable?

If you are referring to the $content variable that is available in node.tpl.php, its value is set in template_preprocess_node() from the following code:

  // Helpful $content variable for templates.
  $variables += array('content' => array());
  foreach (element_children($variables['elements']) as $key) {
    $variables['content'][$key] = $variables['elements'][$key];
  }

$variables['content'] is then passed to field_attach_preprocess().

  // Make the field variables available with the appropriate language.
  field_attach_preprocess('node', $node, $variables['content'], $variables);

To alter the content of the $content variable, you can implement hook_preprocess_node() (in a theme, or a module), or hook_field_attach_preprocess_alter().

Remember that what in a template file is $content, in other places is $variables['content'].


Obfuscation or e-mail spam protection for content displayed through Views module Currently, SpamSpan seems to work well for anything outside of Views. Having a hard time finding a solution for e-mails that are displayed through the Views module.

Any help would be very much appreciated.

SpamSpan can do that for views too. You need to select te SpamSpan formatter on your display settings of the field.


How to generate url with language code in drupal7? Is there any drupal function to return the url with currently used language.
Like: example.com/en

You can get the URL by using following code

global $language ;
$lang_name = $language->language ;

$url_current = $GLOBALS['base_url']/$lang_name;


Taxonomy and Views - Creating a view based off of user selection Been working with Drupal for a few weeks, and I have a question:

I have a large amount of content for content type X. I have built a view that returns certain fields from X nodes. Is there a way to build a user interface that will allow users to see all taxonomy tags for X and select a tag and then use that tag as a filter for the view?

For example, a user wants to see all results that are tagged "SEO." They will then see the views results for all nodes tagged with "SEO."

There are a few ways to accomplish this; i'll offer up my easy answer.

You can show all of the nodes associated with a taxonomy tag by adding the "Taxonomy: Term" filter (select the taxonomy term ID filter). Select your relevant vocabulary, and then select 'dropdown' for your Selection Type.

Click 'Expose' to show a dropdown box to your users. When a user selects a tag from your dropdown, your results will be filtered according on the Operator you have chosen.


How can you remove the edit lock on a node? When I try to save a node I am working on I get this error message.

  The content on this page has either been modified by another user, or you have already submitted modifications using this form. As a result, your changes cannot be saved.

What is causing that issue and how can I remove the lock?

Did you use the back button to get to your edit page? Have you tried manually going to the node and clicking the edit tab again to see if it reoccurs?

This message is caused when either (1) two users access the edit page and one user saves changes before the other user gets a chance or (2) when a user edits content, saves it, and clicks the back button to get back to the edit page.

https://obrienmedia.co.uk/kb/drupal-website-management/avoiding-the-the-content-on-this-page-has-either-been-modified-by

Are there other users signed in? When all else fails (or rather the first step of troubleshooting always) Flush all cache. Clear your browser cache. Close your browser out. Re-open your browser. Attempt to recreate problem. Is it still happening?


Author of question flags only nodes that are answer to his question (node reference) I have 2 node types - questions as parents and answers as referencing nodes. I would like to display flags only for nodes created as an answer to a given question. This should be only selectable by the author, not everyone.(same as stackoverflow best answer) So far I found out that I can manually place in node-answer.tpl.php the link using:

<?php print flag_create_link('select_answer', $node->nid); ?>

This will print the flag on every answer node, but I would like it to be selectable only by the author of this particular question. (basically it is the same functionality as stackoverflow - author can select best answer) There is an API function flag_create_link($flag_name, $content_id), so I need to set $content_id to point to all referenced answers for a given question.

ANy idea how can I do it? Any advice appreciated.

Are they 2 nodes or 2 node types? If types, just create 2 separate .tpl files for them (node--type1.tpl.php and node--type2.tpl.php).

If they are the same content type, you can check that the node reference exists inside node.tpl.php like so:

Edit: code below now only prints the link if the current user is also the author of the node.

global $user;
if ($user->uid == $node->uid && isset($node->field_my_reference_field_name[LANGUAGE_NONE)) {
  print flag_create_link('select_answer', $node->nid);
}


How to retain  tag in HTML output when added in a Views Fields? I need to re-write some fields in my Views to output certain format for my  tag. Since the new format that needs to be written isn't actually accessible, I would need to include  tag for the original  tag.

Example

Accessible, original format

Non-Accessible, new format

<img src="/images/myimage.jpg"

Question

How to make it so that the  tag is retained and not stripped?

Please kindly share your detailed solutions in a way that a Drupal beginner like me can understand. Thank you!

Had to use Views PHP module for the <noscript> tag to be retained. Even so, had to do some workaround to make it work >.<


Group similar nodes in a view I have a group of universities that have a director.  However, BYU has 2 directors.  I try and "group multiple values" and turn on distinct in the "basic settings", but then fields for only one director appear while both director names appear.

Basically I want the same layout as below, but Tracy and Carl to be on the same row with their contact information.

I've tried for a few hours and googled for another few hours... Thanks!

http://i.stack.imgur.com/awWQ4.jpg
http://i.stack.imgur.com/TdFxS.jpg

For those that might have a similar issue (having one node with 2 relationships and all other nodes in the view have 1 relationship to display) I found that by displaying the node teaser instead of just the field, I can get the information I need.


How to print a view in node.tpl.php only if it's not empty Views can be printed in tpl.php files with this code:

<?php print views_embed_view('myview','block_1'); ?>

However, if that view is empty, the view block code will be printed anyway:

Is it possible to check if the view has any results first and then print it if it does? E. g.:

<?php if ($view_myview,block_1): ?>
<?php print views_embed_view('myview','block_1'); ?>
<?php endif; ?>

You can check it using the below code

<?php
$viewName = 'myview';
$displayid = 'block_1';

$view = views_get_view($viewName,$displayid);
$view->execute();
$reviewCount = count($view->result); //It will return number of results
if($reviewCount>0){
print views_embed_view($viewName,$displayid);
}
?>

Hope it will help.


Node and Webform - Open, Close, Scheduled and Limit per source entity I use Drupal 8 with webform. I have a content type called "Event" which has several fields of simple type and reference type for other content types.

In addition it has a field entity reference that points to a webform named "Team".

In "Event" in creation and edit mode, using the field_permissions-8.x-1.0-rc2 module, I prevent access to authenticated users,
because the default aspect is too complex for users who create content with the "Event" content type.

Among other things, if I do not prevent these settings, there is the possibility of changing the content type, which I would definitely not want.

For this reason I would like to link some simple fields of the "Event" content type to the "Team" webform.

Status (open, closed, scheduled)
Open (date and time)
Closed (date and time)
Max submissions (Total submissions limit per source entity)

Can anyone suggest me how to do it?
Can it be done with Tokens?
Should you use a Hook?
I searched the net but I didn't find anything like that.

The Webform module includes the 'Webform Demo: Event Registration System' module which shows how to pass field related tokens from a Webform 'event' node to a webform submission.


Expiring roles for users? I have created few user roles and one of them should be an expiring role, which would be active only for a period of time (something like paid subscription - if user pay for new period of time, the account becomes fully active again). I know of Role Expire, but I'm not sure it's the right think - it wasn't updated in long time and first activating the module instantly created few error messages. Similiar thing (probably) with Notifications.

Any hints how to achieve it? Use one of these modules? Or is there something more I couldn't find so far?

One way to do this would be using rules.

Rules allow you to execute some rules/action sometime in the future.

See http://dev.nodeone.se/node/1032 shows a great similar example.


Integrating Drupal and Non-Drupal Site Content I'm on a project to build some interactive data visualizations in D3. At no time during the discussion phase with the client did they mention the site had to be in Drupal.

We've now developed a draft site, and my team builds sites with just HTML, CSS and JavaScript, and no one has experience with Drupal. I know it's technically possible to implement what we've done in Drupal, but way beyond the scope of what was agreed upon.

The client seems open to having a launch page in Drupal that goes to the non-Drupal site with the fancy data viz stuff, but I'm not really sure how to go about this. Any recommendations?

All I can think of right now is just to have bunch of links back and forth between the two platforms, but seems kludgy.

Hard to say from your post if there is any real content management involved here, but if so - if Drupal is a requirement and your expertise is in JS - maybe look at a decoupled approach?

... in Headless Drupal, the visitor will see pages created with Javascript frameworks such as Angular.js or Backbone.js. They will not see a traditional Drupal theme. That's where the "Headless" name comes from: Drupal's head / theme is missing.
In this situation, Drupal is mainly used as store for data that is then read by the framework. The normal Drupal interface is still used by users to enter the content that will appear on the website.

Source: What is Headless Drupal? (OSTraining)


Limited fields at registration time and full profile after logged in I want to display limited fields at registration time say username email and password
And when user get registered then he can edit his profile with rest of the fields like Phone no., Address, Date of birth etc.

I tried adding field in admin/config/people
But that fields are visible at the time of registration.

How can I do that any help....
I am using drupal 7

You can do this without installing another module. It's good practice to avoid installing additional modules if you don't have to.

1) Go to the Manage Fields screen for user accounts at admin/config/people/accounts/fields

2) Edit the fields you want to hide/display from the user registration form. There is a setting at the top of the form called "Display on User Registration Form". View the attached screenshot for example.

3) If a field is marked as "required", it has to be displayed on the user registration form.

Certain form fields on the user registration form are not managed through the "Manage Fields" screen. So they can't be changed without getting in to modules. These include username, password, and a few others depending on your set up. But fields that you add yourself, like phone number, address, etc., can be edited.


How do I override the "This image has been removed" message? I'm using Drupal 8.0.0-beta10. I just tried to add a new basic page node that contains an image hosted in an external website: While it's showing up in the preview, the image isn't showing up once the node is published; when I hover over the broken image, it shows the following message.

This image has been removed. For security reasons, only images from the local domain are allowed.

How do I override this?

First, you need to know which input text filter you have enabled where the images are not showing. For the sake of this answer, let's say it's the "Basic HTML" input filter.

Go to the configuration for this input filter, such as /admin/config/content/formats/manage/basic_html

Scroll down to "Enabled Filters" and look for:

"Restrict images to this site"
Disallows usage of  tag sources that are not hosted on this site by replacing them with a placeholder image.

If you can not view externally-hosted images, it is likely this filter is enabled. Simply disable this filter.


How to get batch ID? I'm running some really long batch process. So in case user navigates away from the batch progress page, I'd like to be able to give him a link that leads back to that page. How can I get the batch ID needed for the batch processing page?

Knowing that batch processing url is something like http://example.com/batch?op=start&id=183 so in theory I could look for the $_GET['id'] inside my batch process function and store that in a session variable but it seems really ugly. Yet I didn't find any way to get the id of the batch that I just started.

It would be really nice if batch_set() would return batch id or would just add it to the batch definition array.

After batch_set(). Use

$batch =& batch_get();

This contains the information you need.

But I'm not sure you will be able to resume.


Feeds: How to import content from multiple xml files I have around 100 xml files. Each xml file contains a single item.

I have created a feeds importer which is working fine for single xml file.

But I don't know if feeds can work with multiple xml files?

Something like loop on the files and import content from each file?

Is it possible with feeds? As I didn't find anything useful.

D7

You can import a series of files by using the File upload fetcher and enabling the option "Supply path to file or directory directly" on the fetcher settings.

Steps:

Select the File upload fetcher, enable the option "Supply path to file or directory directly".

Store the XML files to import in the public or private directory. On Administration > Configuration > Media > File system (/admin/config/media/file-system) you can see which paths are configured for the public or private file system.
On the import form, enter the path to the directory with XML files. If you placed these for example in a folder called "mydir" on the public file system, enter public://mydir.

Public file system

Import form

D8

In the D8 version of Feeds you would select the Directory fetcher. The next steps would be similar as for the D7 version of Feeds.


How to controll rss feed in D7? Could anyone please tell me that how to control RSS feed in D7, because even without my knowledge D7 has created a RSS feed for my site.eg http://wwww.mysite.com/rss.xml

Even though in that feed my page contents are not selected but some un-nessaary items are selected like News letter, Poll and image jCarousel details. I'm 100% sure that I didn't select these items to generate feed but I don't understand how get it involved.

Also if I want to select the required page content link to display on the RSS feed how can I do that ?

To default RSS feed page goes for example every node with promote to front page flag set to true.

You can use Views to create your own, highly configurable RSS feeds. If you want even more control you can use this module https://drupal.org/project/views_rss.

You can override default RSS feed with a Views one too


Delete "permanent" file when it has 0 uses Files that are "used in 0 places" (viewable at /admin/content/files) are not being deleted automatically by cron. They also show a status of permanent.
How do I allow these files to be deleted by cron, or if not possible is there another way?

Prior to 8.4.x this was the default behavior, but a number of issues with file reference counting meant it was possible for files to get deleted prematurely (and possibly also for stale files to linger, though that's not so important). In 8.4.x the default behavior was changed. See Files that have no remaining usages are no longer deleted by default.
For completion, to answer the question it's possible to change back to the old behaviour by setting make_unused_managed_files_temporary to true in file.settings. It's clearly not recommended (that's why core doesn't use it anymore). See Dealing with unexpected file deletion due to incorrect file usage to track progress on file reference tracking.


Seeking an approach to maintain a drupal site from a mobile platform I have a client who needs to update their drupal site almost exclusively from their iPhone and iPad. They need to be able to upload images from iOS Photos. I have some ideas on how to approach, but I'm wondering if anybody in the community has encountered this situation and can suggest a combination of theme & modules that will help me get most of the way there.
thanks

I don't know about the qualitiy of this app, but could

Drupad - Drupal on the go (iPhone/iPad App)

help you?

App description:

Features for webmaster

Manage any number of websites
Create and edit content (CCK, Fields API support)
Search and edit user accounts
Read, post, moderate comments
Moderate your content
Mollom™ support
Promote, sticky, publish, unpublish nodes
Manage your users, send them email etc.
Gravatar™ fallback for User's picture
Drag to refresh and to load more content
Built-in web browser
Optimized to be fast in 3G or Wifi