RouteNotFoundException thrown when trying to reroute I am converting a Drupal 7 module to Drupal 8. The purpose of this module is to have shorter URLs which can be shared, as an alternative of /node/123 the module should send people typing /n/123 to the same content.

I feel like I am pretty close to competion but there is 1 more issue.
When I try using the 'littlurl' I get this error Symfony\Component\Routing\Exception\RouteNotFoundException: Route "node" does not exist. in Drupal\Core\Routing\RouteProvider->getRouteByName() (line 187 of C:\Users\SAMUEL\Sites\devdesktop\Module3\core\lib\Drupal\Core\Routing\RouteProvider.php).

routing.yml

littlurl.node:
  path: /n/{nodeid}
  defaults:
    _controller: '\Drupal\littlurl\Controller\DefaultController::nodeForward'
  requirements:
    _permission: 'access content'

littlurl.user:
  path: /u/{userid}
  defaults:
    _controller: '\Drupal\littlurl\Controller\DefaultController::userForward'
  requirements:
    _permission: 'access content'

littlurl.taxonomy:
  path: /t/{taxid}
  defaults:
    _controller: '\Drupal\littlurl\Controller\DefaultController::taxonomyForward'
  requirements:
    _permission: 'access content'

controller.php file

<?php /**
 * @file
 * Contains \Drupal\littlurl\Controller\DefaultController.
 */

namespace Drupal\littlurl\Controller;

use Drupal\Core\Controller\ControllerBase;
use \Symfony\Component\HttpFoundation\RedirectResponse;
/*use Drupal\Core\Session\AccountInterface;
use Drupal\node\NodeInterface;*/

/**
 * Default controller for the littlurl module.
 */
class DefaultController extends ControllerBase {

  public function nodeForward($nodeid) {
    $route_parameters[0] = $nodeid;
    $options['absolute'] = TRUE;
    $url = $this->url("node", $route_parameters, $options);
    $response = new RedirectResponse($url);
    $response->send();
  }

  public function userForward($userid) {
    $route_parameters[0] = $userid;
    $options['absolute'] = TRUE;
    $url = $this->url("user", $route_parameters, $options);
    $response = new RedirectResponse($url);
    $response->send();
  }

  public function taxonomyForward($taxid) {
    $route_parameters[0] = $taxid;
    $options['absolute'] = TRUE;
    $url = $this->url("taxonomy", $route_parameters, $options);
    $response = new RedirectResponse($url);
    $response->send();
  }

}

These are the routes for content entities in a drupal standard install:

 entity.block_content.canonical                        /block/{block_content}
 entity.comment.canonical                              /comment/{comment}
 entity.contact_form.canonical                         /contact/{contact_form}
 entity.menu_link_content.canonical                    /admin/structure/menu/item/{menu_link_content}/edit
 entity.node.canonical                                 /node/{node}
 entity.taxonomy_term.canonical                        /taxonomy/term/{taxonomy_term}
 entity.user.canonical                                 /user/{user}

In this list the route parameter names are in {}. Put the parameter name as key in an array:

$route_parameters = ['node' => $nodeid];

Don't send the response, return it:

return $response;


Passing arbitrary data into a node prior to preprocessing I am looking for a way of passing arbitrary data though node_view() to a preprocess function.

I am using the following code.

  $node = node_load(1);
  $node->mycustomdata = 'mydata'; // This is the data I want passed through.
  return node_view($node,  'teaser');

I want mycustomdata to be available to me inside my preprocess function so I can add it as a template variable.

function MYMODULE_preprocess_node(&$variables) {
  $node = $variables['node'];
  $variables['mycustomdata'] = $node->mycustomdata; //  Here is where I want to access the data.
}

How can I achieve this?

Node's in D8 work differently to D7. in D7 node was a stdClass object - basically used in the same way an array was assign a value to a key ($node->value). In D8 Node's are proper objects and can't do the same key/value. Instead, how about creating a field on the node and assigning the value to the field, save the node and then view it?


D8 Commerce - Non-orderable product What's the best way to configure some products so that they are not on sale .. i.e not show the price or add to cart button without creating a new product type?

Ideas...

1) create custom config entity like "products_not_on_sale"

2) Alter node view to hide the fields if referenced in above ^

--- or ---

1) add new field of type bool to say item on sale or not.

2) alter node view to hide fields if value is checked.


How to show friendly url when using Facets search? I installed the commerce_kickstart distribution. Its products pages shows facets search blocks to filter the products.

When using these filters the url change to a not friendly url. How can change this? How to show the taxonomies terms names instead.

Look my capture below:

I mean to change this:

http://localhost/commerce_kickstart/es/products?f[0]=field_collection%3A81

to something like

http://localhost/commerce_kickstart/es/products/field_collection/cds

I was looking for the same thing yesterday and came across Facet API Pretty Paths

  Enables pretty paths for searches with Facet API. You will likely use this module in combination with either Search API or Apache Solr Search Integration.

I haven't had a chance to try it yet but looks promising...


How to create a quote request form? I'm building a Drupal site that uses nodes to display a number of high value products. There are no e-commerce features due to the high value of the products being offered for sale, but the client wants a quote form on each product (node) page so that a potential buyer can enter some brief information and click to send a quote request for the item that they are viewing.

To make it clear, I have a content type called "Product", and I want this quote request form to be on each page and pre-loaded with the name of the product that that page is listing... it's not important whether the form is embedded in the node itself or displayed in a block, but it is important that the name of the product be preloaded in the form.

Following the form submission, ideally it would send an email to the website contact address.

I've considered using the entity form module and embedding the option to select a form in a node, but I don't want the client to have to manually create a form for each node.

Any ideas about how to create this functionality?

Entity Forms are, IMO, a long shot.

1. Webform module

You can use Webform module, and add an Option list (HTML select list) field to the webform, and autopopulate it with a URL parameter. Webform module supports populating the field value automatically from any $_GET, $_COOKIE, or $_SERVER value.

For the select list values, you can use a View to build the list of Product nodes.

2.  Entity Forms

Since you already have an Entity Form, you can do it with the traditional field approach.
Similar to the webform's select lists, you can create a View to list all Product nodes. Entity Reference module supports Option (radio, select, checkboxes) field type, with the options fetched from a View. You can use Entity Reference Prepopulate module to populate the Product node from a URL parameter.

3.  Custom module

Either way above, you will have to use some modules. If you are OK to create a custom module, you can do it with a little coding as well. Be prepared to go through a little bit learning and conventions first. This is a nice guide to get you started.

You can do this easily with an EntityFieldQuery to fetch the eligible nodes list, and then setting the #default_value in hook_form_alter hook.


Custom form values in hook_form_alter() not available in custom validate function I'm modyfing a node form to add a few extra fields. On submit, I need to program some extra logic to these values then save them to the node object.
function module_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == 'my_node_form') {
    $form['custom_form'] = array(
     '#type' => 'textfield',
     '#title' => t('Custom field'),
     '#default_value' => 'enter custom text here',
    );

    $form['#validate'][] = 'custom_form_process_values';
  }
 }

 function custom_form_process_values(&$form, &$form_state, $form_id) {
    echo '
' . print_r($form_id,1) . '
';
    echo '
' . print_r($form_state,1) . '
';
    exit();
  }

When I go to node/22/edit and change "enter custom text here" to something else, and I submit the form, I only ever see "enter custom text here" and not the new text I entered. It seems that it does not carry the text through to the validate function. Also tried it in a submit function but the same problem occurs.
Why does this happen?

This pair of functions should do the trick:

function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if (stripos($form_id, 'node_form') !== FALSE) {
    $form['custom_form'] = array(
     '#type' => 'textfield',
     '#title' => t('Custom field'),
     '#default_value' => 'enter custom text here',
    );
    $form['#validate'][] = 'mymodule_custom_form_process_values';
  }
 }

function mymodule_custom_form_process_values($form, &$form_state) {
  // Check to see if the default text has been altered by the user.
  if ($form_state['values']['custom_form'] != $form['custom_form']['#default_value']) {
    // Do something here...
  }
}

Tested on Drupal 7.53.


Images don't show in Drupal 7 I've created a content type with some custom fields, one of which is an image. When I try to render a node that contains some images uploaded like this the route is messed up, like this:

http://localhost/gisele-drupal//var/www/gisele-drupal/sites/default/files/contract.png

What can I do to configure this right?

There is something wrong with you basepath.

in your .htaccess file make sure you uncomment this line

  # If your site is running in a VirtualDocumentRoot at http://example.com/,
  # uncomment the following line:
  RewriteBase /

and in your settings.php file you may have to change your $base_url

 $base_url = 'http://localhost/gisele-drupal';  // NO trailing slash!

let me know if that helps


How to print a field in node.tpl.php without labels or markup? In Drupal 7, you can render a field in a tpl.php file like this:

But that prints it out with it's label and HTML. Is there a way to get just the raw value of the field.

I know you can do the following:

Override the field markup in the field.tpl.php file (or field--FIELDNAME.tpl.php)
Turn off labels in the admin interface
Use a module like Fences to control mark up in the admin interface.

However, all of those involve extra steps. I was wondering if there is a way to do it directly in the node.tpl.php file. That way, all the changes are contained in a single place. (Plus if you change themes to one that requires the labels, you have to go back in the admin interface and turn them back on).

If you just want the value of a given field, it will be in the $node object in your node.tpl.php file (or node--type.tpl.php).

Normally it's under something like:

$node->field_name['und'][0]['value']


How to add an entity reference field value on Behat Test My Behat test starts like this:

@api
Scenario: Testing user
Given users:
    | name | pass | mail    | status | roles  | field_lines_ref |
    | test | test | t@t.com | 1      | Tester | Line Name       |

field_lines_ref is an entity reference to a node.  The user gets created but the Lines Reference field never gets populated.  I also tried using the node id but it also didn't work.

One thing to note is that I already have a node created "Line Name" and I have to use that exact node because of logic in place (Based on node id).

If you have an entity reference field, you need to refer to the entity with it's name/title/label field (this applies for taxonomy terms too). Like you did it.

This code will run for your association:

/**
 * Entityreference field handler for Drupal 7.
 */
class EntityreferenceHandler extends AbstractHandler {

