Enable Relationships in Views with Entities? I am creating some custom entities and one of them will need to contain a helper table to store a lot of data against one entity (event dates, prices, and tickets left). This is not a Commerce based app, we simply need to display the data appropriately as we receive it all from a third party service.

What I would like to do is rewrite the Entity implementation and not use Fields, but store this all as Properties, which will require its own table and fields with the proper foreign key back to the main Entity. Currently, it is all stored in Field Collections, which can be difficult to work with (Importing/Exporting the entity, or installing/uninstalling the module- FCs are just hard to script, attach, and add fields to in my experience).

So, assume:

entity
entity_event

I can get the data in and out fine.

With Views, how do I tell the Entity there is a relationship available here by the ID? When I am searching them with Views, I need to allow a search by date, AND that the event itself has tickets left (tickets wont be a exposed filter).

I assume too, that when buildContent() is called on the Entity to view it, here I attach the additional data from the event table?

You will need to use (or override) the views_handler_relationship class to create the relationship, and also use hook_views_data_alter(&$data) to tell views how to use the handler and with which tables/columns it applies.


CSS to define where a image is located on each Node Short version: How do you use CSS to define where a image is located on each Node?

I AM NOT TALKING ABOUT IMAGE STYLES: https://drupal.org/documentation/modules/image#styles

Long version of my question:

I have created a content type call image_content, in which I can create a node and upload a image to that node. That works great! but now what? I mean if load 10 images one one node, the are lined up hortizonaly, and thats pretty ugly. How can I use CSS to change the style of the images per node.

Now I understand, I could create a photo gallery, but I want more control of how each image is displayed. Example my background looks like a empty room. On node created by the image_cotent, I might want a image1 far left, and image2 far right. Basic CSS understanding can do this, but how would I do this node? The reason is I might want the images on node2 have a left-margin of 50px, but images on node1 to be margin-right-0px

Does this make sense?? PLEASE provide example if you can!

If you look at the body tag in view source or firebug you should be able to see a list of CSS classes assigned to class attribute; Ex. class="html not-front page-node page-node-1"

So you should be able to style each node different than other nodes based on the node ID

CSS example:

/* node 1 styles */

body.page-node-1 .title {
  color: #333;
  background-color: blue;
}

body.page-node-1 .field-name-field-image {
  position: absolute;
  left: 100px;
  top: 100px;
}

/* node 2 styles */

body.page-node-2 .title {
  color: #000;
  background-color: yellow;
}

body.page-node-2 .field-name-field-image {
  position: absolute;
  left: 200px;
  top: 200px;
}

I hope this will help you.


Allow VIEWS accessing PARAGRAPHS fields collection I have a content type called "Slideshow" where users can create any number of "slideshow" nodes.
This content type has a field called "Slide" which is a field collection of other fields (caption, image, description, and link). The user can add multiple "Slides" to each "Slideshow" node  (I can achieve this with the help of either PARAGRAPHS or FIELD COLLECTION modules).

Then I use VIEWS to create Blocks of the "Slideshow" content type to display specific nodes using contextual filter Nid.

MY PROBLEM IS:
In VIEWS I can only list "title" and "slide" fields (as  rendered) of the "slideshow" content type, whereas I need to list the fields inside the "Slide" field (the caption, image, description and link) so that I can customize them using VIEWS.
Is there any way to achieve this? (allowing VIEWS to access the fields of PARAGRAPHS module).

POSSIBLE SOLUTIONS:
In VIEWS I added a relationship "Slide", this allowed me to list the fields inside "Slide" field. the problem is that I'm trying to avoid relationships as it uses a lot of LEFT JOINS and this may decrease performance.
my website uses lots of these slideshows and galleries multiple time in the same page and I don't want to lose performance.

Any help will be much appreciated.

In D8 your View's are automatically cached; thus, your query is results are cached, so I wouldn't worry too much about this. Nonetheless, you can enable Show performance statistics in views settings (/admin/structure/views/settings), to see how long it takes.

Testing with 1 field, the View Render Time is ~1.20ms faster when you create a View of Show: Field Collection Item and then add relationship to node rather than a View of Show: Content with a relationship of field collection.


How to View of commerce products with image from product_variation Drupal 8, commerce 2: I would like to make a a view of commerce products and show a) the title of the product b) the image of one of the product_variations, e.g. at delta 0.
What I have done:
* view of products

add relationship to product_variations
add the variation image field for display

-- this gets me a list of products and images, but it is in essence a list of variations, with the product title repeated over the different images, so

I turn on aggregation and

-- I get this error: Table 'mytable.commerce_product_variation__field_variation_image' doesn't exist:

WITHOUT the product_variation image field and aggregation on, I have the correct list of product titles.

This seems like a pretty basic need for a view of products, without we put an image field directly on the product.

One alternative I have explored is to do a rendered entity of the Product and make simplified view modes for the product_variation and product, then set the display mode for the entity in the view, but I will have to customize the field display for every type of product_variation and product I have, and in my one test its still not right, giving me duplicate variation images stacked under the product title, and there is no way to specify "link to content" when using the rendered entity, or do any custom buttons as you might do using fields. I suppose its possible to get this way to work using twig templates, but it seems a lot tougher than if we could have a working aggregation while using a relationship.

Here's how I did mine :