  /**
   * {@inheritdoc}
   */
  public function expand($values) {
    $entity_type = $this->fieldInfo['settings']['target_type'];
    $entity_info = entity_get_info($entity_type);
    // For users set label to username.
    if ($entity_type == 'user') {
      $entity_info['entity keys']['label'] = 'name';
    }

    $return = array();
    foreach ($values as $value) {
      $target_id = db_select($entity_info['base table'], 't')
        ->fields('t', array($entity_info['entity keys']['id']))
        ->condition('t.' . $entity_info['entity keys']['label'], $value)
        ->execute()->fetchField();
      if ($target_id) {
        $return[$this->language][] = array('target_id' => $target_id);
      }
    }
    return $return;
  }

}

Which also means, the first item will be tried to associate with your user, which doesn't mean, that it can be (i.e. for content type restriction). So make sure you have only one entity which named like you want to associate. Also make sure, you don't have ', ' and ' - ' in your value, because those will be converted to multi value, and if ' - ' is present than the ': ' value will be converted to key: value pairs. You need to say exactly the entity name which is possible to refer inside that field (but as far as I can see in the code, make sure you don't have space before and/or after the name field's value, because the query above may fail to find your entity). Also check if your field is a real field, (not like the path 'field', which is not a field) you can do it, be executing the field_info_field_map() command, and if you find your field machine name there, as a key, you are fine.

If all the above is fulfilled and you already has a node which can be referred by the user's field_lines_ref field and the node title is 'Line Name' you should be able to create your user with the reference:

Given users:
    | name | pass | mail    | status | roles  | field_lines_ref |
    | test | test | t@t.com | 1      | Tester | Line Name       |

From features file or

$user_obj = (object) array(
  'name' => 'test',
  'pass' => 'test',
  'mail' => 't@t.com',
  'status' => '1',
  'roles' => 'Tester',
  'field_lines_ref' => 'Line Name',
);
$user = $this->userCreate($user_obj);

from context object.

If these doesn't help, you may need to debug your own code (including vendor code), to see where is the problem.


Can a pager item point to an anchor on the page? I'm building a page where, somewhere down in the middle of it, there's a pager of some stuff.  The pager is working fine, but, when you click on one of the pager items, the page is redrawn showing the top of the page, which usually does not include the (now updated) contents of the pager.  This is because the pager item URLs simply refer to the page as a whole.  Is it possible to get a reference to an anchor inserted into the URLs of the pager items, so that the browser will redraw the page with the pager contents in view?

Have you looked at theme_pager_link in Drupal 7. Your site's theme can customize any pager link by implementing YOURTHEME_pager_link and then add additional logic into a copied version of that function to embed anchors as needed.

You can probably embed the anchor as a parameter to the link to be inserted into the querystring:

  parameters: An associative array of query string parameters to append
  to the pager link.


Access control in group based forums On my websites I have forums that mirror the structure of og-based groups. I am using advanced forums, OG Forum D7 and a decent amount of custom code.

My problem is to restrict access/visibility to forums based on the og role. While I know how to do it with forum topics which are stored as nodes, I have problems with forums which under a hood are taxonomy terms.

I am looking for a place where I can hook the code restricting visibility of a taxonomy term.

function mymodule_taxonomy_access($taxonomyterm, $op, $account) {
    if( $op == 'view' )
        $gid = get_grop_from_term($taxonomyterm);
        if( user_has_forum_access($gid, $account))
                return ACCESS_ALLOW;
        //else
        return ACCESS_DENY;
    }
}

I have no idea in which module I should look for the right hook: taxonomy, forum, forum_access, core (I think that taxonomy terms are entities)?

Taxonomy Access Control while being very powerful, provides no connection with organic groups.

UPDATE
I have found that TCL Lite is using the hook_query_TAG_alter to hide taxonomy terms.
The hook is editing all queries made to the database and is effectively filtering the taxonomy_terms that any query can see.
This looks like an awfully heavy solution.

Can anyone suggest a better approach?

After a small fight I managed to have it solved. There are few issues to have in mind like caching or preventing infinite recursion (you don't want to change the queries that you use inside the query altering function).

The code is based on TAC module.

function mymodule_query_term_access_alter($query) {
    static $mymodule_recursion_flag = FALSE;

    //prevent infinite recursion altering db_queries inside of this function
    if($mymodule_recursion_flag) return;

    // Take no action if there is no term table in the query.
    $alias = '';
    $tables =& $query->getTables();
    foreach ($tables as $i => $table) {
        if (strpos($table['table'], 'taxonomy_term_') === 0) {
            $alias = $table['alias'];
        }
    }
    if (empty($alias)) {
        return;
    }

    //store once obtained results
    static $mymodule_tids = null;
    if($mymodule_tids == null){
        //set the recursion flag
        $mymodule_recursion_flag = TRUE;
        // Fetch a list of all terms the user should not see
        $mymodule_tids = mymodule_get_taxonomy_black_list();
        //unset the recursion flag
        $mymodule_recursion_flag = FALSE;
    }
    // No restrictions - user can list all terms
    if (empty($mymodule_tids)) {
        return;
    }
    // Otherwise, filter the terms
    else {
        $query->condition($alias . ".tid", $mymodule_tids, "NOT IN");
    }
}


Form in modal dialog: Template suggestions have weird random suffix My custom module has the following form route in mymodule.routing.yml:
library_assets.add_asset_to_slideshow_modal:
  path: 'library/add-to-slideshow-modal/{library_asset_nid}'
  defaults:
    _form:  '\Drupal\library_assets\Form\AddAssetToSlideshow'
    _title: 'Add to Slideshow'
  requirements:
    _permission: 'access content'

And I have a link (in another form) which opens this form in a modal dialog:
$asset_display_title = $this->node->field_la_display_title->value;
$modal_form_url = Url::fromRoute('library_assets.add_asset_to_slideshow_modal', [
    'library_asset_nid' => $this->node->id(),
]);

$form['actions']['add_asset_to_slideshow'] = [
    '#type' => 'link',
    '#title' => $this->t('Add to Slideshow'),
    '#url' => $modal_form_url,
    '#attributes' => [
        'class' => [
            'use-ajax',
            'btn',
            'btn-blue',
            'w-100',
            'd-block',
        ],
        'data-dialog-type' => 'modal',
        'data-dialog-options' => json_encode(['title' => $asset_display_title, 'width' => 600]),
    ],
];

All of this is working – the form modal appears when I click on the "Add to Slideshow Link"; it validates correctly; the form submit handler works properly, etc.
But I'm having problems theming the form. When I inspect the contents of the modal to see the template suggestions, I see this:
<!-- FILE NAME SUGGESTIONS:
   * form--add-asset-to-slideshow--pv65ooQgrPE.html.twig
   x form.html.twig
-->

The pv65ooQgrPE part is different every time - it seems to be randomly generated (maybe a hash of some kind?).
I obviously can't create a template file if the filename is essentially random every time.
I tried omitting the suffix, and creating a template named form--add-asset-to-slideshow.html.twig – but that doesn't work.
What's going on here? Is this an intentional feature of Drupal? (If so, where is the documentation? I've been unable to find it.)
Most importantly, though: what's the proper way to theme my form, in this situation?
Thanks!

Create a .module in your module folder ex : library_assets/library_assets.module

in the .module file use this HOOK to create a new form suggestion that will be dynamically equal to form--{form-id}.html.twig

    <?php
/**
 1. Implement {module_name}_theme_suggestions_form_alter
 */
function library_assets_theme_suggestions_form_alter(array &$suggestions, array $variables) {
  //Get the form id
  // ! - you must replace the '-' with '_' in the suggestion name otherwise it won't work.
  $form_id = str_replace('-', '_', $variables['element']['#id']);

  // adding a new suggestion to the form template
  $suggestions[] =  'form__'.$form_id;
}

now clear the cache and inspect the code again and you'll find a new theme suggestion = form--{form-id}.html.twig


Display content by specific groups of users Is it possible to display content by a group of authors without using a group module? I like the group module, but it's much more complex and robust than what I need it for.

Synopsis: We need to build a page that will display blog posts by not one specific author but by a group of authors dynamically and preferably contextually. The authors will not have control over this page or interact with it in any way. There will be dozens of these groupings of authors. The page will also display a view block of biographies for the authors that can be linked to the author's Drupal profile.

Edit: screenshot of my contextual filter using the selected answer below; pastebin of exported view

The simple solution would be to add Term Reference field to the user's profile fields. Then for each user assigned them a taxonomy (in this case the taxonomy term name would be the group name).

Use Field Permissions module to control who can edit and change the user's tax reference field.

Use Views and filter by taxonomy term to display the "group's" content. You  will need to make a View of Users then under Advanced (far right) add a Relationship of Content authored.


Programmatically add PDF file to user So using the 'file' module i have added a field to the user table called 'user_files'. What i want to know if how can i programmatically add a file to the user, so that it is displayed on the users profile.

So far i am storing the file information locally and then targetting the database tables directly and inserting the data into them. This has been done correctly, but the file is not dispalying.

I am using file_save_data to store the file in the database. Then manually adding it to 'field_data_field_user_files', 'field_revision_field_user_files' and 'file_usage' tables.

Is there a simpler way to get this to work?

You first need to insert the file in the database, then assign it to your entity (a user in your case)

To insert file in the database say you have your file in a temp location. You can add it to the databse at the same time the file is moved to its final location:

// uid of user that to add the file.
$uid = $UID;

// Final file name
$filename = $FILENAME;

// Fieldname where to attach the file
$fieldname = $FIELDNAME;

// File temporary path.
$file_tmp_path = $FILE_TMP_PATH;

// Let's go!

// Load user object.
$account = user_load($uid);

// Gather file info.
$filesize  = filesize($file_tmp_path);
$mime_type = mime_content_type($file_tmp_path);

// Create file object.
$file = new stdClass;
$file->uid      = $uid;
$file->filename = <desired filename>;
$file->uri      = $file_tmp_path;
$file->filemime = $mime_type;
$file->filesize = $filesize;
$file->status   = FILE_STATUS_PERMANENT;

$destination .= '/' . $filename;

// Move to its final destination and add it to the database.
// file_move moves the file and is in charge of add the needed DB records.
$file = file_move($file, $destination, FILE_EXISTS_RENAME);

// Attach file to user.
$account->{$fieldname}[LANGUAGE_NONE][0]['fid'] = $file->fid;

$user_save($account);


How do I create a custom template for view? I have created a content type called "Hotels". I want to display to the view in different manner other than view options provided by Views module. For that I have to create custom template but don't know how to do it. What should be the naming conventions and where to store the template file. Please help me.

Below give are the views template suggestion allowed in Drupal 8.

views-view--foobar--page.html.twig
views-view--page.html.twig
views-view--foobar.html.twig
views-view.html.twig
views-view-unformatted--foobar--page.html.twig
views-view-unformatted--page.html.twig
views-view-unformatted--foobar.html.twig
views-view-unformatted.html.twig
views-view-fields--foobar--page.html.twig
views-view-fields--page.html.twig
views-view-fields--foobar.html.twig
views-view-fields.html.twig

Refer Views template files for more information.


How should I add ID or classes to secondary tabs? I'm developing a site in drupal 7. I see that the function theme_menu_local_tasks() in includes/menu.inc is responsible for generating the secondary tabs. However the <li> elements do not have any IDs or classes. How do I start adding IDs and classes to the list elements?

The theme function that render the single menu local tasks is theme_menu_local_task(), which is the function that output the <li> tags.

return '<li' . (!empty($variables['element']['#active']) ? ' class="active"' : '') . '>' . l($link_text, $link['href'], $link['localized_options']) . "</li>\n";

In a theme, you can implement an alternative of that theme function, using the code of that function as base; you then can add more CSS classes.

Supposing that your theme is "my_beautiful_theme," you need to create a "template.php" file (if it doesn't exist), and add the function my_beautiful_theme_menu_local_task() with the code for your theme function.

From a module is more complicated, but it has the pro of being applied for every theme you set in your site. If users are allowed to set a theme for themselves, you don't need to add that theme function in all the themes you enable, which also means not altering the code provided by other users. If you alter a theme you install, you then would lose your customizations every time the theme is update, and you install the update in your site.

With a module, you just need to implement something similar to the following code:

function mymodule_theme_registry_alter(&$theme_registry) {
  if (isset($theme_registry['menu_local_task'])) {
    $theme_registry['menu_local_task']['function'] = 'theme_mymodule_local_task'; // The new theme function.
  }
}

function theme_mymodule_local_task(&$variables) {
  // Add here your code for the theme function.
}

For more information, you can look at hook_theme(), and hook_theme_registry_alter().


How do I remove markup from fields? I want to remove all the default Drupal markup around content types fields.

In Drupal 7, Fences does it like a charm, but its Drupal 8 version is not stable yet. Another choice would be Display Suite Extra, in Drupal 7, and we can do it with Control markup with field templates, but in the Drupal 8 version there isn't any admin/structure/ds/extras and Check the option Enable Field templates exists.

How can I get rid of the default markup field wrappers?

Depending on your project and goals there are a few solutions. Drupal 8 core itself generates very little markup, the field markup is now coming from a theme, and the markup from those base themes is much lighter-weight than D7's core. To get started you may want to review the new theme guide, and MortonDK's session from DrupalCon New Orleans.

Given the control you seem to be seeking, you should probably create a theme that's based on Stable (which is the default if you don't set a base theme). Then enable theme debugging, and as you find templates you don't like the output of, copy them from core/themes/stable/templates/... into your theme's templates folder. If you explore either stable or classy you'll see a variety of field templates in the field directory, and you can target them on a case-by-case basis in your theme as needed (theme debug will provide you the name suggestions you need to create the properly targeted file).

Some people are copying the entire stable theme so they have all the templates on hand from the start. If you did that you may also want to set the base theme to false so stable is disabled entirely.

You can also use the hook_theme_suggestions_field_alter() and hook_preprocess_field() in your theme's .theme file to make changes before reaching the twig files.  If you use the Drupal console to generate your theme, the boilerplate code will come with a large collection of the preprocess functions already defined.