View of products
Add relationsip: variation image
Add that relation in the fields displayed (You'll now get all the images for the product
Add a field Product variation delta
Add a filter with the delta which equals to 0 (which will show the image of the first variation).

It's not perfect as if the first variation as no images, it think it won't show up... But it should fits quite some cases.


CAPTCHA default for Blog post forms does not work in Drupal 7 I'm trying to get CAPTCHA to be automatically added to my blog post forms so that I don't have to enable it individually on each blog post. I've followed the suggestion on this post, but unfortunately, this doesn't work for me. I've enabled everything that I should, but the CAPTCHA doesn't work for blog posts unless I manually enable them per post. This is not practical. I've used the CAPTCHA module fairly extensively before, so I understand how it works, but it's just not doing what I've told it to do.

Does anyone know what may be keeping my site from enabling CAPTCHA as the default for blog posts?

Following the same post you saw, this time use "comment_node_blog_form" as your form id, or "comment_node_CONTENT_TYPE_form" if your content type is not called blog


How do I keep the cron from removing a poll from my front page? I am running Drupal 6 and cron from my crontab. I created a poll on a site that I have inherited and moved it into the first sidebar where it appeared until the cron ran. I can duplicate this (cron runs every hour) . How do I keep it from doing this?

I would highly recommend Elysia Cron, it allows fine grained control of crons provided by modules (ie poll) in which you can completely disable the cron of a specific module (or change the timing from the global setting for that specific module's cron; in your case, 1 hour), which seems like something you might need to try out.  See attached for an example settings screen on a D6 site (the checked boxes mean that cron is disabled).


How to get field value from referenced entity inside a field collection My structure is as follows:

I've got a custom contenttype with a multivalue field containing a field_collection. In this field_collection there are an amount field, a entity_reference_field and a computed_field. The referenced entity also contains several fields.

What I need to do:

Step 1:
In the computed field (inside the collection) I need to get the value of a certain field of the entity, referenced by the entity_reference field (also inside the field collection) and multiply this value with the value of the amount field.
Step 2:
In another computed field (on the node itself) I need to sum up all the values of all the computed fields inside these collections.

My Problem is primarily Step 1

Based on what I read in the computed_field documentation, you have two options when creating the necessary code to compute the field. You could create the PHP into the text area of the field (I really dislike PHP in the database...but that's just me) or you can create a custom module with a specific function in it. Per the documentation:

Drupal 7

To use a function in a custom module instead of writing the code in text area create a function that looks like:

<?php
function computed_field_YOUR_FIELD_MACHINE_NAME_compute(&$entity_field, $entity_type, $entity, $field, $instance, $langcode, $items) {
  $entity_field[0]['value'] = 'value';
}
?>
Parameters:

&$entity_field - The computed field. Used to store the computed value.
$entity_type - The entity type: node, user, comment, etc.
$entity - The actual entity (a node, user, comment, etc.)
$field - General field settings.
$instance - Field instance settings.
$items - The list of items.
Note:
Make sure $entity_field is passed by reference.

What is awesome about this method is we have the entity available to us via $entity (in your case, it would be an entity of type field_collection). From this approach, I would:

Create a custom module with this function
I would then create logic around calling the $entity variable, loading the entity (if required) and then getting it's entity reference, which will probably require another entity load.
Do compute field logic that you'd like.

Once this is done, you can use the same custom module to write another computer_field_YOURFIELD_compute() function for your initial field (on the node) that computes the combination for all field_collection computed field values.


How to have various 'access denied' pages depending on URL I'm trying to make multiple access denied pages and show the relevant one based on the page attempted to view.

Use case:

User is limited to only one "CV" node. If they try to create another, they get an access denied page. I want to display a custom page that says something like, "You can only create one CV". A different access denied page, resulting from a different url, would display a different message.

Is this possible? The only solutions I've found seem to create a single page for all access denied notifications.

Cheers,
Oliver

I think you what you need is: hook_node_access($node, $op, $account)
https://api.drupal.org/api/drupal/modules!node!node.api.php/function/hook_node_access/7

Parameters

$node: Either a node object or the machine name of the content type on which to perform the access check.

$op: The operation to be performed. Possible values:

"create"
"delete"
"update"
"view"
$account: The user object to perform the access check operation on.

Base on the return values, you can redirect them to custom error page.
Example:

function hook_node_access($node, $op, $account) {
  $type = is_string($node) ? $node : $node->type;

  if (in_array($type, node_permissions_get_configured_types())) {
   if ($op == 'create' && user_access('create ' . $type . ' content', $account)) {
    $query = drupal_get_destination();
    drupal_goto('node/custom-error-page',$query);
   }
 }


Removing field from form I just came across a solution regarding media module.
It suggested that:
replace all
unset($form[$id]);

to
$form[$id] = array('#language' => NULL);

in media_gallery.module
This worked nicely for my problem, but I do not understand what it actually does.
The unset is used when we want to remove a field from a form, fx when someone does not have access to the form.
Is the 2nd equivalent of the 1st?

The first statement essentially removes a field from the form. The second statement sets the field's language to undefined (neutral). They are not the same, but they both help you to deal with this module's issue as they both prevent the form from passing invalid keys to locale_field_node_form_submit().


How do I display a field from a referenced user? I have a content type A with a reference to a user and I would like to show a specific field from that user in nodes of that content type.

How can I achieve this?

You might achieve this with Views, by creating a view for nodes of that content type, and then adding a "relationship" to the user. The user fields will then become available for you to display.

You can find an introductory tutorial to start using Relationships with Views in "How relationships work in Views and how to add a referencing entity relationship".


Creating a block programmatically in a theme on Drupal 8? So I was hoping to have my theme create special blocks for different parts of the front page so that they can be moved around easily later. I added the files to mytheme/src/Plugin/Block/BlockName.php but they never show up anywhere on the site or the block manager even after clearing cache.

Here's the code for one of my blocks (MediaPanel.php):

<?php
/**
 * @file
 * Contains \Drupal\mytheme\Plugin\Block\MediaPanel.
 */

namespace Drupal\mytheme\Plugin\Block;

use Drupal\Core\Block\BlockBase;

/**
 * Provides my custom block.
 *
 * @Block(
 *   id = "media_panel",
 *   admin_label = @Translation("Media Panel"),
 *   category = @Translation("Blocks")
 * )
 */
class MediaPanel extends BlockBase {

/**
   * {@inheritdoc}
   */
  public function build() {
    return array('#markup' => 'hello world');
  }
}

?>

Do I have to use a module for creating Blocks? It would be inconvenient to have to make a module to create blocks that will be specific to my theme anyway.


Setting link target through views programatically I have a text field that turns its value into a link, provided it's an absolute link. For some reason, setting the target to blank is not working. Am I doing something wrong? I set the target inside the array.

elseif (valid_url($row->{$view->field['field_myDoc_link_value']->field_alias}, TRUE)) {
  $fields['title']->content = l(
    $fields['title']->content,
    $row->{$view->field['field_myDoc_link_value']->field_alias},
    array('target'=>'_blank', 'html' => TRUE)
  );
}

Or would I set it somewhere else? Thanks!

Your problem is that you need to define the target under attributes, so

array('target'=>'_blank', 'html' => TRUE)

should instead be:

array('attributes' => array('target' => '_blank'), 'html' => TRUE)


Panel page title with date field I have a panel page with title set to %node:field_pub_year from substitution list. field_pub_year is a date field which is to select publication year. My problem is this is displaying whole date like '2012-01-01 00:00:00' as title. Is it possible to show only '2012' as title.

Thank you.

In theme_preprocess_page hook

    // CIsSharp, 07/23/2013: For 'projects' page, only display year as title
    if (isset($variables['node'])) {
        if (isset($variables['node']->type) && $variables['node']->type == 'projects' &&
            isset($variables['node']->field_pub_year)) {
          $date = strtotime($variables['node']->field_pub_year[LANGUAGE_NONE][0]['value']);
          $year = date('Y', $date);
          $title = $year . ' Project';
          drupal_set_title($title);

          // Because breadcrumb creation executes before preprocess
          // Fix breadcrumbs title also
          $crumbs = drupal_get_breadcrumb();
          if (count($crumbs) > 0) {
             $crumbs[count($crumbs) - 1] = $title;
             drupal_set_breadcrumb($crumbs);
          }
      }
   }


Setting up regex-style rewrite rules within Drupal? I have a couple of legacy rewrite rule redirects that I've traditionally put in .htaccess. For instance, paths are of the format:

story/[story:title]

And paths like:

story/[story:nid]

redirect to that.

Is there any way of setting up regex-matching redirects within Drupal? I could always do it in .htaccess, but that would get overwritten on the next Drupal core update. Further, it seems that Boost is nerfing any redirect I put in .htaccess -- the above hasn't worked since I installed its redirect rules.

Thanks!

Well if you are familiar with PHP and preg_match, you could theoretically install Drupal rules module and write custom rules using PHP to redirect pages inside Drupal without touching .htaccess file.


Bundle fields for entity without type config entity not created I have entity that has bundles defined in code(hook_entity_bundle_info) and does not use config entity. It also defines fields for each bundle in \Drupal\Core\Entity\FieldableEntityInterface::bundleFieldDefinitions. But when I install the module the bundle fields are not created, only the base fields.

According to documentation this is possible and config entity is not needed to provide bundles and fields. So do I have to manually create the fields in hook_install or I'm missing something here?

If I run the following code only one field will be created out of 11. Strangely that field is my custom field that I've defined in the my module. Others(string, entity reference..) are left out.

  $entity_type_id = 'resource';
  $entity_type = \Drupal::entityTypeManager()->getDefinition($entity_type_id);
  $bundles = \Drupal::entityManager()->getBundleInfo($entity_type_id);
  $update_manager = \Drupal::entityDefinitionUpdateManager();

  foreach (array_keys($bundles) AS $bundle) {
    $fields =\Drupal\mymodule\Entity\Resource::bundleFieldDefinitions($entity_type, $bundle, []);
    if (!empty($fields)) {
      foreach ($fields AS $name => $definition) {
        $update_manager
          ->installFieldStorageDefinition($name, $entity_type_id, $entity_type->getProvider(), $definition);
      }
    }
  }

If I run the following code the fields are present, so it's not an issue with definition.

\Drupal::service('entity_field.manager')->getFieldDefinitions('my_type', 'my_bundle');

I found few references on the internet for hook_entity_field_storage_info but so far I have no idea what to do with it.

This is not answer to the problem I had but a workable solution nonetheless.
In the end I have created custom entity per each "bundle" that I have initially planned.

It actually resulted in less tables and also it provided option to handle logic that I have initially planned to do via plugins.

The only drawback of this solution are some route handlers where I have to provide the entity type via option parameter in order to be able to use single handler to get a page title, for example, due to the variable name "restriction" in route handlers.

Also in entity references or entity loader I have to use entity type only instead of entity type and bundle but that's totally fine.

I am using single entity base class, the same forms and so on so not that big of a deal(for now).


Do features uninstall variables when a module is uninstalled? I have created a module using The Features module. The module exports some variables using the Strongarm module.

If a person installs the module and then uninstalls it, will those variables be removed?

No, it does not. Features do not implement an uninstall hook, and as such don't get a chance to clean up after themselves.


How Admin can logout other users? The users can logout visinting my-site.com/logout by themselves
But is there any way Admin can logout other users?

If you go to admin/user/user, you can block the user, which will cause them to be logged out.  After that, if you want them to be able to login again, you can just immediately unblock them.  Also, if you as an admin change a user's password, they will be logged out and will have to use this new password to log back in.

If you want to get fancy, you could do something like this in a custom module as well:

function YOURMODULE_user_operations($form_state = array()) {

  $operations = array(
    'logout' => array(
      'label' => t('Logout the selected users'),
      'callback' => 'YOURMODULE_user_operations_logout',
    ),
  );

  return $operations;

}

function YOURMODULE_user_operations_logout($accounts) {
  foreach ($accounts as $uid) {
    sess_destroy_uid($uid);
  }
}

which would add a "Logout the selected users" option to that menu as well.


Map Views fields from custom query I have a view and I want to override the query by writing my own using the Database API of Drupal. I already wrote a function that overrides the query and returns the result set I need:

function kviews_views_pre_execute(&$view) {

if($view->name === 'custom_fans_evolution'){

    $sql = db_select('node', 'n'); //Initial table select

    $sql->join('field_data_field_metric', 'm', 'n.nid = m.entity_id'); //Join the metrics table
    $sql->join('field_data_field_values', 'v', 'n.nid = v.entity_id'); //Join the values table
    $sql->join('field_data_field_page_connection', 'p', 'n.nid = p.entity_id'); //Join the pages table
    $sql->join('field_data_field_value_date_date', 'd', 'n.nid = d.entity_id'); //Join the dates table

    $sql->fields('n', array('title')) //Add fields - chained
    ->fields('d', array('field_value_date_date_value'))
        ->fields('v', array('field_values_value'))
        ->condition('m.field_metric_value', 'page_fans', 'LIKE')
        ->condition('p.field_page_connection_tid', 69, '=')
        ->condition('d.field_value_date_date_value', strtotime(date('Y-m-d')), '<')
        ->condition('d.field_value_date_date_value', strtotime(date('Y-m-d').' -8 days'), '>')
        ->orderBy('field_value_date_date_value', 'ASC') //Order results - chained
        ->range(0,15); //Limit results - chained

    $view->build_info['query'] = $sql;

}
}

The query executes successfully, in PHPMyAdmin it returns the right data and in the preview window of the view it displays the right amount of rows. All I get though is the label of the field I choose in the UI:

How can I map the fields I get from the query to the fields I add to the Views UI? Or maybe I need to add the fields to the view using a hook?

Thanks!

One solution I found is to add PHP fields for the data you want to present into the view. The variable $data that holds what was retrieved from the database, per row, is printed this way:

print $data->[alias];

Where [alias] is the field alias from the database, without the brackets (ex. in $sql->addField('n', 'title', 'node_title') the alias is node_title).

This solution is not as clean as I would like so I will wait for more, "cleaner" answers before accepting this one.


A strategy question regarding content types vs. basic pages plus taxonomy/tags I'm having trouble deciding what makes more sense. I am building a somewhat simple site and so far it seems fairly straightforward to use the basic page content type for nearly everything and add a field for taxonomy (to associate the page with the categories of the main menu) and if needed, tags to further categorize the pages for various views and lists. But is that the best strategy? The end-user is going to have to remember to choose a taxonomy term for each page, and choose the right one. If a tag is needed, they are going to have to remember to add a tag and spell it correctly. People are notoriously unable to do simple things like this without making mistakes. So, would it be better to create separate content types for each main menu category, even if they basically are the same basic page content type? If I did separate content types, I wouldn't have to ask people to select an item in the main menu taxonomy. I would still have to ask them to tag some of the content types, but I could leave that field off for those content types that don't need tags. But then I'd be faced with having to instruct the end-user to select the correct content type before creating a new page.

What is your opinion? Is there a better strategy among these choices or perhaps even another choice I didn't consider?

You could use radio buttons for your 'content type' taxonomy terms and make it required.  That way your user sees all the content types available and has to pick one.  For your free tagging, you might be able to use a module like Active Tags to make it a bit more accurate as well.


Custom module and block API Have followed all the steps at http://www.packtpub.com/comment/reply/7089 to create a custom module.

I am able to create it and it is showing under the Modules and is getting enabled. However as the purpose of this module is to create a new block it is not doing so. Its not showing under the Structure/Blocks. Any reasons?

name = First
description = A first module.
package = Drupal 7 Development
core = 7.x
files[] = first.module

;dependencies[] = autoload
;php = 5.2

/**
 * @file
 * A module exemplifying Drupal coding practices and APIs.
 *
 * This module provides a block that lists all of the
 * installed modules. It illustrates coding standards,
 * practices, and API use for Drupal 7.
 */

/**
 * Implements hook_help().
 */
function first_help($path, $arg) {
  if ($path == 'admin/help#first') {
    return t('A demonstration module.');
  }
}

/**
 * Implements hook_block_info().
 */
function first_block_info() {
  $blocks = array();

  $blocks['list_modules'] = array(
    'info' => t('A listing of all of the enabled modules.'),
    'cache' => DRUPAL_NO_CACHE,
  );

  return $blocks;
}

/**
 * Implements hook_block_view().
 */
function first_block_view($block_name = '') {
  if ($block_name == 'list_modules') {
    $list = module_list();

    $theme_args = array('items' => $list, 'type' => 'ol');
    $content = theme('item_list', $theme_args);

    $block = array(
      'subject' => t('Enabled Modules'),
      'content' => $content,
    );

    return $block;
  }
}

Let you try with this code. Clear performance cache.

function example_block_info() {
  $blocks['my-block-id'] = array(
    'info' => t('Block Name'),
  );
  return $blocks;
}

/**
 * Implementation of hook_block_view().
 */
function example_block_view($delta='') {
  $block = array();
  switch ($delta) {
    case 'my-block-id':
      $block['subject'] = t('Block Name');
      $block['content'] = example_contents();
      break;
  }
  return $block;
}

/**
 * custom html block
 * @return string
 */
function example_contents() {
  return '

      Hello World, this is a example custom Block

  ';
}

For more info see this http://www.summasolutions.net/blogposts/how-create-basic-block-code-new-drupal-7


How to make live node preview? I need an instant preview of what an entire node will look like before getting published. Ideally preview gets updated by every change user makes to the form., probably in an iframe beside the form.

The closest I can get is using Page Preview Module, but I need it without the context of a fully rendered page and without having to click preview button.

Have you looked at the Spark distribution?

Rather than placing the preview next to the form as you propose, the Quick Edit module (in-place editor) allows you to edit certain fields while they're still in their original context. The Responsive Theme Preview might also be useful to you.


Render simple php function in twig template I am rebuilding a website in Drupal 8 and the website shows some content with bootstrap classes according to a conditional php function based on time of day

function openStatus(){
$open_str = 'Open until 5pm';
$closed_str = 'Closed - Open Mon-Fri 9AM-5PM';
if(gmdate('N') <= 5 && gmdate('H') >= 8 && gmdate('H') <= 16){
echo $open_str;
} else {
echo $closed_str;
}

This is what I have so far, which I think works but not sure how to do day of week.

{% if "now"|date('H', "Europe/London") >= 8 && "now"|date('H', "Europe/London") <= 16  %}
Open until 5pm
{% else %}
Closed - Open Mon-Fri 9AM-5PM
{% endif %}

Would suggest doing a pre-process function and stuff in the variables everything the template needs to render. The point of Twig is to push the logic back to the PHP side so that your template does not look like "HTML-in-PHP" or "PHP-in-HTML" (whichever way you look at it) as with previous versions of Drupal.


Profile2 and Panels in Drupal 7 How can I override a Profile2 profile page using Panels in Drupal 7?

The page I'm looking to override is the edit for for one of the new profile2 pages.  Here is an example URL: http://example.com/profile-user_settings/%uid/edit

There is a work around using Page Manager Existing Pages (as suggested by Letharion) and hook_menu().

hook_menu() was required as Profile2 doesn't seem to register profile pages with the menu router. This was preventing Page Manager Existing Pages from being able to intercept the page.

function MYMODULE_menu() {
    $items['profile-example'] = array(
        'page callback' => '_profile2_form',
        'page arguments' => array(),
        'access callback' => TRUE,
        'type' => MENU_CALLBACK,
    );
    return $items;
}

function _profile2_form() {
    global $user;
    module_load_include('inc', 'profile2_page', 'profile2_page');
    $profile2 = profile2_by_uid_load($user->uid, 'profile2_profile_system_name_goes_here');
    $entity_form = entity_ui_get_form('profile2', $profile2, 'edit');
    return $entity_form;
}

This can now be intercepted by Page Manager Existing Pages and properly displayed by the Panels module.


How to Restrict Content OVerview to certain content types for user roles I have a user role called Athletics and I have given these users access to add, edit or delete the content type Athletes. However when the content type is created it just creates a node not a URL alias so the Athletics users can not navigate to a page to edit or delete. I tried giving access to the content overview but I think that would confuse my non-technical users. Is there a way to make it so they can ONLY see the content they can edit or delete within the content overview?

Administration Views will replace the admin listing pages with views, and then you can tweak it.

But looking at your question in the greater context what you really need is Contextual Admnistration. With it you can create a admin UI for your athletics role to manage content. There is a video tutorial series on Youtube.


Can Views output only the first vocabulary term? Is there an easy way in Views to output the first vocabulary term only?

Edit the term reference field in your view, and under "Multiple Field Settings" check "Display all values in the same row". You will be presented with further options. You will probably want Display options to be Simple Separator, then change "Display [all] value(s)" to "Display [1] value(s)", apply and save your view.


Pass custom variable to block.html.twig I have a customer who requires the correct set of responsive classes for his block in a given theme depending on its position and count. In my theme_preprocess_page(&$vars) I can identify the blocks in this region and build up an array for each block using its plugin_id and save it to $variables['highlighted'].

In my page.html.twig I use {{ highlighted }} and the array shows up wonderfully. Because block.html.twig by default is set up to be looking for {{ plugin_id }} I expected that I can test if plugin_id is in_array() and add these classes to that instance of the block.

But {{ highlighted }} in block.html.twig returns null in this theme, suggesting that $variables['page'] works for the page, but not block?
Twig has a way to pass off variables to an arbitrary twig file but I do not know how to do this in Drupal. For instance, my page.html.twig is using {{ highlighted }} to pull in these blocks from $variables.

So my question is how does Drupal 8's adaptation the Twig source determine which variables are passed (plugin_id, content, attributes, id, etc) and how I can add mine? I've looked through the twig.engine and searched the Twig source, but it's not clear to me which class controls what variables are passed to blocks?
My other avenue is to find a way to pass this array of classes to theme_preprocess_block but every attempt I made to try this ends up with theme_preprocess_block returning NULL for this array, suggesting that preprocess_page() and preprocess_block() are working separtely.

You will need to preprocess the block instead of the page. Preprocessing pages will not pass a variable to the block. See hook_preprocess_block. If you are needing to determine values based on how many times a block is rendered you can look into using drupal_static to store variables that can be reused during the rendering process.

Drupal static example:

$first_row = &drupal_static('first_row');

if ($first_row == 2) {
  // I equal 2
}

// Since I am passed by reference I can alter and will keep my value.
$first_row++;


Disabling auto-translation from English to another language? I've installed Drupal 8 and setted the site to be in Hebrew. It was changed to Hebrew, but from some reason, all the management system area\navigation\menues themselves were also translated to Hebrew. Such a thing never happened to me In Drupal 7.

In Drupal 7 when I was installing sites and setting the language to Hebrew, I would only have everything moving to the right (Hebrew is an RTL language) and the usage in the language became available, but I never, ever, had all the site translated automatically.

Is there a way to allow Hebrew without translating every part of the site to Hebrew?

You can configure the administration language seperate to the content language by setting:

/admin/config/regional/language/detection:
Account administration pages: enabled

If you want to force this, set this setting at the top of the list.

Then there is in the user configuration of admin's the option to set a different language for the site and the administration pages language.

For other roles, just set the permission "Use the administration pages and help" to allow this setting to appear on the user page.


Programmatically create a block region in Drupal 7 I am stuck with programmatically creating of regions in Drupal 7. I know how to create regions in .info file, but my problem is that I want regions for every node I create, to show a specific block to each and every node differently.

I am interested in Drupal 7 only. If it is possible by creating a module, that is a solution that interests me, too.

Edit your theme .info file to add the following line:

regions[youregionname] = Your Region name

Edit your template file (e.g. "page.tpl.php"), and add the following lines:

<?php if(!empty($page['youregionname'])) : ?> <!--check if region enabled-->
  <div class='my-new-region-class' >   <!--add class to my region-->
    <?php print render($page['youregionname']); ?> <!--print the region-->
  </div>
<?php endif; ?>

After editing the files, don't forget to clear the cache.


Price comparison website I have two sets of taxonomy lists

Engine Codes
Vehicle Make and model

Now I'd like to link the two taxonomy terms from different lists/vocabs e.g.

Nissan Skyline R33 GTR (Vehicle make and model)  - - - > RB26DETT (engine code)
RB26DETT (engine code) --> Nissan Skyline R33 GTR (Vehicle make and model)

I'd like to do this without having to manually input it twice. In some cases the same vehicle may have different engine codes, and visa versa.

So If I look at the Taxonomy term page for Nissan Skyline R33 GTR, it lists the RB26DETT and visa - versa.

I'm not sure (i) which module to use, and (ii) whether I should use term reference, or entity reference.

I'm new to this and learning so appreciate any help/advice!

Thanks
Shah

While I don't have the detailed steps, I suggest you look to the Views module. The relationships and/or contextual filters provide WHERE and FROM type SQL queries.

If you have two views, one based on each vocabulary (taxonomy lists), and each has a contextual filter (with block settings to show only on specific page) then you will get a correlated listing on page/block sets.

If you have troubles getting it going, try exposed filters and AJAX refresh options - Get close enough to help your users help themselves. From a marketing angle, even if automatic/ideal results aren't automatic yet, IF views exposed filters get your customers/staff/partners to answers within 60 seconds from only a click or two, AND they also see message/indication you are actively working on the automatic results, the anticipated "better" site will up their anticipation and your reputation with most people (if, of course, presented with care).

Alternate possible "maybe" modules are "Views Field View" or "EVA". The "Better Exposed Filters" module might also be handy.

Try a search inurl:tutorial-6-10-views-relationships-and-contextual-filter for a great video.

Good luck.


Selecting First Name of Billing Address in Rules with Data Selector? How do I use data selector for Billing Address > First Name in Rules for Commerce?

I want to use the order owner's first name in automatically generated emails.

For example:

  Hey Scott,

  Thanks for your order...

The solution likely depends on the billing customer profile's address field using a split first and last name field instead of the combined "full name" field. I've noticed on my Commerce site that there appears to be a bug in Address Field (hope to fix soon) that prevents a full name field from being split up into first and last name fields or vise versa.

Assuming your customers are entering first and last name separately, then all you have to do is drill down from the order through the profile to the first name on the address field. To do this using a Rules data selector, you'd first need to add two "Entity has field" conditions - one to ensure the commerce-order entity has the commerce_customer_billing field and a second to ensure the commerce-order:commerce-customer-billing entity has the commerce_customer_address field. IF those are in place, using the data selector you can drill down to the following token:

commerce-order:commerce-customer-billing:commerce-customer-address:first-name

The problem comes when you actually want to embed this value in the body of an e-mail. Right now, as far as I can tell, there is no chain of tokens (replacement patterns in Rules UI parlance) that will drill down to the first name using that same pattern. Looking in the code for addressfield.module, I don't see any token related code. This may just need to be opened as a feature request for the Token module.


Storing anonymous user information in a cookie I want to store the zip code of a user, if they use it for a proximity search in a cookie. However, I don't know where or how to start to implement this.

How do I store anonymous user information on a cookie?

Since Drupal 7, there are two functions to store data in a cookie: user_cookie_save(), and user_cookie_delete(). Despite the function names, the functions work also for anonymous users, since they don't get information from the $user object or any information that is related to the user ID.

comment_form_submit() uses user_cookie_save() in the following code lines:

if (user_is_anonymous()) {
  user_cookie_save(array_intersect_key($form_state['values'], array_flip(array('name', 'mail', 'homepage'))));
}

If you are using a version of Drupal that doesn't define that functions, you can implement similar functions in a module you use.

function mymodule_cookie_save(array $values) {
  foreach ($values as $field => $value) {
    // Set cookie for 365 days.
    setrawcookie('Drupal.visitor.' . $field, rawurlencode($value), REQUEST_TIME + 31536000, '/');
  }
}

function mymodule_cookie_delete($cookie_name) {
  setrawcookie('Drupal.visitor.' . $cookie_name, '', REQUEST_TIME - 3600, '/');
}

Keep in mind that setrawcookie() is only available in PHP 5. If you are developing a module that could be used with PHP 4, then you should use setcookie(), and the code of the functions should be accordingly changed: the parameter needs to be declared as $values (not array $values), and the call to rawurlencode() needs to be removed as the cookies are already URL encoded from setcookie().


How can you expose a Quantity update / delete field in the checkout cart? Currently when adding items to cart, I have all users redirected straight to /checkout, but the problem arises is when users want to modify their cart contents.

I tried adding the Quantity Text Field, but no update button shows up. And I tried adding the delete button, but it doesnt delete anything.

It actually isn't possible, at least using the Views Forms functionality that we use to create the shopping cart form at /cart. The issue is that using a Views Forms field in a View turns the entire View into a form - as in, you get a new form element in the DOM that wraps around the entire View HTML. Because the cart contents checkout pane is already part of a form, you end up nesting a form within a form - which just doesn't work.

You have two basic options to work around:

Alter your checkout form to embed custom quantity editing fields in that part of the checkout form. Difficult, not sure it's possible. (In the same vein, you could also figure out how to make Views Forms embeddable inside other forms - even more difficult, but probably more possible.)
Use a custom block on /checkout to show the cart contents with a Views Form that saves updates asynchronously (not the default behavior). The idea there would be you'd have a form with quantity edit fields outside the checkout form that you'd be using to update the cart contents completely separate from whatever happens on the checkout form. I say you'll want to use AJAX to save the updates because you don't want to have someone submitting a cart update form after putting data into the checkout form elements below and losing data.

These two options work with the existing Views powered cart contents pane. If I had this scenario and owned the feature, I'd probably just create a custom checkout pane and eschew the Views powered form entirely.


Blocks page and Themekey module I am referring to this page.

I need to use the administration theme on this page, but this is blocked by default.

At the moment I have to go to the theme page, change to my admin theme, and then change back when I have made the changes I need.

Is there anyway I can set this up using the Themekey module? It is beginning to be a major problem for my client.

No, there is no way you can change theme on this location using themekey.

You might consider to do this in your custom module. Something like this:

function YOUR_MODULE_NAME_init()
{
  global $custom_theme;
  if($_GET['q'] == 'admin/build/blocks'){
    $custom_theme = 'your_theme_name';
  }
}


Grouping of vocabularies I have several vocabularies some of which are related to the same concept. Ex:
- Car
- Bicycle
- Boat
- Tags
- Countries

In the above example, Car, Bicycle & Wheel could all relate to "Vehicles".
I would like to group these vocabularies in order to pull out all vocabularies related to Vehicles...

Is there any way I can add this relation ?

Assuming D7, you can add a field to the vocabulary entity to group the vocabularies together.

For example, you could add another vocabulary "Group" that contains your vocabulary group terms. You could then add it either as a select or free-tagging style term reference field on your other vocabularies and link them that way.

Admin > Structure > Taxonomy > Edit Vocabulary > Manage Fields

You may also want to consider using a single hierarchical vocabulary where the terms are nested under a parent term, e.g 'Vehicle' (recommended)


Why can't I uncheck "Create new revision" on the content type edit page? On Drupal 8, I created a new content type, MyContentType, and accepted all the defaults.

I noticed that Create new revision under Publishing options was checked but slightly grayed out and I could not adjust the value, even though I was logged in as user 1:

I don't know why I can't uncheck it, but this is fine because I always want to save a new revision every time the node is saved.

However, to test this, I then created a new node of MyContentType and saved it.  Then I edited the saved node-- and the Create new revision checkbox is unchecked!

So Create new revision is permanently enabled on the content type edit page, but on the actual edit pages for that content type, the revision box is not checked by default.

What is causing this bizarre behavior?

In Drupal 8.2, create new revision became checked by default, but it says nothing about making it "mandatory by default".

The problem was the Content Moderation module (Drupal 8.4).  I guess I have to take the experimental warning seriously.

When Content Moderation module is enabled, you can't change the "create new revision" status for any content type.

However, content types not subject to content moderation will not have the "Create new revision" box checked on the node edit page if the box was not checked before Content Moderation was enabled-- or if the content type was created while Content Moderation was enabled.

This can be confirmed by checking the config for the content type that has been exported by drush, which shows new_revision: false.  This is most likely a bug so I'm off to file an issue.


Drush, Views and Page Manager I've got several custom modules I have written and they make liberal use of Views, Panels and the CTools page manager.  I've exported the views, panels and page variants into the module code, and am wondering if there is any way I can use drush to revert my production site to the new views/panels/variants after I do the rsync, rather than logging in and commencing the click, wait, click routine.

There is drush views-revert, which alone will give you a list of views to revert, or can also take multiple views names as arguments, as in drush vr archive frontpage.

So far, nothing like that exists for Panels.

However, if you were to use the Features module to export the Views and Panels, instead of a custom module, you could use the drush commands that Features provides.


How can I load a javascript file into a Drupal 7 page using the Code per Node module? What is the syntax for including Javascript from a remote location into a Drupal 7 page using the Code per node module?

I have seen this code drupal_add_js('path/to/somescript.js') at Managing JavaScript in Drupal 7 | Drupal.org, but it seems that is not for use on Drupal 7.

What would be the Drupal 7 equivalent?

Code per node module is  intented to use to have a custom JS for each node. The JS code must be placed inline, in the node add / edit form. You have this tutorial to see how it works.

If you want to add the same js to a specific content type you can create a module custom where you invoke preprocess node hook:

function YOUR_MODULE_preprocess_node(&$variables) {
  if ($variables['type'] == 'INSERT_CONTENT_TYPE') {
       drupal_add_js('path/to/somescript.js');
  }
}

You can also do this in a custom theme, there are examples in this answer.

If you want see a module with drupal_add_js examples and a nice documenttion, you can see the module js_example , which is a module inside Examples 7.x.


make view modes for commerce enabled by default when exporting with features I am trying to make the Drupal Commerce view modes administrator and checkout_pane enabled by default when I export with features.

I have strongarm dependency required; but I do not see the view mode options available.

Does anyone have some ideas? I would greatly appreciate the help.

That info is stored in the field_bundle_settings_node__contenttypenamehere variable.  So make sure you export that for each of your content types.


How to install drush on a shared hosting without SSH and without composer? I would like to install Drush on my shared hosting account in order to let a cronjob call a specific module to this installation.

I have NO SSH access and NO Composer access on this shared hosting account and will not get it neither. I can setup a crontab job and run a call.

I looked extensivly to install drush but cannot find it.

Please do not answer that I should use SSH or composer. These answers will not be helpfull :-)

Rather than using drush, consider writing a custom script you can call instead.

In Drupal 7 you can bootstrap Drupal from the command line like this:

<?php
chdir('/var/www/YOUR SITE ROOT');

// no time limit!
set_time_limit(0);

// set some server variables so Drupal doesn't freak out
$_SERVER['SCRIPT_NAME'] = '/importer.php';
$_SERVER['SCRIPT_FILENAME'] = '/importer.php';
$_SERVER['HTTP_HOST'] = 'somewhere.com';
$_SERVER['REMOTE_ADDR'] = '127.0.0.1';
$_SERVER['REQUEST_METHOD'] = 'POST';

// change to the Drupal directory
define('DRUPAL_ROOT', getcwd());

 // Drupal bootstrap throws some errors when run via command line
 //  so we tone down error reporting temporarily
error_reporting(E_ERROR | E_PARSE);

// run the initial Drupal bootstrap process
require_once('includes/bootstrap.inc');
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

// act as the first user
global $user;
$user = user_load(1);
// add your custom code here

You will need to tweak this to your specific needs. Place it outside your site root for security reasons.


How to disable "Add To Cart" button on select products? I have a Drupal 7 / Ubercart 3 website. How can I disable the "Add to Cart" button on only some products? For instance, if I wanted to list product ABC but did not want to actually sell it online, I'd like for its "add to cart" button to either be hidden or to display a different button that would not be clickable.

The only solution I could find is for D6 (https://drupal.org/project/uc_disable_product).

Thanks!

On What ever products you dont want customers to buy or add to cart, the easiest solution is just hide them using css for that button alone.

.parentclass #add-to-cart
{
  display:none;
}

Or

you can use uc_auction module and let the products be auctioned for particular period of time.there will be no add to cart button.


Is there a way to call a drupal ajax function on a multistep form without causing the form to resubmit? I added a drupal ajax element to my multistep form but when it runs, it reloads the entire form.

The problem is, there is logic which is performed via a case structure for each step.  When the ajax loads, the next step's logic is ran.

For example, the user is on step 2 of a 4 step form.

The user will cause an ajax call to load in a preview image.  Triggering this ajax call loads step 3.

Triggering the same ajax call again will submit the form (step 4) causing very undesirable results.  Is there some sort of secret voo doo code or argument I can use to prevent this?

The ajax call has a callback function that has a few commands including what it needs to render again. In this care i image it starts rendering the whole form again. You will see someting like this in the callback.

$commands[] = ajax_command_replace('#form', drupal_render($form));

And you want something like this

$commands[] = ajax_command_replace('#form .ajax-section', drupal_render($form['ajax section']));


Step-By-Step Content Type in d7? I want to create a tutorial content type, something where people can upload images, title, body, etc into 'steps'; each step would then be linked together.
The users can upload an unlimited number of steps for the entire node. It is very similar to the instructables.com site. How could I achieve that?

By the way, someone did ask a similar question about this using Drupal 6. The suggestions were to use a story book content type, or to use CCK field grouping. I don't understand how to do those things in d7.

The suggestion of using the book structure or field groups would be exactly the same in D7 as it would have been in D6. However, the CCK multigroup module would be a much better fit and would check on it's D7 status (I tried, but it's spread over several issues in the queue)


ImageCache throwing 500 internal server error I'm trying to use imagecache for the first time. (already installed by someone else. currently not serving any images)

So whenever I try to see an image modified by imagecache I have a 500 internal error. In the drupal's watchdog report log there is just an error without much description:

Failed generating an image from imagecache_sample.png using imagecache preset small_analysis.

I have no idea why, but in the apache error logs, I can't find anything...

This happens even when I try to display the imagecache sample:

http://www.radicalislam.org/sites/default/files/imagecache/small_analysis/imagecache_sample.png?1344778168=

I've just ran into this issue and i solved it by enabling the ImageAPI GD2 module and disabling the ImageAPI ImageMagick module.

There's also a number of things to check: presence of the GD library in system and in PHP config, enough PHP memory to parse the images, valid file system configuration and permissions, etc.


How to make an custom content entity can be refered like user in Drupal 8? Follow project examples, I have created a content entity, but how can make it can be attached into another entity as a reference field like user in drupal 8?

Eyal's comment is just the answer, Choose content as the reference type.


How can I a revert an overridden template to its default in a sub theme? If a base theme overrides a certain template, how can I tell a sub theme to revert to the default template instead of using the overridden template?

Of course I could simply copy the default template to the sub theme's templates directory, but that's not an ideal solution because it duplicates code and one would not take advantage of future (security?) updates in the default template.

My ideal solution would be smart enough to undo the template override provided by the base theme, but still allow for other overrides on the module level.

I don't know if there is a perfect solution to do that without any inconvenient. Here are two proposals :

Altering the Theme Registry :
To prevent the base theme from overriding a specific template, an idea would be to alter the theme registry. The theme registry array is keyed by theme hook name, and contains informations returned from hook_theme().
As Clive suggested above, you can achieve this by implementing hook_theme_registry_alter(). Here an example of how to revert theme overrides to preserve the original "node" template :
function example_theme_registry_alter(&$registry) {
  // Default template file path we want to use (relative to the Drupal root directory).
  $default = 'modules/node';

  // In Drupal 6, we can retrieve default template path in 'theme paths' array. The 1st key should
  // contain it, however 3rd party code might already have altered the registry...
  // $default = $registry['node']['theme paths'][0]; -> should be 'modules/node'

  // Reassign the template file path and theme path accordingly.
  $registry['node']['path'] = $default;
  $registry['node']['theme path'] = $default;

  // Reassign the name of the template file if needed (could have been overriden too).
  $registry['node']['template'] = 'node';

  // You may also need to unset some preprocess functions to protect template variables as well.
  unset ($registry['node']['preprocess functions'][11], ... , ... );
}

This hook is executed as the theme cache is rebuilt, you will need to clear it to see the changes.
This solution still "allows for overrides" on the module/theme level. However, since this code will always hook after modules and themes, you will probably need to bypass it every time you expect a change (e.g. brought by a new overriding template), just to be sure that what you see is what you expect, and to know which theme do what in the rendered page. So, if allowing module/subtheme overrides while preventing base theme overrides is required, you may want to try the 2nd solution.

Bypassing specific theme overrides :
This is not the clean way but according to your needs and how specific it is, you may prefer to directly "tweak" your base theme :

Templates : prevent override by renaming the theme template file : in the node example, one would rename node.tpl.php to bypass.node.tpl.php (or whatever).
Preprocessing : comment out preprocess functions in the base theme's template.php, e.g: themename_preprocess_node()
CSS, JS, ... : depending on how well your theme is structured, it can be easy or simply horribly boring to comment out the "overriding" part in these files.

The inconvenient here is that you'll have to redo these 3 steps every time you update or change the base theme, but until such a case happens, this will make it easier for modules and subthemes to manage overrides without messing with the theme registry.


Prepopulate custom fields during checkout with data from user account I have installed Drupal Commerce in an existing site and I am currently trying to figure out how to prepopulate fields during the checkout process. I use the Commerce Extra Adress Popuplate module to fetch the address information from the user account, but how do I do this exact same thing with other custom fields? For instance I have a custom Client number field in the user account that I really would need to prepopulate to the checkout form.

I have read a bunch of other post on this subject (for instance Populating fields from the User entity during a Commerce checkout, but I haven't found a solution that seems to do exactly what I am looing for.

EDITED: to be more specific, I have created a new Customer Profile using the Customer Profile Type UI module. It contains one field so far, the client number field.
How can I fetch the current user's value from the same field in the User account, during checkout?

EDITED AGAIN:
With rules I have tried using this setup:

{ "rules_kopiera_kundnummer_fran_anvandaren" : {
    "LABEL" : "Kopiera kundnummer fr\u00e5n anv\u00e4ndaren",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "entity" ],
    "ON" : { "commerce_order_insert" : [] },
    "DO" : [
      { "data_set" : {
          "data" : [ "commerce-order:owner:field-kundnummer" ],
          "value" : [ "site:current-user:field-kundnummer" ]
        }
      }
    ]   } }

But the current client number is not copied into the field in question.
Any ideas?

If I am not mistaken, you can do this with rules. Use the 'after saving a new commerce order' event and choose to 'set a property' on the commerce order. For the value you can navigate to the customer profile and select your field.

Optionally you can also add the 'after saving an existing commerce order' to update the field at every step in the process. (commerce saves the order after each checkout step).

Update

This requires some knowledge about how Drupal commerce works. An order is created as soon as you place a product in the cart. You now have a product in the cart state. As you proceed to checkout, the order state updates with every step. If you leave the checkout, the state is frozen and you could continue it at every time.

Since your rule only acts on commerce_order_insert this means the number will only be copied if you create a new cart. (proceed to checkout your current order or delete the entire order by going to the order overview.) This is why I proposed to also add the commerce_order_update event as a trigger. That should update the number at every step of the checkout process.

Also there appears to be a misconfiguration in the rule (or I misunderstood your question). If the number is on a customer profile type, you should get it from there. [ "site:current-user:field-kundnummer" ] assumes this is a field configured on the user profile. And [ "commerce-order:owner:field-kundnummer" ] is really the user if of the order owner. (Changing that might mess up everything).

I guess you should be setting [ "commerce-order:<commerce-customer-profile-reference>:field-kundnummer" ] instead. That would be the field on the customer profile.


Add custom link to a page I am not able to find out how can I add a custom link at the bottom of a page (like in the image below - "hlee's blog"). When I click on the 'Edit' tab, there is not html/code for that link. I need to add another link on this page but have no clue where the setting/code is.

Thank you.

I'm assuming that you're using Drupal 7. Many ways to do this, one way is to implement hook_node_view


Sort criteria by year for blog posts I have a View set up for blog post content in Drupal 8. The blog posts were all posted at the same time but have different "year" tags attached to them based on when the post is relevant to the company, and I am trying to sort them starting with most recent year (2019 to 2014. I can't seem to get them to filter in the correct order based on the tags.

These are the steps I have already taken:

Added a relationship with "Taxonomy: Terms on node". Selected the tags vocabulary.

Added a sort criteria for taxonomy term - year (which is in the tags)

Tagged all blog posts with the correct year (ranging from 2014-2019)

But the posts are still in a completely random order. Am I missing a step somewhere?

You don't need a Relationship to add the Tags sort (use the actual Tags field reference, not the generic "Terms on node").

But this way the results will be sorted by TID, not by term names. If your tags have been added chronologically then their TIDs will also be chronological and you can use this sort criteria (it doesn't matter if asc. or desc.).

But if your TIDs for years terms are mixed up you have to sort by term name. This is an alphabetical sort, not a numerical sort, but luckily it will work correctly in your "years" case.

To do that you have to:

Add the Relationship for your tags field, you can require it since you only want nodes that have the years tag to appear
Add Sort criteria Name from the Taxonomy term Category (it will automatically use the Relationship from above)

Now your results will be sorted by text 2015, 2016 etc.


Is there a way to submit a form on an element's #ajax? given a form like this:

function awesome_form() {

 $form['select'] = array(
     '#type' => 'select'
     '#options' => array(
        'hello' => t('Hello'),
        'good-bye' => t('Good Bye'),
     ),
     '#ajax' => array(
        'callback' => 'awesome_ajax',
        'progress' => FALSE,
     ),
 );

 $form['actions'] = array('#type' => 'actions');
 $form['actions']['submit'] = array(
   '#type' => 'submit',
   '#value' => t('Save'),
 );

 return $form;

}

I want the ajax callback on the select box to fire a submission.
So for instance, when someone selects "Hello" the form submits and when someone selects "Good Bye" the form submits.
Right now (with the code above), awesome_ajax() fires like it's supposed to, but I can't seem to get the form to submit (save the data in the database).

Also, I would like it if there wasn't a visible submit button on the page (as the submit button is unnecessary).

How would I do this?

thanks!

You've not mentioned what your ajax callback is doing internal to it, but if all you want is to submit the form upon a change, you can do something like this in jQuery with no drupal involvement:

$('#edit-submit').hide();
$("#edit-field-FIELDNAME-0-value").live('change', function() {
  $('#edit-submit').click();
});

where #edit-submit is the id= in the form html of the submit input button and #edit-field-FIELDNAME-0-value is the id= of your select that you want the form submited upon change.  Throw this and the appropriate drupal behavior wrapper into a js file and you can drupal_add_js() it from your form hook.

ADDITION:

I suppose $('#form-id').submit(); is better than $('#edit-submit').click(); above where #form-id is the id= of your form.

Also, if you are running D6, you'll need the jQuery Update module installed.


Javascript works inline in webform but not as standalone I have a javascript that works if I place it in a mark up in my webform but breaks the form if I make the form a multipage. If I place the script as it's own file and then call it using drupal_add_js(path_to_theme() .'/scripts/SCRIPT_NAME.js'); in my webform-form-NID.tpl.php nothing hapens.

Here is my script in my markup:

$(document).ready(function(){
    var ac_config = {
        source: "/example/sites/all/themes/skeletontheme/js/democities.php",
        select: function(event, ui){
            $("#edit-submitted-info-company").val(ui.item.company);
                        $("#edit-submitted-info-address").val(ui.item.address);
                        $("#edit-submitted-info-address2").val(ui.item.address2);
                        $("#edit-submitted-info-city").val(ui.item.city);
            $("#edit-submitted-info-state").val(ui.item.state);
            $("#edit-submitted-info-zip").val(ui.item.zip);
        },
        minLength:1
    };
    $("#edit-submitted-info-company").autocomplete(ac_config);
});

In the stand alone .js file:

(function($){
    var ac_config = {
        source: "/example/sites/all/themes/skeletontheme/js/democities.php",
        select: function(event, ui){
            $("#edit-submitted-info-company").val(ui.item.company);
                        $("#edit-submitted-info-address").val(ui.item.address);
                        $("#edit-submitted-info-address2").val(ui.item.address2);
                        $("#edit-submitted-info-city").val(ui.item.city);
            $("#edit-submitted-info-state").val(ui.item.state);
            $("#edit-submitted-info-zip").val(ui.item.zip);
        },
        minLength:1
    };
    $("#edit-submitted-info-company").autocomplete(ac_config);
});

First question is why does the script not work if I add page breaks to my webform.

Second question - why won't the script work the way I have it formatted as it's own .js file.

Thanks for any assistance.

I think you can use default druypal behaviors

  Drupal.behaviors.mywebform = {
      attach: function (context, settings) {
    var ac_config = {
            source: "/example/sites/all/themes/skeletontheme/js/democities.php",
            select: function(event, ui){
                $("#edit-submitted-info-company").val(ui.item.company);
                            $("#edit-submitted-info-address").val(ui.item.address);
                            $("#edit-submitted-info-address2").val(ui.item.address2);
                            $("#edit-submitted-info-city").val(ui.item.city);
                $("#edit-submitted-info-state").val(ui.item.state);
                $("#edit-submitted-info-zip").val(ui.item.zip);
            },
            minLength:1
        };
        $("#edit-submitted-info-company").autocomplete(ac_config);
        }
    }

Hope it will help!


Empty field value showing in webform email content I have a file attach field in my webform. When i have submit my webform without this field,in my email content showing like "ATTACHED FILE: [webform_submission:values:attach_file]".
I have checked "Exclude empty elements" in my email handler.This is working for all other fields in my form except this "File attach" field.How can i solve this issue?

Similar question was recently answered by the Webform module developer at drupal.org:

"You might just need to append the :clear prefix.

[webform_submission:values:element_value] => [webform_submission:values:element_value:clear]"

https://www.drupal.org/project/webform/issues/2982562

So, in your case use replacement pattern: [webform_submission:values:attach_file:clear]


Is there a "hook_user_login_failed" hook? Or something similar? I'm needing to detect when a login failure happens in Drupal and am finding it to be exceedingly difficult even after searching Google.  I have to believe this exists somewhere.

I found this post back from 2007 which seems like an entirely reasonable request for a "failed login" hook: https://www.drupal.org/node/160469 Is there something that allows this?

Thanks in advance.

AG3

At least in Drupal 7, there is no hook for that.  The login form uses validators, one which authenticates, and another that follows and sets a form error if login failed.

One option would be to add a custom validator to the form using hook_form_FORM_ID_alter, and check the status of login there.  See user_login_final_validate in user.module for an example of how status is checked.


Trivial Example of a Module that Creates a Content Type I want to write a module that creates a content type with a title and one or more textfields. I'm having a very hard time simplifying the roles of each hook function call in the documentation of the node_examples module.

Right now I'm trying to figure out what the next function should be and what it will do with the form data. So far I've gotten the content type and the forms to show up in the add content section of my site but when I save the "votable" content none of the form data is stored, just a blank piece of content with content type "votable". Could someone point me towards the next step?

function votable_form($node, &$form_state) {
    $type = node_type_get_type($node);
    $form = array();
    $form['votable_title'] = array(
        '#type' => 'textfield',
        '#title' => check_plain($type->title_label),
        '#default_value' => !empty($node->title) ? $node->title : '',
        '#required' => TRUE,
        '#weight' => -5,
    );

    $form['votable_results'] = array(
        '#type' => 'textarea',
        '#title' => t('Results'),
    );

    return $form;
}

 function votable_node_info() {
    return array(
        'votable' => array(
            'name' => t('Contestant'),
            'base' => 'votable',
            'module' => 'votable',
            'description' => t("Select this content type to create a Contestent Page"),
            'help' => 'add content',
            'title_label' => t('Contestant Name'),
            'has_body' => FALSE,
        ),
    );
 }

Flex Slider creates a content type for a slider image and a view to make the slider itself, so you could look at that for an example module.


Fancy insert stopped working Does anyone have an issue with the fancy insert module, not actually inserting the image on click recently?

It looks like the javascript in the fancy insert was hooking into the insert button by traversing up from each image thumbnail.

// Click on Insert button when an image is clicked
      $('#' + value + ' img').bind('click', function (e) {
        $(this).parent().next().find(".insert-button").trigger("click");
      });

I can't see any obvious reason why this would have stopped functioning with updates.

So my question is, has anyone else run into this issue with the latest Drupal core updates? At first I thought it was a lack of unique id on each imagefield, but after reviewing the code again I don't think that is the case.

At any rate am looking for anyone who may have run into this and found a fix.

The issue is caused by the insert module. The latest version (1.4) switched from using click to mousedown events, in this issue https://www.drupal.org/node/2295507

The patch submitted here (https://www.drupal.org/project/fancy_insert/issues/2955599#comment-12571625) should solve your issue, it basically switches from triggering click to triggering mousedown events as a way to connect to the insert module's functionality.

Here is the code change for reference:

diff --git a/fancy_insert.js b/fancy_insert.js
index 8325c96..0b99824 100644
--- a/fancy_insert.js
+++ b/fancy_insert.js
@@ -21,7 +21,7 @@ Drupal.behaviors.fancy_insert = {
-            $(this).parent().next().find(".insert-button").trigger("click");
+            $(this).parent().next().find(".insert-button").trigger("mousedown");

Good luck!


How to create mutliple order statuses in Ubercart? Is it possible to create multiple order statuses?

I.e. order can be "In checkout" and "Paid" (I have a list with few parameters which may be set to true or false).

My software: Drupal 7.24, Ubercart 3.6

First off, just a friendly reminder to get yourself on the latest release of Drupal 7 core ASAP, as there was a major vulnerability discovered in all versions of Drupal 7 prior to 7.32.

As for your direct question, I don't believe you can set multiple order statuses for the same order at the same time. What you can do, however, is setup a couple of other fields on orders to handle your additional statuses and then automatically set those statuses using Ubercart's Checkout Rules. For the example you stated, though, I'm not sure if it makes sense that an order would be "In checkout", which means that the user hasn't completed the checkout process, and "Paid", which usually happens as part of completing the checkout process.

Regardless, you can add a custom field for an Order at "/admin/store/settings/orders/fields". Then, you can add a new Checkout Rule at "/admin/store/settings/checkout/rules" and set the value of the new field automatically triggered by one of the Rules events Ubercart lists when creating the rule.

If you provide more detail on what the fields are and how you're planning on using/reporting on them, I may be able to help further.


How do i get the node id using menu_hook Hi I try to get the node id when user edit the node by the code below:

       function test_plugin_menu(){
            $item = array();
            $item['node/%/edit'] = array(
                'page callback' => 'test_plugin',
                'page arguments' => array(1),
                'access callback' => TRUE,
                'type' =>  MENU_LOCAL_TASK,
            );
            return $item;
        }

        function test_plugin($node_id){
              dpm($node_id);
         }

I get into a blank page when i edit a node. Please help, thank you !

Although you pass a node id into the url, it get's converted to a fully loaded node by the time your callback function is called. You could read up on it on the documentation page for hook_menu, under section Auto-Loader Wildcards.

In node.module you will see this menu item for node edit:

$items['node/%node/edit']

Now, the path you are trying to register already exists in the node module, so that is where the WSOD comes from. You need to do a hook_menu_alter on it, or perhaps hook_form_alter if all you want to do is alter the node edit form.


Navigation block title no longer defaulting to user name in d7 The default behavior for the Navigation block in d6 was to replace the word Navigation with the user name.  It appears that this logic was removed from the core user module in d7.  My client stills wants the user name to display.  Is there a way to duplicate this same behavior in d7 ??

What complicates things a bit is that we are using a mini panel that includes that block but I haven't figured out a way to override the title with the user name.  I've tried using the user:name token as the Navigation block title and then overriding the title with %title but it displays the literal value 'user:name' instead of the actual user name.

Have you set "user" in the contexts? It sounds like you do not have access to the %user:name token, and that's why it sets the actual text instead of the username.


How to call the implemented hook_profile2_access() function? I'm rather inexperienced in module development, sometimes I have really basic issues: I'd like to grant custom access to user profiles. I think I can do it with the implementation of hook_profile2_access() (profile2 and profile2_og_access submodule use such implementations)

I added the mymodule_profile2_access() to my module but I don't know how/when it would be called?

Well, it was a typical user error: The implemented mymodule_profile2_access() function is called only for non-admin users and I checked it with administrator. So simple...


Download all files from webform I need to download a zip with all attached files from a webform.

Is it possible?

Webform stores all these files in sites/default/files/webform you can download them with FTP.


Save me from changing the look of CKEditor using Javascript I see that code is being rendered to produce this CKEditor (via the CKEditor module) contains an inline style that creates a height of 200 pixels. I'd like to change this value to 100px to save a bit of screen space.

I would like to change this or override this is a maintainable way. In the hopes it was in a tpl.php I tried find . -name '*.php' -exec grep -lin 'presentation' {} \; with little luck.

Can anyone point me to where can override this value? Or better put, how can I do better than this:

jQuery(function() {
        console.log('Resizing ckeditor')
        jQuery('#cke_1_contents').attr('style', 'height: 100px; max-height: 100px;');
  });

You can use a CSS override in your stylesheet to achieve this:

.cke_contents {
  max-height: 100px;
  height: 100px !important;
}

And, of course, if you only want to change one instance of the editor, just use an ID selector instead.


Dynamically hiding / showing Field API fields in Drupal 7 I've created an entity with an 'add new' form. The entity itself has a limited number of actual variables. I've added most of the extra data I need using custom Fields (i.e. the Field API).

What I need to do at this stage is be able to dynamically hide one field based on the value of another. i.e. if a drop-down field has it's value set to No, another field should be hidden, otherwise it should be shown.

From what I can see, it is somewhat easy to add this functionality to fields created using the Form API (i.e. via the AJAX property), however is there any way to achieve it using attached fields? I have no issues using custom Javascript if that is what is required to solve this.

In Drupal 7 you can use $form #states instead of custom jQuery script. Example:

  $form['student_type'] = array(
    '#type' => 'radios',
    '#options' => array(
      'high_school'   => t('High School'),
      'undergraduate' => t('Undergraduate'),
      'graduate'      => t('Graduate'),
    ),
    '#title' => t('What type of student are you?')
  );

  // High school information.
  $form['high_school']['tests_taken'] = array(
    '#type' => 'checkboxes',
    '#options' => drupal_map_assoc(array(t('SAT'), t('ACT'))),
    '#title' => t('What standardized tests did you take?'),
    // This #states rule says that this checkboxes array will be visible only
    // when $form['student_type'] is set to t('High School').
    // It uses the jQuery selector :input[name=student_type] to choose the
    // element which triggers the behavior, and then defines the "High School"
    // value as the one that triggers visibility.
    '#states' => array(
      'visible' => array(   // action to take.
        ':input[name="student_type"]' => array('value' => 'high_school'),
      ),
    ),
  );

Here is example if you want to use #states for multiple values condition:

 $form['student_type'] = array(
    '#type' => 'checkboxes',
    '#options' => array(
      'high_school'   => t('High School'),
      'undergraduate' => t('Undergraduate'),
      'graduate'      => t('Graduate'),
    ),
    '#title' => t('What type of student are you?')
  );

  // High school information.
  $form['high_school']['tests_taken'] = array(
    '#type' => 'textfield',
    '#title' => t('What standardized tests did you take?'),
    '#states' => array(
      'visible' => array(   // action to take.
        ':input[name="student_type[high_school]"]' => array('checked' => TRUE),
        ':input[name="student_type[undergraduate]"]' => array('checked' => TRUE),
        ':input[name="student_type[graduate]"]' => array('checked' => FALSE),
      ),
    ),
  );

See the form_example/form_example_states.inc from examples module for more details and examples.


How to format QueryPath Xpath Mappings in Feeds Module I have an XML document with the following structure:

<?xml version="1.0" encoding="utf-8"?>
  <ooh>
    <occupation>
      <title type="text">Accountants and Auditors</title>
    </occupation>
    <occupation>
      <title type="text">Another Title</title>
    </occupation>
  </ooh>

What do I enter in the QueryPath XML Parser to set the context to be Occupation and add the title as a new source? I tried //ooh//occupation but I keep getting this error: CSS selector is not well formed.

The context should be the outer most wrapper of each item, so if your XML is

<ooh>
  <occupation>
   <title>Some Title</title
  </occupation>
</ooh>
<ooh>
  <occupation>
   <title>Another Title</title
  </occupation>
</ooh>

The context would be //ooh and the children of 'ooh' would be entered as occupation and occupation/title.

If occupation is the outermost wrapper of each item like:

<ooh>
  <occupation>
   <title>Some Title</title
  </occupation>
  <occupation>
   <title>Another Title</title
  </occupation>
</ooh>

The context would be //occupation and the title would be entered as title


Adding metadata to nodes for SOLR search We have a website using SOLR search and we've run across an issue. For example, we have a page called "Organizational Chart" but if someone searches for "org chart" it will not appear in search results.

Is there a way to add aliases or metadata to nodes so that we can add "might be searched by" data or extra information that may enhance search visibility?

Would simply adding a cck field accomplish something like this? Taxonomy doesn't really apply because these are not categories and would be different across each node.

Apache Solr supports synonyms, and you can add them to the solr/conf/synonyms.txt file.  The path is relative to where you copied the "example" directory to.  This way people searching for "org chart" would find documents containing "Organization Chart" and any other synonyms you wish to add without any modifications to Drupal.


How to access single field in views-view-fields.html.twig If I enumerate all fields using loop then everything is printed properly:

{% for field in fields -%}
    {{ field.content }}
{%- endfor %}

But I need to print here the fields individually and the following prints nothing:

{{ fields[0].content }}

What's wrong? This is used in views-view-fields.html.twig

You can retrieve it with:

{{ fields.machine_name_of_field.content }}

So for example if your field is a title with:

{{ fields.title.content }}

Install devel to list key / values inside the array of fields with:

{{ dsm(fields) }}


Label for Child in Simple Hierarchical Select by using a module While using Simple Hierarchical Select Module, I have 2 levels of Hierarchy for my Phone. Is it possible to label for child by using a module ?

I guess this is possible by Client side hierarchical select.

Let me know if there is any other option.

Thanks.


What is the correct ways to add themes to a profile within an Aegir install I have Aegir installed with a two platforms. I'm interested in adding some additional themes/modules to the platform. Normally I might do this through Drush, but when I log into the server, I am logged in as Root not as Aegir (I don't believe you can log in a Aegir).

What is the best approach to adding themes and or modules? Should I simply upload via FTP and then make sure that I change ownership of the files?

I figured out a work around, actually it is quite simple. First ssh in as root. Then switch users su - aegir. Now drush will work. then simply use the drush command with the @sitename, so for instance drush @sitename.com dl themename. now this downloads to sites/all/modules, if you want you can move it to sites/sitname/modules. Either way it's a pretty fast workflow.


How to render the textfield from custom advanced theme setting? I'm working on a custom theme with message field(textfield) in custom advanced theme setting.

In "theme-settings.php", I added a "textfield" for "message" field

<?php
function MYTHEME_form_system_theme_settings_alter(&$form, $form_state) {
    $form['message_value'] = array(
        '#type'     => 'textfield',
        '#size' => 12,
        '#maxlength' => 100,
        '#default_value' => theme_get_setting('message_value'),
        '#description' => t('Some text here'),
    );
}
?>

In "template.php", I added "theme_get_setting"

<?php
  function MYTHEME_preprocess_page(&$vars) {
    $message = theme_get_setting('message_value');
  }

And in my "page.tpl.php", I render the "message" if it is not empty

<?php if(!empty($message)) echo $message; ?>

The problem is, it does not render anything and has no error.

It works if I put the theme_get_setting in page.tpl.php

<?php $message = theme_get_setting('message_value'); ?>

How to make it work if I want to put that in "template.php"?

In your template.php preprocess function, you need to pass the message back as a key/value in the variables array. (I set the variable key as "custom_msg" as "message" may be too generic and be accidentally confused with any system message variables"

function MYTHEME_preprocess_page(&$vars) {
    $message = theme_get_setting('message_value');
    $vars['custom_msg'] = $message;
}

Then, in your page.tpl.php, the variable would be accessible as $custom_msg (or whatever custom key you set in the preprocess function) and can be included in your page template as:

<?php if(!empty($custom_msg)) echo $custom_msg; ?>

More information about this can be found on this Drupal.org page: Setting up variables for use in a template (preprocess and process functions)


jplayer in drupal 7 preloads the audio There is a content type called song and it has a file fields. I'm going to add a player on website using jplayer. the problem is, it preloads all of the songs. I mean all of the songs in the page are loaded with the page while I want it to be loaded when the user clicks on the play button. any idea or alternative for jplayer?

try to use MediaElement and library MediaElement.js
simply install and enable it and put the library in sites/all/library/mediaelement .

Creat content type and add song/video field then go to manage display anad select which type of media you want (Song or Video)
That's it , you're done
let me know what's happen ;)


Drupal 7 Comments Alternating Row Colors I'm interested in making the comments that appear on my resource content type nodes show with alternating background colors. Anyone know how to make this happen?

I tried something like this with CSS but I'm not seeing how I can make this work as the comments don't seem to have anything regular I can target (as the class is quite a bit different if the comment is made by a logged in user vs. an anonymous user for instance):

.comments-by-anonymous .field-item:nth-child(even) {
    background: #fcfc33;
}

Then I thought, well I could try and do some PHP if/then hackery to my comment.tpl.php template but I'm unfamiliar enough with that template to know if its a) even the correct one to edit, and b) if perhaps there might just be a better way to do it.

Anyone have any good ideas?

Looks like you can use the $zebra class in the comment template.

Add it in the preprocess hook as a class:

/**
 * Implements hook_preprocess_comment
 */
function THEME_preprocess_comment(&$variables) {
  // Zebra classes are added in the default template_preprocess function
  if (!empty($variables['zebra'])) {
    $variables['classes_array'][] = $variables['zebra'];
  }
}

You can then style the 'odd' and 'even' comments with CSS

e.g, something like:

.comment.odd{
  background-color: #efefef;
}
.comment.even{
  background-color: #ffffff;
}


Have to delete cron_last every time for cron.php to work I am having trouble running cron.php. For testing, I am just running it from the browser (my_domain/my_site/cron.php.) Basically, if I go into the database and delete cron_last from the variable, it works fine, for one iteration, but the next time I try to run it, it doesn't work (until I delete the cron_last value again)

I put watchdog statement in cron.php. From that I could see that it runs until it hits drupal_cron_run. That statement doesn't execute correctly.

drupal_cron_run in in common.inc, so I put more watchdog statements in there. It fails to run past module_invoke_all('cron').

module_invoke_all is in module.inc, so I looked in there, but now I'm stuck. Any ideas?

Basically, you can't delete it with your code - it's set up after last cron hook finishes, so no matter what you do inside Drupal, it'll be set. If the last line that gets executed is module_invoke_all('cron') (in Drupal 6) or module_invoke_all('cron_queue_info'); (in Drupal 7 real cron tasks are wrapped in try catch so this is the only really risky point), or if your server logs timeouts, it's probably a faulty module that fails to execute it's hook_cron, or too many modules defining it, so at some point it times out.

I see two ways to deal with it:

Use Elysia Cron and with it's GUI manually run cron tasks you need to test. That way even if single task will fail, other will get executed. they will be executed one at a time, if you set it up correctly, so less risk of a timeout. And you will be able to test which hook, exactly, fails to execute. Then simply uninstall faulty module, or fix it, and you'll be OK.
In MySQL, create a trigger that will delete cron_last value for you. PostgreSQL supports triggers too, and most of RDBMS support them or something similar to them. It will not solve your problem, but it's way faster than point 1. and it will get you going if all you need is quick and dirty hack.


restrict to subdirectory not work and media module load all images in public:// I use a media module to select file from library, in field option on my field I specify a custom sub directory(it's name is gift_cards) that  I have been created in public path.    but when the media file selector popup triggered I see all images instead images that on gift_cards.
where is the problem, and how can I restrict my custom field to load only image that are in gift_cards directory?

one suggest is using filedeop module , but I don`t want use this module (this is big module with more feature but my needs is something tiny) , restrict to show only custom sub directory in public://

Option 1
Media Browser Plus module states that it will allow

Personal and public “folders”

Which might answer to your needs
Option 2
Views Media Browser should allow you to specify a view to use as the media browser - you could then filter the view based on file path or other file attribute to get the result you are after.
Option 3
If you are using v2 of Media module you can apparently define a View with a 'views media browser' display to create your media module listing. Media module 2.x is currently in alpha, so take care if you wanted to go down this route, and obviously do not test on live site.
see https://drupal.org/node/1547884


Installing drush for use with Drupal 8 I have now found two instances where it seems I will finally need to learn how to install and use drush for my new drupal 8 site. I've been avoiding drush the last 5 years working with drupal 7 because I couldn't find a clear tutorial on how to download, install and run (or even how or where to dl, install and run) drush.

For the record - the two use cases I seem to need drush for are:

running a migration command to import the csv I've already prepared with content I exported from a wordpress site. I'm trying to use the migrate Migrate Source CSV and the example listed on github.
running the command entity-updates per the mismatched entity question I posted.

So, I've now plunged back into trying to suss drush out, and I have some questions with my understanding thus far. My knowledge has been limited to logging into my host server to use cpanel (file manager, backups) and using the filezilla ftp client.

According to [this tutorial by digitalocean][4] I need to install LAMP stack and pear. This is the first point of confusion.

Is this still the correct method for drupal 8?
How do I install LAMP on my server - I'm using a Bluehost dedicated server, so it should already have Linux Apache MySQL PHP, correct? Or is this an application of some kind for those components I'm already using on my server to run my sites?
How do I install pear? From the command line I can access through my cpanel?

Then, trying to follow this Toronto Website Developer by Peter Yaworski tutorial it seems I also need composer?

Do I need to install the composer module?
Or do I install the [full composer here][7] - and do I install it to my server via cpanel command line as well?

That's about as far as my spaghetti understanding goes as to how what is needed to actually get drush up and running as a command line I can use. Oh, and finally, when I see videos or examples of people using drush, I assume they're running it from their server unless they have a local drupal install, correct?

Thanks in advance for any clarification - can't help but feel I'm in over my head here.

Drush is an incredibly helpful tool, you are going to enjoy it. There are a lot of other benifits you'll get from installing it as well.

I'm going to assume you are on a Mac.(There are other ways to do this on a Windows machine, but you'll have to look for them.)

Drush installation is independent of your Drupal version. The only variable is which version of Drush you install. This shows that you'll want version 8.x for Drupal 8.
Yes, your Bluehost server already has Linux, Apache, PHP & MySql. The LAMP stack that is referred to in the digital ocean tutorial is one that you install on your home computer. This will allow you to work locally much faster than making changes locally, uploading them to your Bluehost server and seeing if they worked. I'd recommend using homebrew to set it up. Here's a great article to help you out.
Here's some info on installing pear on your Bluehost server.

As for the other questions...

No, you don't need the composer module. (I haven't used it & I've been using drush for years. I'm not dissing the module, I just know it isn't needed.)
Try this go to see how to install composer. This will tell you how to install Composer on both your

You haven't specifically asked about this but I hope you take the time to install LAMP on your home computer. It'll be a hassle but end up in a huge leap in your productivity. BTW You can also use homebrew to install drush. Here's a Drupal article that explains how.

Good luck!


LDAP Module - Notice: Trying to get property of non-object in ldap_authentication_init() appears I have a site with Drupal 7.41 and LDAP module version 7.x-2.0-beta8. My goal is to connect my drupal site with an Active Directory account.
After I installed LDAP module i saw a error message: Notice: Trying to get property of non-object in ldap_authentication_init() (line 223 of  [... ] ldap/ldap_authentication/ldap_authentication.module)
But i thought that was a part of Module. When i configure and test my module, this error message still appears. The stack of test is:

            sid = empresa.cl
            numeric_sid = 1
            name = empresa.cl
            status = 1
            ldap_type = default
            address = XX.XXX.X.XXX
            port = 389
            tls = 0
            followrefs = 0
            bind_method = 2
            basedn = Array ( [0] => ou=chile,dc=empresa,dc=cl )
            binddn =
            user_dn_expression = empresa//%username
            user_attr = samaccountname
            account_name_attr =
            mail_attr = mail
            mail_template =
            picture_attr =
            unique_persistent_attr =
            unique_persistent_attr_binary = 0
            ldap_to_drupal_user =
            testing_drupal_username = nombre
            testing_drupal_user_dn = CN=nombre, OU=chile, DC=empresa, DC=cl
            grp_unused = 0
            grp_object_cat =
            grp_nested = 0
            grp_user_memb_attr_exists = 0
            grp_user_memb_attr =
            grp_memb_attr =
            grp_memb_attr_match_user_attr =
            grp_derive_from_dn = 0
            grp_derive_from_dn_attr =
            grp_test_grp_dn =
            grp_test_grp_dn_writeable =
            search_pagination = 0
            search_page_size = 1000

Any possible suggestion or advice for this problem?

This message disapears when i add data in a 'Authorization Tab' In a email section and I select a "LDAP Server Type" (This option belongs to LDAP server's configuration from Server tab) such as Active Directory.

Thank, you Anyway


How to add more field columns using Inline Entity Form table display I was wondering if it is possible to have more columns in an Inline Entity Form table to show things like serial numbers and make/model after I input the Node ID. I was reading the answers from this question but I am confused on how to make these work. But in the end I would like the table to look similar to this:

For example, I would like to be able to input the existing Inventory number (node) and when I click "add" it will display the make/model and the serial number (if this is even possible). Which will then be saved as a Sales Order.

Consider using ief_table_view_mode module or hook_inline_entity_form_table_fields_alter()

For more information see answers to a similar question: How to show fields in the Inline Entity Form display widget?


Using an include file from a different module I've got a module that I've created just for the sole purpose of sharing .inc files between multiple modules. The modules .module file is empty, as it doesn't do anything. But in the modules .info file I have included:

files[] = includes\Permissions.inc
files[] = includes\Roles.inc
files[] = includes\PermissionsInterface.inc
files[] = includes\RolesInterface.inc

And then in a module that is using these files (a different module), I have included:

use Portal\Permissions;
use Portal\Roles;

$permissions = new Permissions\Permissions();
$roles = new Roles\Roles();

I don't have any include or require statements, because I thought that was covered by the files[] declaration in the shared modules .info file.

However, I'm getting a PHP error that it can't find the class Permissions(). Just wondering what I'm doing wrong?

The files[] = declarations are only for classes you want to reference at runtime. The declaration should be in the module using the classes (not some other module).

If that doesnt work, look at the xautoload module for D7. Or, simply put include 'includes/Permissions.inc'; into the top your custom module file using those classes/functions -- if you use Features, that's what features (for D7) does; adds an include for features.inc.