How do I make the custom module "Configure" option appear on the module list? I have written a simple module that implements hook_menu() (the added path is admin/settings/mymodule").

On the admin/modules page which lists all the present modules, there is no "Configure" link for my module. How do I implement it so that the link to "admin/settings/mymodule" is visible on the modules page?

It's done in the module's ".info" file, using the "configure" key.

name = Example module
description = Gives an example of a module.
core = 7.x
package = Views
dependencies[] = views
dependencies[] = panels
files[] = example.test
configure = admin/config/content/example


500 Internal Server Error I changed my server and when I uploaded my site this error appeared:

  Internal Server Error
  The server encountered an internal error or misconfiguration and was unable to complete your request.
  Please contact the server administrator, webmaster@xxxxxxxx.com and inform them of the time the error occurred, and anything you might have done that may have caused the error.
  More information about this error may be available in the server error log.

  Additionally, a 500 Internal Server Error error was encountered while trying to use an ErrorDocument to handle the request.
  Apache/2 Server at xxxxxxx.com Port 80

I tried to upload it again without success. I tried uploading the index.html file without the drupal site, and it worked.

How can I solve this problem?

I had this problem too, due to a bug in my PHP code and the fact php.ini was not set to display errors.

Find the line display_errors = Off in php.ini and change it to display_errors = On. This way you'll see the specific php error message instead of the generic internal server error.


Need to know the most essential JS and CSS files for a Drupal 7 page I am creating a module that has a page that is intended to be a viewer for a certain kind of content. The content itself is a Drupal Book viewer meant to behave like an epub reader. Basically I want this page to be a stand-alone, theme-independent, full-screen "player."

To achieve this effect, I don't want to load the usual long list of CSS and JS files, including those from the current theme as well as any from modules that I am not interested in using. I want the page to load only those JS and CSS files that are required for basic Drupal functionality -- e.g. I want Behaviors to work and a few other things, such as overlays.

My question is, what are considered to be the essential JS and CSS files? I realize I can find a way to just dump a list of all files by module. But I am looking for information on importance. I realize this is a little vague and that there are probably a lot of answers that begin with "It depends ..." However, there must be some items that are more fundamental than others.

I am working in Drupal 7 and using hook_js_alter() and hook_css_alter() to remove (unset) items, and a preprocess function to add items.

You can achieve this by making your module load your own html.tpl.php and in that version of the html template, you simply remove references to styles and scripts.

<?php print $styles; ?>
<?php print $scripts; ?>

For a viewer, you can probably do without the reams of CSS cruft that is loaded by default and add your own bare bones css & js either through a hook or by including it in your custom html template.

<?php print $path_to_your_reader_styles; ?>
<?php print $path_to_your_reader_scripts; ?>


Is there a way to create a Webform automatically via script using Drush or another method? I'm automating a base Drupal 8 install using a bash script with Composer and Drush commands that installs Drupal and uses Drush and other methods to set my basic site configurations.

I'd like to also create some other basic settings like creating a standard Webform contact form, including its URL, etc.

Is this possible to do somehow via a script? Perhaps have a Webform config export stored somewhere and import it via the script? Note, this would be a new site so its UUID would differ each time.

You can exactly do what you touched on with config: put a placeholder into the yaml for the URL and remove the uuid completely. As you import into a new site, that will generate a new one for you.


Contextual Filters Help - User Pages I am working with user pages and I have styled a user page with a custom .tpl and I am using a block to bring in the latest post from that user using views. I am having a problem sorting out the posts with contextual filters. I have set up the contextual filter to work if the URL was /user-name but because it is a users page the URL is /users/user-name and this is screwing up my filter. Any advice someone can give me?

I usually add a contextual filter for "user: uid", specify a default of "userid from the URL" and then set a validation criteria for "user" and "Allow both numeric UIDs and string usernames".
That way you can use both the uid and the username.

You'll probably have your "last post block" show up on the profile edit page because it's at "user/%/edit".
I changed my user profile pages to "member/USERNAME" using the pathauto module.


How to remove creation of file paths? I have created a Drupal project, on that project I have many files uploaded. But when I crawl the project through crawlers I am getting files as file url like the following.

http://project.com/files/file2png
  This means I have a file in my files directory as file2.png
http://project.com/files/file1png
  This means I have a file in my files directory as file1.png

I have a File Entity module. Does it create url in this format?
If yes, how to avoid this?

And I don't know which module makes this. I want to avoid this. Is there any way to remove creation of file paths for my files?

According to your comment:

  I don't want to create pages for the Files

The url file/%file is registered as menu item in file_entity_menu(). You can disable the page by implementing hook_menu_alter() in custom module.

Example

/**
 * Implements hook_menu_alter().
 */
function mymodule_menu_alter(&$items) {
  // disable the file entity page
  $items['file/%file']['access callback'] = FALSE;
}

Another question you mentioned.

  Can I redirect to home page for file url's?

You can override the page callback and add the redirection in it.

Example

/**
 * Implements hook_menu_alter().
 */
function mymodule_menu_alter(&$items) {
  // disable the file entity page
  $items['file/%file']['page callback'] = 'mymodule_file_callback';
}

function mymodule_file_callback($file) {
  drupal_goto('<front>');
}


Get menu item of a node I have a node (in D8) which is placed in the menu "Main navigation". How do I get the menu item (in code)? In Drupal 7 you could use $node->menu but in 8.x, the object is not populated with menu information. So, how do I retrieve it? I also want to support another type of menus in the future, so something which works with more than the menu_link_content module is appreciated.

You can try this code:

use Drupal\menu_link_content\Entity\MenuLinkContent;

$node_id = 1;
$menu_link_manager = \Drupal::service('plugin.manager.menu.link');
$result = $menu_link_manager->loadLinksByRoute('entity.node.canonical', array('node' => $node_id));

dpm($result);


Remove drupal parameters from form submitted via GET I have form which is submitted via GET method. The problem is that after submit the URL looks very bad, with lots of parameters like form_build_id & form_token. How can I get rid of them? Thanks

I ended up doing this:

$form = drupal_get_form('my_form_id');
unset($form['form_build_id']);
unset($form['form_id']);
unset($form['form_token']);


Placing exposed filters (with BEF) in various Panel regions So, my question is basically the same as How to show in different positions exposed filters in a View?  However, the answer here did not work for me (and I could not post a comment there because I don't have 50 rep -- very sorry).  I follow the steps outlined exactly and I only have the option to place "View exposed widgets" with no sub options.

Basically, I'm trying to place my exposed filters in various places within the display (almost identically to the referenced ticket).  I'm running Views with type of Context and using Better Exposed filters.  According to quite a few places, that should allow me to place the individual filters in whichever region of the Panel I desire.  However, I don't see them.

Any advice?

did you finally find a solution for this? You could use the module MEFIBS which allows you to put your filters (and sort) into different blocks.

Anyway, MEFIBS didn't work for me because of the fact that all blocks get seperate submit button. So it would be interesting for me to hear how you finally ended up with this.

Best,
Thomas


How can I add a class to link around image field I have a field field_sidebar_gallery which outputs multiple images. These images are rendered using image style gallery_thumb and the display format on them is using the lightbox2 module which wraps the rendered image in an  tag.

What I need to do is add a class to the  tag which wraps around the image. I could easily do this in the template file for field--field-sidebar_gallery.tpl.php and just look at the uri for the image and build the link and image html myself using the relevant functions (theme(), l() etc). However, taking this approach I then lose all of the configuration abilities of lightbox2 (and I suppose any other modules which may end up manipulating the links in the future)

The output currently is as follows

I've looked at

theme_links()
template_preprocess_field()
hook_entity_view()
hook_entity_view_alter()
hook_node_view_alter()

With little to no success. I suspect the display formatter kicks in and that's what I should be looking at but I don't really know where to start.

All I need to do is for this particular field (field_sidebar_gallery), is to add a class to the  so that the final output is as follows (note the class="thumbnail[...] compared to the above)

If anyone can point me in the right direction, that'd be much appreciated.

From the way lightbox does it (line 145), i would think there is not much you can do to alter the link, since it is "hardwired" there.
What you could do (and is surprisingly easy :) is to implement your own handler that would extend the lightbox one and allow you to specify the css class (or submit a patch that would do it in their code).

You might as well specify the class on the parent div (in views "Styles settings" for the field, "Customize field HTML" and "Create a CSS class". And then just sligthly change your selector.


How can I loop through entity reference values? My content type "Export" has an entity reference to the type "country" (i.e. you assign countries to the export). I wish to do something like the following

$countries = $node->field_exporter_countries['und'][0]['value'];

foreach ($countries as &$value) {
   print $value;
}

Edit

I also tried this. But i get the wrong titles back.

$nodes = entity_load('node', array_keys($countries));
foreach ($nodes as $n) {
  print $n->title;
  print "<br /> ";
}

According to the entityreference_field_schema() function, the column name for an entity reference field is target_id (not value). That said, to extract the node ids you should probably use something like this:

$nids = array();
foreach ($node->field_exporter_countries[$node->language] as $index => $item) {
  $nids[] = $item['target_id'];
}

$nodes = entity_load('node', $nids);

// etc...


Sort result by taxonomy term weight $query = db_select('node', 'n');
   $query->join('field_data_taxonomy_catalog', 'tc', 'n.nid = tc.entity_id');
   $query->leftjoin('field_data_field_chip', 'fdc', 'n.nid = fdc.entity_id');

   $query->fields('tc',array('taxonomy_catalog_tid'));
   $query->fields('fdc',array('field_chip_tid'));

   $query->fields('n',array('nid'));

   $query->condition('tc.taxonomy_catalog_tid',$get_tid,'=');

   $query->orderby("fdc.field_chip_tid","ASC"); //I Want to sort the resultset on the basis of weight instead of the term Id.

   $result = $query->execute()->fetchAll()

I need to sort the result on field_data_field_chip weight instead of the term Id. I am new to Drupal and don't know how to fetch the weight of the taxonomy terms.

The weight column in the taxonomy_term_data table contains the information you need.

You can join it in to your current query via taxonomy_term_data.tid.


Overriding the view_handler_field_node_link_edit I have created a view using custom content type with edit link.I have to write some php code for edit link.Can i override views_handler_field_node_link_edit extends in my custom module?

    /**
     * Renders the link.
     */
    class views_handler_field_node_link_edit extends views_handler_field_node_link {
        function render_link($node, $values) {
        // Ensure user has access to edit this node.
            if (!node_access('update', $node)) {
                return;
            }

            $this->options['alter']['make_link'] = TRUE;
            $this->options['alter']['path'] = "node/$node->nid/edit";
            $this->options['alter']['query'] = drupal_get_destination();

            $text = !empty($this->options['text']) ? $this->options['text'] : t('edit');
            return $text;
        }

    }

Maybe this post will help you out http://thereisamoduleforthat.com/content/recipe-extending-views-handlers-without-subclassing


linkd not displaying for anonymous user I'm trying to make node/add URL appear on front of site to anonymous user and when clicked, it redirects to login or register page. drupal hides links automatically, any help please. I'm using drupal 7

You can do that by creating a block as follows

Go to admin/structure/block and add a new block as follows

set show block for anonymous user.

and set the Region where you want to display the link on Front page. and if you want to display the link only at front page. make the following settings


Basic functions not being seen I am getting the following error when invoking "commerce_cart_order_product_line_item_delete()" in a custom module I'm writing.

  Fatal error: Call to undefined function commerce_entity_reference_delete() in
  /Users/[username]/Documents/Sites/[site_name]/profiles/commerce_kickstart/modules/contrib/commerce/modules/cart/commerce_cart.module
  on line 1268

The commerce_entity_reference_delete() function that Drupal claims it can't find resides in:

  /[site]/profiles/commerce_kickstart/modules/contrib/commerce/commerce.module

Which, if I understand correctly is THE main commerce module that makes the whole shopping cart functionality work. So, my commerce module is enabled (because my shopping cart is working, and which is confirmed also on the Modules page), so why isn't commerce.module serving up the function above for me?

Aren't I allowed to call commerce_cart_order_product_line_item_delete() from a custom module?

This function commerce_cart_order_product_line_item_delete is in commerce_cart.module in line 1259 tnen in line 1268 call commerce_entity_reference_delete, function should be in commerce.module file line 124, check the function exist there.
This is some strange if the function exist in commerce.module and return fatal error,
I suggest first be sure that the function exist in code then  clear cache and then try again.
It is allowable call any function in any custom module and drupal not have restriction about this subject.


Pathauto for a multilingual site not generating alias for non-default languages I have a site with 90% content in Chinese, and only 10% in English.

Thus the requirement of the client is that when viewing an article in English, everything around it remains in Chinese. Blocks, menus etc

a) Enable language prefix

What this does is sets english article with en/[node:title] which is acceptable. But the problem occurs as it appends that to every url in the menu, and other places. So they become like en/categories/CHINESE-CHARACTERS which is not right, and no content is displayed.

In pathauto for English articles, I thus tried, specifically giving it [node:title]. Yet it prepends the en.

b) Disable language prefix.

Now all my links are fine. But the english article is now a node/[nid]. The url aliases just don't seem to be working in this case. If I could just have the URL alias working in this case, things would be great too.

Any solution to my misery is welcome.

Aliases indeed disappear from nodes with non-default language after disabling language prefix in URLs. The solution to that is easy, but you have to do it in code, using Pathauto's hook_pathauto_alias_alter().

Basically all you need to do is:

function yourcustommodule_pathauto_alias_alter(&$alias, array &$context) {
  // Force all aliases to be saved as language neutral.
  $context['language'] = LANGUAGE_NONE;
}

This way you make sure that the language of the saved alias (not of node!) will always be und, meaning it will show for nodes of all languages.

Note: For existing aliases it is not enough to re-save the node. You have to delete the alias first and then have it recreated. Often the easiest is to do it in bulk via Pathauto's configuration interface. First delete all paths, then bulk-recreate them.

For more, see https://www.drupal.org/node/1234924


Redirecting a page after form submission If I have a module that is creating a page, after form submission for that page, how would I redirect? Is there a function to do this in Drupal? I imagine that I would put the redirect command inside my function that executes after form submission, correct?

Beside the drupal_goto() function there's also the 'redirect' property in the $form_state

See https://api.drupal.org/comment/18139#comment-18139


A time field instead of end date in drupal 7 date field Is it possible to have a time field (for example in minute only) instead of end date of date field in drupal 7?

so that the user select start date and time and due time (in minute) and end datetime will be start datetime + due time?

The Date single day module for Drupal 6 worked great for this use case. There isn't a 7.x version yet, but there is an issue to port it.


Adding rating and commenting to individual fields I have a node with a CCK field file upload, which is using the image widget.
This node can have multiple images uploaded to it.

How can I add fivestar rating (or something similar), and comment to these individual pictures? How could I do it with other fields in general?

The best way to solve this would be to use the Field Collection module. All you would need to do is create a field collection with a rating and an image in it, and every time a new image is added, there would be a new rating next to it. The latest D7 version has come a long way and should work for what you need.


How do i get the type attribute when adding javascript to drupal? i'm adding javascript with

  drupal_add_js()

but drupal cuts the script attribute "text/javascript" or just forgot it. It just adds the

<script></script>

tags. Can i add the script tags? Its w3c standard...;-P

On the off-chance that you're using an HTML5 DOCTYPE, you don't need to worry:

  The type attribute gives the language of the script or format of the data. If the attribute is present, its value must be a valid MIME type. The charset parameter must not be specified. The default, which is used if the attribute is absent, is "text/javascript".

Emphasis mine

Source: HTML 5.1 Nightly - 4.3 Scripting


How to control a taxonomy view's output? On the page referenced below, the two blocks to the left are separate views that represent two different taxonomy terms: "fence type" and "application."

J.C. Greene Rail Fencing photos page

I want to be able to add a new page of photos each job and be able to label type with something like "2 Rail" and application with "Horse fence" for example. But the views need to be dynamic, so that if a new type/application is used, it is added to the list to the left and the styles applied as desired.

For example, if a new fence is installed, and its application is to keep cattle in a field, then I might put "Cattle fence" in the application field, so a new item would be added to the Application block, and upon clicking "Cattle fence," the visitor would see a grid showing one job with one picture (later to see more jobs as more cattle fences are done). Upon clicking the one picture, it would go to that job's page with the slideshow, as shown by the link below (which is what I want to see when clicking on the 2 Rail link in fence type).

2 Rail test view

To get an idea of the view configuration for each block, check out this image:

(Right click & click 'view image' to see the full size.)

It sounds like you're trying to do a couple complex things: 1) use contextual filters to choose which term to show and 2) then you're trying to theme certain taxonomy term pages. Once you've got stuff set up in a way that uses these concepts, you should be able to accomplish your end goal (But the views need to be dynamic, so that if a new type/application is used, it is added to the list to the left and the styles applied as desired.) relatively easily.

This is a good basic introduction into Views Contextual Filters: http://www.metaltoad.com/blog/using-drupal-contextual-filters-views

As for theming taxonomy term pages, I think everyone has different ideas on how to best to do that, but if you've already got these three views set up, it might be easiest to use Panels (https://drupal.org/project/panels) and drop those existing views into a panel that is context-based. Of course, Panels comes with its own learning curve, so it might not actually be that easy (though here is a basic introduction for something like what you're trying to do: https://drupal.org/node/1582906). And maybe I'm over-complicating this by assuming you want to theme your pages; maybe contextual filters were all you needed?

Just in case, here are some other ways of theming taxonomy pages:

override taxonomy-term.tpl.php (the basics of overrides: https://drupal.org/node/173880)
Display Suite: https://drupal.org/project/ds

I'm sure there are a bunch of other ways too, but that's all I've got off the top of my head for now. And I'm sure someone else will chime in with more options soon.

Also, here are some other links that you might find useful:

How to theme each nodes in a taxonomy term page seperately in drupal 7
Theme a taxonomy terms page
Overriding the default taxonomy page with a view in Drupal 7


HTML email containing selected node content I need to send an email containing the content from one or more selected nodes.

The nodes are selected in an email contact form by the user (which also needs to fill the rest of the form with other, more basic details).

Is there an efficient way to achieve that functionality?

If you mean to sending whole nodes, than from my lookup, this might be a solution for you.

If this solution doesn't satisfy you, an alternative would be to send the user a link to the printing version of that given node. This shouldn't be very much complicated in PHP I guess.

A print version can be made with this module (Make sure the printing-versions have HTML canonical tags referencing to the main node).


image_scale_and_crop In Drupal 6 there is a parameter $destination for the function 'image_scale_and_crop()' . The parameter is not available in D7. I have the following code block.

image_scale_and_crop($image, 100, 70);

This code is executed an the thumbnail is created in a path if I examine the file directory.

My question is, how I can determine the path where the cropped file is created in order to save it to db.

Maybe it's better to use an image style and use theme_image_style($variables)


Move fields into fieldset with field_collection module doesn't work I have a node, inside this node I have a field_collection with one checkbox and 2 fields inside it. I want to move these two fields inside a fieldset to show/hide entire fieldset depending of the checkbox value.

function mymodule_form_testtype_node_form_alter(&$form, &$form_state, $form_id) {
    $form['field_test_collection']['und'][0]['surround_fieldset'] = array(
        '#type' => 'fieldset',
        '#title' => t('Sorround fieldset'),
        '#tree' => FALSE,
    );
    $form['field_test_collection']['#tree'] = FALSE;
    $form['field_test_collection']['und'][0]['surround_fieldset']['field_collection_first'] = $form['field_test_collection']['und'][0]['field_collection_first'];
    $form['field_test_collection']['und'][0]['surround_fieldset']['field_collection_second'] = $form['field_test_collection']['und'][0]['field_collection_second'];
}

But when I try to submit the form these two values are not saved. I tried to remove the original fields using

unset($form['field_test_collection']['und'][0]['field_collection_first']);

or hide them with

$form['field_test_collection']['und'][0]['field_collection_first']['#access'] = 0;

I also tried the "cheat" to move back these two fields in the validate function

function mymodule_article_form_testtype_node_form_validate(&$form, &$form_state) {
    $form_state['values']['field_test_collection']['und'][0]['field_collection_first'] = $form_state['values']['field_test_collection']['und'][0]['surround_fieldset']['field_collection_first'];
    $form_state['values']['field_test_collection']['und'][0]['field_collection_second'] = $form_state['values']['field_test_collection']['und'][0]['surround_fieldset']['field_collection_second'];
    unset($form_state['values']['field_test_collection']['und'][0]['surround_fieldset']);

    $form['field_test_collection']['und'][0]['field_collection_first'] = $form['field_test_collection']['und'][0]['surround_fieldset']['field_collection_first'];
    $form['field_test_collection']['und'][0]['field_collection_second'] = $form['field_test_collection']['und'][0]['surround_fieldset']['field_collection_second'];
    unset($form['field_test_collection']['und'][0]['surround_fieldset']);
    $form['field_test_collection']['und'][0]['field_collection_first']['#access'] = 1;
    $form['field_test_collection']['und'][0]['field_collection_second']['#access']  = 1;
}

With a dpm($form_state) in the submit function I can see correct values in their places, but after it they're not saved.

Any idea?
Thank you

I found the solution. It seems values from fields inside the field_collections are not managed as other Drupal form values.

This is the code to achieve the result:

function mymodule_form_testtype_node_form_alter(&$form, &$form_state, $form_id) {
    $form['field_test_collection']['und'][0]['surround_fieldset'] = array(
        '#type' => 'fieldset',
        '#title' => t('Sorround fieldset'),
    );
    $form['field_test_collection']['und'][0]['surround_fieldset']['field_collection_first'] = $form['field_test_collection']['und'][0]['field_collection_first'];
    unset($form['field_test_collection']['und'][0]['field_collection_first']);
    $form['field_test_collection']['und'][0]['surround_fieldset']['field_collection_second'] = $form['field_test_collection']['und'][0]['field_collection_second'];
    unset($form['field_test_collection']['und'][0]['field_collection_second']);
    $form['#submit'][] = 'mymodule_node_form_submit';
}

function mymodule_node_form_submit($form, &form_state) {
    $form_state['field']['field_test_collection']['und']['entity'][0]->field_collection_first['und'][0]['value']=$form_state['values']['field_test_collection']['und'][0]['surround_fieldset']['field_collection_first']['und'][0]['value'];
    $form_state['field']['field_test_collection']['und']['entity'][0]->field_collection_second['und'][0]['value']=$form_state['values']['field_test_collection']['und'][0]['surround_fieldset']['field_collection_second']['und'][0]['value'];
}


Remove time filter in a date exposed filter in a view I have a view with a date field exposed filter but this date field in its content type configured to be date and time. Is there any way to make this exposed filter work only by date because now when I enter a date, didn't get any result.

Here you can implement this functionality by choosing "Is Between" in exposed filters. It works only with date.
Because at time of node creation, it's asking for date and time both in "Authored On" section.
If still you want to implement, you will have to use any trick by using jquery and hiddem fields in background


What is the best way to overwrite a node display with a view I would like to know what is the best way display a view instead of the content page. This is to have the versatility of views when showing fields instead of the traditional view mode. My current setup is:

Use Panelizar to manage node display
Create a view block with the node id as contextual filters
Add this block to the panelized panel

My question is: is there a better way? Maybe one that does not require an external module?

Thanks

I think the Drupally way to replace node content with a views block would be to hide the fields via the Display Settings, add the fields to your views block, display the views block on the node.

If you cannot hide the fields on this content type, I would suggest creating a content type for this type of page and use case.

My personal vote, if you need truly "re-arrangeable" content, would be to start using Paragraphs.

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

I offer this as an answer because I feel that while things like 301 redirects, NID template overrides, or even hook alters might get the job done, they may be a little hacky for a content situation.

Paragraphs allow you to create re-useable pieces of content with as many or as little fields in each as you'd like. And by far Paragraphs has been the best content experience I've had in Drupal.


How should I balance Features and Installation Profile in a Code Driven Development workflow? Drupal Installation Profiles (in Drupal 7) are pretty powerful and can do just about anything a module can do. I'm using an Installation Profile along with Features to develop my site, keeping everything in code so I don't have to version my database.

Given the power of Installation Profiles, many of the things you can do in a Features module can also be done in an Installation Profile. E.g., creating content types, configuring permissions, etc. How should you go about deciding whether something belongs in an Installation Profile or in a Features module when using a Code Driven Development workflow in Drupal?

I've recently started using the Features module as a deployment system, as described in this presentation on features deployment. Assuming your using a similar setup with hook_update_N, features has one clear advantage that I'm aware of: it's aware of any changes that are not in code. This makes it a fair bit easier to track changes to (for example) views and content types, and also allows you to auto-generate the new features code to be committed and deployed.

I'm not overly familiar with installation profiles, but from the link you've provided it doesn't look like they provide this functionality. However it might be a case of use whichever suits you the best.

Edit: rethought response.


Show multiple term references as ID in one row I've got a view of nodes, displayed as fields. As each node may have references to multiple terms/tags, I would like to show all these tags.

When I use field "term_node_tid", then I get the multiple values properly displayed in one row separated by commas. But instead of the readable term, I need the term-IDs.

So I set up another field using "tid", but now only the ID of the first term is shown. There's no multiple value field setting, where I could tweak things. Any help much appreciated.

Change field Formatter

If you're showing the actual Content field you can change the Formatter. Instead of using Label use Entity ID under Formatter.

This will output Term IDs instead of term names, and all the Multi-valued settings will apply the same way as for the names output.

Rewrite results with TID replacement token

Another way or changing the field output in D8 views (if the Formatter option isn't available for example) is to use the Rewrite results > Override the output of this field with custom text and enter the token for the TID in there. You can look up the correct token pattern under Replacement patterns below the Text area.

That is also how you would get the TID to display instead of the name if you use the field Content: All taxonomy terms.


facebook login redirect drupal for facebook module I am using Drupal for facebook module. I want to redirect user to specific URL, if he login from facebook ? Note: I am using Login destination for normal users and works fine for this.

Drupal for facebook module has a sub module called "FB Rules Integration"
Enable it.

Then create a new rule:
give it a name, something like "after connecting facebook account".

add an action: page redirect
then enter where do you want to redirect to, something like ""

Here is an export of the rule which you can just import.

{ "rules_after_connecting_facebook_account" : {
    "LABEL" : "after connecting facebook account",
    "PLUGIN" : "reaction rule",
    "REQUIRES" : [ "rules", "Drupal for Facebook" ],
    "ON" : [ "fb_user_connected", "fb_user_login" ],
    "DO" : [ { "redirect" : { "url" : "\u003Cfront\u003E" } } ]
  }
}


How do I render a node returned by the Drupal search module? I'm using Drupal 7 to build a fairly simple directory site. I'm trying to theme my search results page the same as a taxonomy page, but as you may know, the results arrive by a completely different process in those two situations. I've copied the search-result.tpl.php file from the Search module to my own theme, and am trying to take advantage of the $result variable returned by the module. However, it doesn't seem to be as simple as print render($result);

I tried to isolate the relevant node object within $result and perform render() on it, like so:

$content=Array(); $content['#node'] = $result['node'];
print render($content);

But that just throws an error (can't use object as array) or simply returns nothing.

$result['node'] definitely contains the fields I want to echo on the page, so what am I doing wrong?

You need to prepare a view for the node object:

$view_mode = 'teaser'; // Or whatever
$view = node_view($result['node'], $view_mode);
print render($view);


How to fill form fields based on other fields values using AJAX I have 3 fields. On blur on any of them I want to look for empty ones - if blurred one has value and any of the others does not, I want to copy value.

Obtaining value is easy, simply $form_state['triggering_element']['#value'], but setting it elsewhere gets tricky.

Changing $form['item']['#default_value'] does not work if field is empty after user's edit. Changing $form['item']['#value'] makes Drupal ignore any further user input. Changing $form_state['values'] seems to do nothing. What is the correct approach that should work? When I'll know that, I'll be able to debug.

I had the same issue and this workaround did the trick.
Basically you clear up $form_state['input'] value and rebuild the form.

Form builder:

<?php
$form['test'] = array(
  '#type' => 'textfield',
  '#title' => t('Test'),
  '#ajax' => array(
    'callback' => 'my_test_callback_func',
    'wrapper' => 'edit-test2',
    'progress' => array(
      'message' => '',
      'type' => 'throbber',
    ),
  ),
);

$form['test2'] = array(
  '#type' => 'textfield',
  '#prefix' => '
',
  '#suffix' => '
',
  '#title' => t('Test2'),
);
?>

Ajax callback function:
This is the trickier part.

<?php
function my_test_callback_func($form, &$form_state) {
  unset($form_state['input']['test2'], $form_state['values']['test2']);
  $form['test2']['#default_value'] = 'Auto Filled!';
  $form_state['input']['test2'] = 'Auto Filled!';
  return form_builder($form['#id'], $form['test2'], $form_state);
}
?>

We unset the user input (or check if it's empty), set a default value and then rebuild the form.


Twig add attribute with value in a variable Using Drupal 8

I want to print out a field's content into the src attribute. I have the following template for my view:

But the iframe gets filled with my own site's "Page Not Found" page instead of the Youtube Video because Twig prints out a whole lot of debug comments before and after printing the variable rows[0].content.

Is it possible to disable the debug comments for a specific field? I don't want to have to be disabling/enabling debug to make sure it works as expected. Because it works if I disable Twig debugging (the comments aren't printed so the URL prints out fine) but it's tiresome to be enabling/disabling to check work.

I also tried using {{ attributes.setAttribute('src', {{ rows[0].content }} ) }} , but no dice.

Another failed attempt was:

{% set iframe_src = rows[0].content %}

My last idea was this:

{% set url = rows[0].content | raw %}
{% set iframe_src = 'src=' ~ url %}

But it prints out src=Array

SOLUTION

The answer is in another question, I'm pasting it here in case that one gets deleted. The author of the following answer is @4k4

field.content is the rendered field. And in views that means it is no longer a render array, but the finally rendered markup. So this is very problematic to use it as a class name, not only because of twig debug.

Better use the row data, where you find the entity object with the field data from the database. Use clean_class to escape it for using it as a class name:

{{ row._entity.field_myfield.value|clean_class }}

I'm pretty sure the nested braces here are an error - inside a {{ }} expression, variables don't need to be enclosed again:

 {{ attributes.setAttribute('src', {{ rows[0].content }} ) }}

But for the real answer: This template isn't the culprit - the content is already rendered separately, passing through its own template which adds the comments.

See Get Views field value in Twig template, where the recommended way of getting at the unrendered field value is via the _entity object.


Create Taxonomy vocabularies and terms in installation profile I'm creating a Drupal installation profile(drupal 6) and want to create taxonomy vocabularies and terms. How to create taxonomy vocabularies and terms in installation profile?

'Terms' are data, so you must import them using the Migrate module or Feeds module.

It's easy to create 'vocabularies', not programmatically but using a Feature and then enable it with you installation profile.

But if you want programmatically here is a good article that describes how to create Taxonomies vocabularies and terms programmatically.


Form is not rebuilding on "Add another item" in unlimited value entity reference field In a content type I have a field of type 'entity reference', 'auto complete' widget with unlimited values.

The whole idea was to give user an option to add referenced node items but only once, Hence selected node items should be excluded for new added fields.

I altered the form to change #autocomplete_path of this field. I took care of altering path for all the added fields, But when clicking on 'Add another Item' it is not updating #autocomplete_path as it should while rebuilding the form. My code could help answer it better way.

In my form_alter

if (isset($form['field_article_test'][LANGUAGE_NONE])) {

  // Loop through all the fields to collect the default set values.
  $selected_nids = array();
  foreach ($form['field_article_test'][LANGUAGE_NONE] as $delta => $field_object) {
    if (is_numeric($delta) && !empty($form['field_article_test'][LANGUAGE_NONE][$delta]['target_id']['#default_value'])) {
      $dval = $form['field_article_test'][LANGUAGE_NONE][$delta]['target_id']['#default_value'];
      $selected_nids[] = substr($dval, (strrpos($dval, '(') + 1), -1);
    }
  }

  //dsm($selected_nids);
  if (count($selected_nids) > 0) {
    // Implode the exsting selected nids so we can pass them in autocomplete custom menu path.
    $nids_hsv = implode('-', $selected_nids);
  }
  else {

    $nids_hsv = '-';
  }
  // Loop through all added fields and get #autocomplete path updated.
  foreach ($form['field_article_test'][LANGUAGE_NONE] as $delta => $field_object) {
    if (is_numeric($delta)) {
      $form['field_article_test'][LANGUAGE_NONE][$delta]['target_id']['#autocomplete_path'] = 'sform/autocomplete/article/' . $nids_hsv;
    }
  }
}

In above code, I collect all selected nodes in variable $nids_hsv and pass to my custom auto complete menu callback so that I can exclude these nids while fetching nodes as options.

Does the form rebuilds on "Add new item" action, if so, Is this possible to update #autocomplete_path of the same field on rebuild of a form?

What you are trying to achieve is Selecting Unique values from Multi Value Reference field... I do agree using default widget you may run into duplicates...

I would say consider using below one of the modules which supports entity reference using which you can avoid duplicate entries while adding..

You can choose one from variety of options mentioned in above article which suggests using of

Using of Multiple Selects.
Using of Chosen
An additional possibility is the Dynamic Multiselect Widget.
Another option is Entityreference Views Widget
There is jQuery UI Multiselect
Improved Multiple Select

Hope one of the above works for you :-)


PaymentMethodManager() get plugin on NULL ubercart error Hi when trying to create an order in checkout state, the order gets created however when trying to view the order it errors out with the error below:

  Error: Call to a member function getPlugin() on null in Drupal\uc_payment\Plugin\PaymentMethodManager->createFromOrder() (line 45 of /srv/bindings/6204a08fb5564631b33e310ef75fe465/code/modules/contrib/ubercart/payment/uc_payment/src/Plugin/PaymentMethodManager.php) #0 /srv/bindings/6204a08fb5564631b33e310ef75fe465/code/modules/contrib/ubercart/payment/uc_payment/src/Plugin/Ubercart/OrderPane/Payment.php(50):

Ubercart version: Version: 8.x-4.0-alpha5+227-dev

My payment methods are all setup however in order creation code we don't need payment method. Anyone facing the same issue?

You can fix this error by applying the patch here: https://www.drupal.org/project/ubercart/issues/2826324


Is it possible to POST values to another page from the FORM SUBMIT function I have a module that allows authenticated users to book a "Facility" and then pay for it online. The module that facilitates the online payment is different from the booking module.

In the booking module I accept the details from the "authenticated" user in a form and in submit function I store the record in the DB with the following code

$form['$source'] = array(
  '#type' => 'hidden',
  '#default_value' => 'obb',
);

$form['uv_amount'] = array(
  '#type' => 'hidden',
  '#default_value' => $amount_final,
);

$form['description1'] = array(
  '#type' => 'hidden',
  '#default_value' => 'OBB - Booking Charges for ' . $hall_type_code . ' ON ' . $arri_date,
);

$form['#method'] = 'post';
$form['#action'] = '/mymodule/pgi/confirm';

In the module that handles the payment gateway I pass these values to the payment gateway after calculating the mandatory HASH values etc (as per the payment gateway integration document)

During testing I figured out that the values are not being posted to the PG page. Is there a way to post the values to the PG page after I store the booking/reservation details in the form submit function? Or is there a better way of accomplishing this. Would appreciate any help.

It sounds like you are doing a multi step form (given the URL in your form is "confirm"). You don't want to be looking at $_POST values, you'll want to utilize FormAPI all the way through.

See for examples:

http://www.sitepoint.com/building-multi-page-wizard-like-form-drupal/

http://jamesdavidson.io/blog/how-create-multi-step-form-drupal-7

http://www.webomelette.com/ctools-object-cache-multi-step-form


How can I use feeds tamper to remove currency ($) sign when importing prices? I have an integer field that I am using for price info (not commerce) and I am importing from a csv. I need to strip out the $ sign and a blank space after. "$ ". How can I do this with feeds tamper?

This is pretty easy.  You can use the "Find replace" tamper under "Text", and then user "$" as the search and "$ " as the replace.  If you want to be fancy you can use the "Find replace REGEX" tamper to make sure you only get the leading $.  IIRC, this needs to include the delimiters.  Using "/^\$/" as the search and "$ " as the replace should work (you need the ^ to anchor to the beginning and then escape the $.  Both of these plugins are part of the base feeds_tamper module.


How to generate a list of field items using the field item name programmatically in Drupal 7? I need a way to generate a simple list of all the items in a particular field. The field name is field_portfolio_description, and I'm looking to simply loop through the results and output each item into an unordered list. For example:

Item 1

Item 2

Item 3

Is there a way to do this programmatically without using a module like Views? I would also like to display the data in page.tpl.php not node.tpl.php. I tried checking out some Drupal functions like field_info_field but they weren't much help.

Update:

I've been working with the following function in my template.php file:

function blocks_preprocess_node(&$vars) {
  $node = $vars['node'];
  if ($node->type == 'portfolio') {
    $vars['description'] = $node->field_portfolio_description[LANGUAGE_NONE][0]['value'];
  }
}

However a quick var_dump($description) where I'm trying to access the data brings up null. Am I on the right track?

edit: fixed typo

You're pretty much on the right track. Try something like:

function blocks_preprocess_node(&$vars) {
  $node = $vars['node'];
  if ($node->type == 'portfolio') {
    $portfolios = field_get_items('node', $node, 'field_portfolio_description');
    $items = array();
    foreach ($portfolios as $folio) {
      $items['data'] = $folio['value'];
    }
    $vars['description'] = theme('item_list', array('items' => $items));
  }
}

Adding stuff to nodes like this is maybe better in hook_node_view() in a custom Module. Because you're altering the node's content before its shown (and its adding derived content to the node, not just changing some markup at the theme layer).

Code is untested and just Help. (but should mostly work)

Resources

theme_item_list function docs
field_get_items function docs
alternatively create a "Code Field" using Display suite to encapsulate this custom code field to a view_mode (aka, magic). See this tutorial on youtube on DS and custom fields.


Is there a way to programmatically add questions to a webform grid? I have seen hooks to use to alter webform options, but not the questions that appear on the left side of a grid.

I would like those questions to be a node titles actually of a content type that I have already defined.

For example, the content type titles will appear on the left and the options are already defined as first choice, second choice, and third choice radio buttons above in the header for each node title.

Here's the grid I would like to produce:

Node Title -- First Choice -- Second Choice -- Third Choice

Title One -- Radio Button -- Radio Button -- Radio Button

Title Two -- Radio Button -- Radio Button -- Radio Button

Title Three -- Radio Button -- Radio Button -- Radio Button

Title n -- Radio Button -- Radio Button -- Radio Button

Essentially I just need a way to import questions that are node titles of another content type into the webform Questions field that requires them to be inputted as pairs ex.

"safe_key|Some readable option"

"safe_key|Some readable option"

"safe_key|Some readable option"

Thank you very much.

Sure enough there is a way, a very neat one, just found it out myself!

In the following example I use a View's result to get the list of nodes I will use as the questions in the webform grid. This allows even easier management of the questions you want to display in your grid, by setting for example specific filters on your view.

You need to implement the hook_webform_component_render_alter hook. Here is the code you need:

function yourmodule_webform_component_render_alter (&$element, &$component) {
  // Select the right webform component
  if( $element['#type'] == 'webform_grid' &&
      $element['#title'] == 'Title of Webform Component' ) {

    // Override the title of the grid component
    $element['#title'] = "Node Title";
    // and use it as the label of the questions' column
    $element['#title_display'] = "internal";
    $new_grid_questions = array();
    // This is a standard content view that contains at least a nid and a node title field
    foreach( views_get_view_result('my_view', 'my_display') as $res ) {
      $new_grid_questions[$res->nid] = $res->node_title;
    }
    $element['#grid_questions'] = $new_grid_questions;
  }
}

And here is a screenshot of the end result:

Hope this helps!


Importing Content Without Including `nid` I have this site I develop, and the way the process works is that I have three versions of the same site: Production, Staging, and Development.

I've been working on some new features on Development, but over time, new content has been added to the Production version. Now that I'm done with the development for now, I'd like to copy the new Content Types + Nodes I've created in Development to Staging, which I've turned into a clone of Production, but I keep running into this issue: when I import content, it always includes the nid, so it overwrites content that has been created on the live site, which I can't have.

I've tried Features, Data Export Import, etc, but they all include the Node ID with the information, so existing content is always getting overwritten when I import.

What solutions are there for importing nodes WITHOUT also importing the Node ID with it? I essentially need to use Node Clone's functionality, except instead of creating the cloned node locally, it exports it to be created on the Staging site.

I think you should use Features and Universally Unique IDentifier.

When you update an existing node, thanks to UUID, it will be updated in production site because they should have the same UUID (but can have different IDs). If the UUID doesn't exist, then it will create a new node.


Array Flip Error Message on All Node Pages Hello i dont know where to begin. All of a sudden MY WEBSITE is displaying this error when i view a node-

  Warning: array_flip() [function.array-flip]: Can only flip STRING and
  INTEGER values! in DrupalDefaultEntityController->load() (line 178 of
  /home/onlineba/public_html/onlineplac.es/includes/entity.inc).
  Warning: array_flip() [function.array-flip]: Can only flip STRING and
  INTEGER values! in DrupalDefaultEntityController->cacheGet() (line 355
  of /home/onlineba/public_html/onlineplac.es/includes/entity.inc).

I havent added anything or changed anything. I was hoping it was because OG groups upgraded to 7.2 but i seem to get it when viewing a node that is not in a group. Let me see my page content type as thats got no OG fields attached or postable in groups.... yes exactly the same thing. its only got a title, body and image field attached to it. Oh and a term referance. Lets remove that...yes still the same.

Panels node page is disabled. Im sorry i cant tell you anymore about my problem but if anyone could be a lifesaver and offer any advice it would be gratefully reveived. I get really depressed when things like this happen. :(

thanks

Something is calling entity load with an incorrect $ids parameter.

This could be from something like node_load() or equivalent or node_load_multiple() or equivalent. If you pass in the wrong type of value into any of these you could end up with the error you mention.

If you want, add just above line 178 the line

print_r($ids);

Then reload the problem page and you will get a bunch of text print out.
Post the text back here (if you can upload files and there is a lot of output you could paste it in a txt file and post it).


How to remove core search index? I' switching core search to SOLR. The core search module still needs to be enabled for SOLR to work. How to I remove the (rather large) core search index?

The "search settings / clear index" option says that it won't clear the index and just update new items instead.

I came across search_reindex(). Do I just run that function?

If I'm reading the function correctly, search_reindex won't actually empty the search index - it just tells all modules that use search to start re-indexing content.

Uninstalling and re-installing the search module using the "unistall" tab at admin/modules will empty all of the search tables. You will have to temporarily disable all dependent modules to do this.

Alternately, you can empty these tables using the TRUNCATE mysql command. The tables needing to be emptied are search_dataset, search_index, search_total and search_node_links. You could also empty the tables using a database management tool - just be sure to leave the table structure intact - you want to empty the tables, not delete them.

You will then need to disable core search indexing to prevent the search index from filling back up. In your sites/default/settings.php file, you can add:

$conf['search_cron_limit'] = '0';

to prevent Drupal from adding items back into the index on cron runs (while still leaving the search module intact.)


What is the purpose of using node_submit() before node_save()? I am creating a node programmatically , In the code given in the link
http://timonweb.com/how-programmatically-create-nodes-comments-and-taxonomies-drupal-7
after creating a node,
the code goes as follows :

 $node = node_submit($node); // Prepare node for a submit
    node_save($node); // After this call we'll get a nid

node_submit() is a small helper function that makes sure the uid/author and creation date is set. Its main purpose is to map ->name to uid and ->date to created. Those two are used in the node edit/create form.

So if you set these two properties yourself anyway (and the validated flag but I haven't found anything that cares about it, likely some sort of left-over from earlier code), there is no need to call it.


Show all children of a specific taxonomy term using Views exposed filters I have a Views exposed filter that checks nodes with specific terms. I can't seem to find an option to display all children of a term if the parent term is selected.

For example, I will outline a vocabulary:

Parent 1
 - Child 1
 - Child 2
 - Child 3
   - Another child
Parent 2
 - Child again

If I select "Parent 1" as part of my filtering process, it will display any nodes tagged with that Term. However I'd like it to display all children as well as just the term.

Contextual filters (in the Advanced section) has a parent filter.

Also if you add a Relationship to parent you can make use of that within normal filters.


Why do I get this error when I try to use db_change_field()? My Drupal installation has a table with a field title of type varchar and length of 255.

For some custom process, I need to increase the length to 500 characters.

I tried doing so with the following code:

function mymodule_schema_alter(&$schema){
    if( isset($schema['field_data_field_document_title']) ){
        db_change_field('field_data_field_document_title', 'field_document_title_value', 'field_document_title_value',
            array(
                'length' => 11,
            )
        );

    }
}

Originally I had that code in my .module file. When I flushed caches I could verify using the DEVEL module that my field length changed. But in phpmyadmin the field length remained 255.

Then I migrated the function to the .install file. I execute run updates and get the following error:

  PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'DEFAULT NULL' at line 1: ALTER TABLE {field_data_field_document_title} CHANGE field_document_title_value field_document_title_value DEFAULT NULL; Array ( ) in db_change_field() (line 3020 of /var/www/Intranet/includes/database/database.inc).

I could really use some help, please.

Check the documentation for hook_schema_alter(): db_change_field() is not supposed to be used there, instead change the $schema array to the required structure.

function mymodule_schema_alter(&$schema){
    if( isset($schema['field_data_field_document_title']) ){
        $schema['field_data_field_document_title']['fields']['field_data_field_document_title_value']['length'] = 500;
    }
}

However, if the module is already installed and has existing data (seems like this is the case), then a call to db_change_field() inside a hook_update_N() implementation is necessary to update the schema.

function mymodule_update_7100() {
    $table = drupal_get_schema('field_data_field_document_title', TRUE);
    db_change_field('field_data_field_document_title', 'field_document_title_value', 'field_document_title_value', $table['fields']['field_document_title_value']);
}

Note (if there is existing data): both these functions need to be included in mymodule.install, as the second function depends on the first: the change of field length made in mymodule_schema_alter() will be included in the table schema returned by drupal_get_schema().


hybridauth redirection to an emailed link after success login Im using hybridauth to let users login from different social media websites ...
I send emails manually to some users with an link to edit specific nodes (for example http://example.com/node/444/edit?parma1=val1&param2=val2).
At that moment the user is automatically redirected to a page to choose a social media he want to login with.
Im using hook_init for this :

function MYMODULE_init(){
  if($node->type == 'type' && other conditions){
    drupal_goto('link_to_hybridauth_login_page');
  }
}

Now I want that user to be automatically redirected to that link sent via email after success login via hybridauth ( I tried to add destination query inside drupal_goto but not working.)

how can I do this redirection ?

Thanks in advance.

How did you try to add the 'destination' query? It should be something like this:

$query_array = array('param1' => 'value1', 'destination' => 'original_path');
$options = array(
  'query' => query_array,
);
drupal_goto('link_to_hybridauth_login_page', $options);

Basically, it's important that the destination is passed as part of the $options['query'].

If that doesn't work, try and add your own hook_user_login(), to pick up the 'destination' (or whatever parameter you want to use for the original URL, and redirect the user accordingly). Like:

if (isset($_GET['destination'])) {
  drupal_goto($_GET['destination']);
}

You can see an example implementation of hook_user_login in the user_homepage module code: http://cgit.drupalcode.org/user_homepage/tree/user_homepage.module?id=6803e00

Hope this helps with your problem.

EDIT: The hook_user_login() is meant to be something additional to the hook_init() logic you were trying, but not to replace it. Thought I'd just clarify that =).

EDIT 2: Ok, So if I'm getting the problem right, you need to get not only the 'node/xxx/edit' part of the URL, which you have already sorted (right?) but you need to also get all the params of the incoming URL.

Basically, you need to use drupal_get_query_parameters() for that. So you could assemble the $options array like this:

  $current_query_params = drupal_get_query_parameters();
  // Pick up URL and treat params as you need, and prepare query array with
  // the 'destination' desired, assembled with data from $current_query_params.
  $new_query_array = array();
  $options = array(
    'query' => $new_query_array,
  );

Hope I'm getting it right now. The linked drupal code from user_homepage uses these functions for a very similar scenario. Look at user_homepage_build_homepage_path_from_request() and user_homepage_user_login() functions.


hook_field_schema not being used I'm trying to create a field with an additional property (or column) to define an extra relationship to a taxonomy term.

I have this in my module file:

/**
 * Implements hook_field_info().
 */
function emtr_field_info() {
    return array(
        // We name our field as the associative name of the array.
        'field_emtr_denominations' => array(
            'label' => t('Denominations'),
            'description' => t('Field linked to target entity as well as denomination taxonomy term holding denomnation value.'),
            'default_widget' => 'number',
            'default_formatter' => 'number_decimal',
        ),
    );
}

And this in my install file:

/**
 * Implements hook_field_schema().
 */
function emtr_field_schema($field) {
    $columns = array(
        'denomination_value' => array(
            'type' => 'int',
            'not null' => FALSE,
        ),
        'denomination_tid' => array(
            'type' => 'int',
            'not null' => TRUE,
            'default' => 0,
        ),
    );
    $indexes = array(
        'denomination_tid' => array('denomination_tid'),
    );
    return array(
        'columns' => $columns,
        'indexes' => $indexes,
    );
}

/**
 * Implements hook_enable().
 */
function emtr_enable() {

    field_cache_clear();
    field_associate_fields('emtr');

    if (field_info_field('emtr_denominations')) return;

    // Create a field for denominations to be used by safe checks and till reads
    $field = array(
        'field_name' => 'emtr_denominations',
        'type' => 'field_emtr_denominations',
        'cardinality' => FIELD_CARDINALITY_UNLIMITED,
        'translatable' => FALSE,
    );
    field_create_field($field);

    // Attach the emtr_denominations reference field to safe checks instance
    $instance = array(
        'field_name' => 'emtr_denominations',
        'entity_type' => 'emtr_safe_check',
        'bundle' => 'emtr_safe_check',
        'label' => 'Denominations',
        'required' => false,
        'widget' => array(
            'type' => 'number'
        ),
        'settings' => array(
            'target_type' => 'emtr_safe_check',
            'handler_settings' => array('target_bundles' => NULL),
        ),
        'display' => array(
            'default' => array('label' => 'inline', 'type' => 'number_integer'),
        ),
    );
    field_create_instance($instance);
}

But after uninstalling and re-enabling my module (drush devel-reinstall emtr -y
) a table called field_data_emtr_denominations is created but it does not have my 2 custom columns.

At what point in this process should I tell Drupal to use my custom field_schema?

You should remove function emtr_enable() out of the .install file, and place its code in a more proper hook where the field is meaningful to be created, like for instance hook_node_type_insert() or EntityAPIController-derived class for your entity bundle, etc.  It depends on what one wants to achieve really.


How to post three nodes of same content type in three different blocks in the front page? I have already set the block regions in both my page--front.tpl.php and site.info files, created the custom content type and created the content that should be displayed on each of them....now how am I supposed to post this in the front page? I was told I should use Views for this with no much further explanation and I'm following some nodeone's screencasts on views... but I'm not really sure what I'm looking for here. Any hints?

Create 3 separate block views, each will display 1 node. make sure they are offseted.

This will display 2nd top node of the content type 'automobile' that is promote to front page.

Then configure them at admin/structure/block


How to avoid "The form has become outdated" after login in separate tab I've read this and this and I can't see how to apply that to my situation, so asking another question.

not-logged in user visits a page with a form on it.
User opens a new tab and logs in.
User switches back to their first tab and tries to submit the form.
Gets the outdated error.

How can I accept the anonymous form submissions once logged in?

In my application it's quite possible that the user has quite a few pages open in different tabs before they log in.

The error is related to form CSRF protection, the error message comes from core form validation.

To avoid the error, it's possible to remove that CSRF token validation check in hook_form_alter e.g:

function my_module_form_alter(&$form, &$form_state, $id) {
  if (strpos($id, 'webform') === 0) {
    // Bypass per user CSRF token check and allow cache.
    unset($form['#token']);
  }
}

The caveat is, the form will no longer have default CSRF protection.

Alternatively, you might be able to detect the user has logged in (e.g custom local storage set event) and reload the original page to refresh it as is.


how to combine profiles and content types in a view I'm trying to filter some content with a view, But view provides access to single entity type. I want to add the fields from profiles and content types. I'm wondering Is it possible to include both contents and profiles in a single view. I have spent lot of hours searching on web to find a solution for this, but didn't helped.

In this image I have selected content and it allows only to access the elements of contents. But I also want to filter the result by matching the contents of a content type and a profile.

Can anyone provide me a better solution to solve this problem....

With Content-type view, you can use the "relationship" feature in Views and have access to the profile fields of the author of a certain node that is listed in the view. The same is valid for the Filters of that view.

To do so, edit your view and expand the "Advanced" settings section on the right. Then click on Relationships -> Add and add the relationship "Content: Author".

Hope that helps.


Entity registration, register to more event from one form in event detail Hi I have created special content type called Event. It is simillar to facebook events. It has description, address where it will be held and date when it will be held. I succesfully added there registration form with Entity registration. So now I can register to one event. But I want to be able to register from one event to more events like this.

In event detail, registration form section, I want to have checkboxes. When I click on these checkboxes and click on register to event, it will register me to every clicked event, and to opened event too. These additional event, I will select in administration, when creating new event.

Install VBO module, create a entity view with checkboxes. See the Rules sections here. You can use that rule in VBO to register them automatically to the Events they selected.


fonts/glyphicons-halflings-regular.woff2 404 error Our drupal site uses fonts/glyphicons-halflings-regular.woff2 through bootstrap v3.3.2. But I am getting 404 for the file fonts/glyphicons-halflings-regular.woff2.
Is it some issue with the bootstrap? What is proper way to fix this?

wget https://github.com/metaskills/less-rails-bootstrap/raw/master/app/assets/fonts/twitter/bootstrap/glyphicons-halflings-regular.woff2
and move it to the openatrium/themes/oa_radix/assets/font directory.
Here: https://www.drupal.org/node/2625784


Upload Data From Excel Sheet to taxonomy I have 4 Excel sheets like:

First (35) Records:
State Code | State Name

Second (650) Records:
State Code | District Code | District Name

Third (6500) Records:
State Code | District Code | Block Code | Block Name

Fourth (650000) Records:
State Code | District Code | Block Code | Village Code | Village Name

I want to upload from Excel sheet based on State Code or sequence hierarchical records to taxonomy.

Adding them one by one is very difficult task.

I have a module for Excel import, but matching of record of parent is necessary like : State -> District -> Block -> Village in taxonomy

So how to upload these records to taxonomy (with no headache)?

Try Taxonomy CSV import/export

  This module allows you to import or export taxonomy from or to a CSV
  (comma-separated values) file or with a copy-and-paste text.


Would disabling these following functions in PHP.INI affect Drupal 7? If i disabled the following php functions:

disable_functions = escapeshellarg,escapeshellcmd,exec,ini_alter,parse_ini_file,passthru,pcntl_exec,popen,proc_close,proc_get_status,proc_nice,proc_open,proc_terminate,show_source,shell_exec,symlink,system

would this affect drupal 7 in anyway? I am disabling them to increase security on my server. This was mentioned on securing an Invision powerboard forum.

Yes, that may cause odd debug issues down the track.

Some of those are required by drush:

i.e:

escapeshellarg
escapeshellcmd

symlink is used in system.tar.inc

Modules such as devel and advanced_help use parse_ini_file

Other contrib may use others, e.g print_pdf uses proc_open


Create chart for user count of user role using chart module(c3 lib) in Drupal 8? I want to use chart module(c3 lib) of drupal 8 to show a chart of user count for different roles using views.
E.g.

Role Name  Total user
a             5
b             10
c             13

I achieved above table using aggregation in views. I followed this guideline to create a chart but when I create chart attachment and add it to parent, the value of child replace the value in the parent chart.It should merge.
Any help would be appreciable.

This is an issue of needing to be sure that you first set the format of the attachment display to "This chart attachment (override)", and then adjusting the format settings. Don't forget to attach your "Chart attachment" display to the appropriate display.

I wanted to set the style plugin to do this by default (see this issue: https://www.drupal.org/project/charts/issues/2899035), but I am unable to find any documentation on how to do this programmatically.