Easy way to make an Installation Profile I want to use my current website as an installation profile. I've set it up so it contains some useful content types, views and example content nodes. Is there a no-coding way to create an installation profile that would look exactly as my current site when installed?

AFAIK, there's no one module that does all that perfectly. But depending on what your site is made of, there are a few modules that can come pretty close. Profiler Builder is probably the closest thing to what your looking for.

  It builds the .info, .profile, .install, .make, and .make.example files
  necessary to turn a site into a distribution / installation profile
  and tar's them up as a download.

The Features module can also be very useful as it allows you to package together subsets of functionalities (e.g. modules and settings for an image gallery).


Change jQuery version with hook_form_alter How do I change the jQuery version used for a form with a specific form ID?

What you would like to achieve is loading another version of jQery in your form page. You need to understand the way hook system works. hook_js_alter() is defined as:

  "Perform necessary alterations to the JavaScript before it is
  presented on the page."

You can use the above hook to change jQuery version. hook_form_alter() is defined as:

  Perform alterations before a form is rendered.

So, first action is hook_js_alter() and second action is hook_form_alter(). You cannot change jQuery version with the second hook, but you can use the following code.

function mymodule_js_alter(&$javascript) {
  if ($_GET['q'] == "node/add/page") {
     // Swap out jQuery to use an updated version of the library.
  $javascript['misc/jquery.js']['data'] = drupal_get_path('module', 'jquery_update') . '/jquery.js';
  }
}

For more information on using newer versions of jQuery you can refer the Drupal.org article which explains how to add Newer versions selectively using various methods.


Trigger download after clicking on submit on webform I'm looking for a way on how I could download an uploaded file from the node once the user has click submit on the webform.

Here is a sample of the webform

Confirmation settings doesn't offer a setting that can download a file after trigger. I can attach link to download the file but I would like the file to trigger automatically once user submits the form

May you could inject a little JavaScript into the Webform and redirect the user to the file download.

Or set the webform's confirmation redirect to point to the uploaded file.


How to add inline Javascript code properly with drupal_add_js for a Drupal Commerce checkout pane? I have a custom checkout pane with a basic validation callback. That pane function commerce_checkout_xyz_pane_checkout_form adds some inline Javascript code with drupal_add_js().

The problem, that Javascript only appears on the initial form and is not added when the form is shown again after failed validation.

I thought about moving the drupal_add_js() to a $form['#after_build'] callback but I don't know if that's the right thing to do and how to do it.

Presumably you're using hook_commerce_checkout_pane_info

Try using $form['#attached'] to add your js to the checkout pane form instead. That may work better there.

$form['#attached']['js'] = array(
  drupal_get_path('module', 'my_module') . '/checkout_pane.js',
);


Trying to print translated field label/values to twig I have been trying to figure out how I can print or display the translated values based on the current language of the page.

I have tried using some of the following options {% trans %} and {% endtrans %} does not work

{# {% trans  %}

{{ tab_label.entity.field_tab_title_selection.value }}

{% endtrans %} #}

2nd Option using preprocess, the problem with this method in the event I have multiple language setup I have to create multiple if's statement. Lets say I have 10 languages then I have to create 10 conditions

Using Pre-process

function iom_preprocess_page(&$variables) {

    $language = \Drupal::languageManager()->getCurrentLanguage()->getId();
    $vars['language'] = $language;

}

{# {% if (language.getId() == 'fr')  %}

{{ tab_label.entity.field_tab_title.entity.translation('fr').label }}

{% else %}

{{ tab_label.entity.field_tab_title.entity.label }}

{% endif %} #}

First the {{ trans }} and {{ var|t }} methods only do substitutions from the UI language strings (e.g. specific strings (e.g. "More") that have translations defined (in the UI or code). So, this will not work for 'random' text entered into a field.

That said, it looks like tab_label is an entity reference field.  So, tab_label.entity will always get the default language entity.

I would say do the theme_preprocess_xxx to add the current language to what you are rendering (e.g. if it's a block or a node use those, not just page.  Preprocess variables may or may not trickle down.  I'd only pass on the langcode just to save a bit of memory.  So the preprocess function would look like:

function theme_preprocess_XXX(&$variables) {
    $language = \Drupal::languageManager()->getCurrentLanguage();
    $variables['lang_code'] = $language->getId();
}

Next in the twig file, you can use this code to get the translations:

{% if tab_label.entity.hastranslation(lang_code) %}
  {% set tabLabel = tab_label.entity.translation(lang_code).field_tab_title.entity.label %}
{% else %}
  {% set tabLabel =tab_label.entity.field_tab_title.entity.label %}
{% endif %}

{{ tabLabel }}

Using the set will help keep your HTML easy to validate in the template.


Load all/multiple fields from entity of certain type I'm quite new to Drupal so bear with me here.
I've created an entity using Drupal Console, specifically using drupal generate:entity:content. Which works perfectly. Kudos to the Drupal console guys.
This specific entity will deal with adding some meta tags on specific URLs thru the site.
It has several fields that need to be completed: url, keywords(if any), one open graph tag, and a tag value.
After looking through this question I've decided that using hook_page_attachments is the way to go for me.
The logic for adding the tags is quite simple:

Get the entity.

$entity = \Drupal::entityTypeManager()->getStorage('meta_tag_entity')

Grab the current url.
Loop through the entity url fields and check if any matches the current url.
If it does, simply add the tags.

And that's it.

The problem boils down this.
After I've loaded the entity ($entity = \Drupal::entityTypeManager()->getStorage('meta_tag_entity')) I have no idea how to grab all the url fields.
I've looked over this question but it's not quite what I'm looking for.

You should be able to use either get or getFields on your entity object if it is derived from ContentEntityBase.

See: https://drupal.stackexchange.com/a/232219/57

So, after you load the entity:

$fields = $my_entity->getFields();

Or:

$foo = $my_entity->get('bar')->value;


How to override "Who's online" block theme without any change to "Who's new" theme In user module, "Who's online" and "Who's new" blocks both use the user_list theme function. How can I change the markup of Who's online without any effect on Who's new's block markup?

Since they both use the same theme function it gets more complicated.

The only real choice you have to alter the markup of the one block, but not the other, is to template_preprocess_block or templates for the blocks. The problem is that by this point the markup for the actual block content has already been created, which means that you would either have to recreate the markup, or use some pattern matching to alter the created markup. Both of which is not really desirable.

Another option would be to create the block yourself like the user module does but alter the markup that is created.


Context Module set default block I am looking to have a subfooter that I can toggle with all types of rich content based on the page that visitors are on.  I would like to be able to say the homepage has this block, the blog section has this block, and so on.  I have quite a few uncategorized pages that I would like to be caught in a 'default' block of some form.  The issue is, if I have a default, it will show two if a condition is met with another context.  I would prefer to avoid the use of php snippits in blocks if possible.

You can exclude other contexts. In the default (sitewide?) context, add a Condition: Context, and use the ~ character to exclude the specific contexts that should not be in effect.

E.g., ~rich_subfoot (if rich_subfoot is the name of the context providing the rich subfooter content)


Which template used for adding nodes I want to add some custom checks to all of my Drupal pages (except the administration pages).

I am using Bartik theme that comes with Drupal 7.26

I added the custom check in node.tpl.php and the check worked for all urls of type /node/%

However, I also want to add this check for node add, edit and delete pages.
I cannot do this.

What I have already tried:
-> Creating a node--add.tpl.php in bartik folder and adding check there.
-> Creating a custom module, and using hook_menu to route /node/%/id to a custom page.
-> Adding this function

function bartik_preprocess_page(&$vars, $hook) {
  if ((arg(0) == 'node') && (arg(1) == 'add' && arg(2) == 'product')) {
    $vars['template_files'][] =  'node-add-product';
  }
}

in my bartik template.php file. After adding this function I created node-add-product.tpl.php file and added check there.

For all the methods I have tried, the node creation page does not change at all.

I also tried creating page--node--add.tpl.php. Then the custom check works. But the header, footer, and sidebars disappears. (Only node creation template is rendered)

I think you are using the wrong tpl file to edit the node/add/[content-type] form.

You need to create (if I remember correctly) a [content-type]-node-form.tpl.php and add the required elements you wish from there. See here for more details:

https://drupal.org/node/1092122


Send email on changing line item field value I have a custom list field on the product line item type, which is for the ability to set seperate shipping statuses for each product in one order.

When the store admin updates this list field on a line item, the site will need to send out an email to the customer.

Is there a nice way to make this happen?

There are three approaches I can think of.

 Use a hook to alter the update function to send an email out based on your conditions.
 Add JS to handle the change via a custom AJAX call.
 Create a cron job that monitors changes in the database and emails out messages when changes are picked up.

The first two options are your best and from those, depending on skill level, I would choose one.


How can I get the term ID out of the hierarchical select theming function? I'm attempting to add a link to flag each term output by hierarchical select in a views template.

Here's the relevant code from hs_taxonomy.module:

function theme_hs_taxonomy_formatter_lineage($variables) {
  $output = '';
  $lineage = $variables['lineage'];
  $separator = theme('hierarchical_select_item_separator');
  dpm($variables);

  // Render each item within a lineage.
  $items = array();
  foreach ($lineage as $level => $item ) {
    dpm($lineage);
    $line  = '';
    $line .= drupal_render($item);
    $line .= '';
    dpm($item);
    $items[] = $line;
  }
  $output .= implode($separator, $items);

  return $output;
}

And here's the output of dpm($item):

Based on the flag module documentation, I tried to add the link like this: $line .= flag_create_link('hobbies', $term->$item['#options']['entity']['tid']);

But that gives this error:
Fatal error: Cannot use object of type stdClass as array in /mysite/sites/all/modules/contrib/hierarchical_select/modules/hs_taxonomy.module on line 880

How can I get the tid of the term being output?

The entity is a stdClass object, you need to use the -> accessor:

flag_create_link('hobbies', $term->$item['#options']['entity']->tid);


Regular session table crashes, on a large multi domain, multi site Drupal set-up I have recently been assigned to a project that has regular session table crashes.

Drupal outputs an error like this one:
"Warning: Table './[database]/sessions' is marked as crashed and should be repaired ..."

The problem with this site is that it started as a small drupal site and various companies have added (custom) modules to it. The site has also been ported to a number of different hosting providers with varying results. Currently it is being hosted at OVH on a shared hosting setup.

The site is rather large now with a constant base of 20 users inserting data simultaniously (on different accounts but through the drupal interface), mostly pictures through a multi upload module. At the same time there is a lot of traffic coming from anonymous users (who do not upload anything at this point).

I think the problem might be the shared hosting platform. I think it might not be able to cope with all of the different inserts and just crashes...
Normally I would see if I could cause the crash in some way, but I can't take the site down since it will result in a major financial loss to the company.

I've read some other posts here regarding a large session table where they mentioned the "ini_set('session.gc_maxlifetime',   200000);" line in the settings.php file.
The "answer" was to reduce the amount of sessions to 900-1800 which would result in a smaller session table, but I don't know if this would solve the problem?

To make matters worse my client cannot give me any information on when the crashes occur, if they are perhaps caused by using a custom module, etc.
The site is running on Drupal 6.

I realize there is not a lot of useful information in my post and I apologize for that.
I am a new Drupal developer and I don't know how to address this problem.
(The developer who was handling this issue before I got here quit...)

Any help in this matter would be appreciated.

Thank you.

I would convert the user & session tables to InnoDB. I would also check the memory limits for MySQL. It's not the most ideal tool, but if you're in a shared environment you can install a copy of Drupal Tweaks (http://drupal.org/project/drupal_tweaks) and see if you are able to alter any of the MySQL configuration directive such as memory limit.


How to add a custom views filter handler for a specific field? Currently I have a boolean field field_private_content, if that field is set, the content should only be shown to authenticated users, anonymous users may only see the teaser and a login form. So far it's working well, also with views where I added the filter on that field. The filter get's removed automatically by the implementation of hook_views_pre_view() in a custom module:

function custom_module_views_pre_view(ViewExecutable $view, $display_id, array &$args) {
  // Remove filter on field_private_content != TRUE for authenticated users.
  if ($view->getHandler($view->current_display, 'filter', 'field_private_content') && \Drupal::currentUser()->isAuthenticated()) {
    $view->removeHandler($view->current_display, 'filter', 'field_private_content');
  }
}

Although that works very well, the behavior is not obvious from views ui. I would prefer to have a duplicate of the field_private_content filter which should have the mentioned behavior by default and could be labeled properly - the original filter should keep it's original behavior.

How can that be achieved?

How to add a custom views filter handler for a specific field?

This require a little effort so I will only put here the main parts and a reference to an article that I used to create a custom Views filter in Drupal 8.

First you need to declare the filter inside the hook_views_data_alter() implementation:

$data['node_field_data']['nodes_titles'] = array(
  'title' => t('Node titles'),
  'filter' => array(
    'title' => t('Node titles'),
    'help' => t('Specify a list of titles a node can have.'),
    'field' => 'title',
    'id' => 'd8views_node_titles'
  ),
)

Since we are filtering on the title column, we are extending on the node_field_data table but with the title column as the real field to be used. Additionally, this time we are creating a plugin to handle the filtering identified as d8views_node_titles. Now it follows to create this class:

src/Plugin/views/filter/NodeTitles.php:

    /**
     * @file
     * Definition of Drupal\d8views\Plugin\views\filter\NodeTitles.
     */

    namespace Drupal\d8views\Plugin\views\filter;

    use Drupal\views\Plugin\views\display\DisplayPluginBase;
    use Drupal\views\Plugin\views\filter\InOperator;
    use Drupal\views\ViewExecutable;

    /**
     * Filters by given list of node title options.
     *
     * @ingroup views_filter_handlers
     *
     * @ViewsFilter("d8views_node_titles")
     */
    class NodeTitles extends InOperator {

      /**
       * {@inheritdoc}
       */
      public function init(ViewExecutable $view, DisplayPluginBase $display, array &$options = NULL) {
        parent::init($view, $display, $options);
        $this->valueTitle = t('Allowed node titles');
        $this->definition['options callback'] = array($this, 'generateOptions');
      }

      /**
       * Override the query so that no filtering takes place if the user doesn't
       * select any options.
       */
      public function query() {
        if (!empty($this->value)) {
          parent::query();
        }
      }

      /**
       * Skip validation if no options have been chosen so we can use it as a
       * non-filter.
       */
      public function validate() {
        if (!empty($this->value)) {
          parent::validate();
        }
      }

      /**
       * Helper function that generates the options.
       * @return array
       */
      public function generateOptions() {
        // Array keys are used to compare with the table field values.
        return array(
          'my title' => 'my title',
          'another title' => 'another title',
        );
      }

    }

Inside the plugin, you need to override three methods, as explained in Creating a custom Views filter in Drupal 8. Here is a quote from it:

  Inside init(), we specify the title of the set of filter options and the callback that generates the values for options. This callback has to be a callable and in this case we opted for the generateOptions() method on this class. The latter just returns an array of options to be presented for the users, the keys of which being used in the query alteration. Alternatively, we could have also directly created the options inside the init() method by filling up the $this->valueOptions property with our available titles. Using a callback is cleaner though as you can perform various logic in there responsible for delivering the necessary node titles.

  The point of overriding the query() and validate() methods was to prevent a query and validation from happening in case the user created the filter without selecting any title. This way the filter has no effect on the results rather than returning 0 results. It's a simple preference meant to illustrate how you can override various functionality to tailor your plugins to fit your needs.


Block a single basic page from authenticated users I have a website with a couple of pages and organic group pages. I'm trying to deny access to one "basic page" for authenticated users. (I only want anonymous users to see the page). Every module I've downloaded seems to mess up my permissions and stuff set up for my other pages and views. Is there any simple way to do this?

I've tried content access and node privacy by role.

If you don't mind hard coding the node ID you could do this fairly easily in a custom module using hook_node_access():

function MYMODULE_node_access($node, $op, $account) {
  if ($node->nid == $node_id && $op == 'view' && $account->uid > 0) {
    return NODE_ACCESS_DENY;
  }
  return NODE_ACCESS_IGNORE;
}


Clear form fields after AJAX submit Given:

I am using Drupal 8.
I have a custom "add form" of the custom entity type.
Form has an ajax submission.

Problem:

When I submit form all the values remain in fields.

Expected:

Form fields should be cleared after submission.

Form source code:

<?php

namespace Drupal\mymodule\Form;

use Drupal\Core\Entity\ContentEntityForm;
use Drupal\Core\Form\FormStateInterface;

/**
 * Form controller for the add/edit entity forms.
 */
class MymoduleForm extends ContentEntityForm {

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

    $form['#prefix'] = "
getFormId()}-wrapper\">";
    $form['#suffix'] = '
';

    $form['actions']['submit']['#ajax'] = [
      'wrapper' => $this->getFormId() . '-wrapper',
      'callback' => array($this, 'ajaxRebuildCallback'),
      'effect' => 'fade',
    ];

    return $form;
  }

  /**
   * Callback for ajax form submission.
   *
   * @param array $form
   *   An associative array containing the structure of the form.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The current state of the form.
   *
   * @return array
   *   The rebuilt form.
   */
  public function ajaxRebuildCallback(array $form, FormStateInterface $form_state) {
    drupal_set_message(t('Entity was successfully created'));

    // @todo Clear form values.
    //$form_state->setRebuild(TRUE);
    //$form_state->setValues([]);
    /*$entity = \Drupal::entityTypeManager()->getStorage('liveblog_post')->create([]);
    $form_object = \Drupal::entityTypeManager()
      ->getFormObject('liveblog_post', 'add')
      ->setEntity($entity);*/
    //$new_form_state = new FormState();
    //$form = \Drupal::formBuilder()->rebuildForm($this->getFormId(), $form_state);

    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function save(array $form, FormStateInterface $form_state) {
    $entity = $this->getEntity();
    $entity->save();
  }

}

P.S. you can find my attempts in the ajaxRebuildCallback() method.

@Berdir's answer helped me to figure out the solution. We should indeed clear the user input, but we can not simply just say $form_state->setUserInput([]), because there are some system values, that should stay(e.g. form_id, form_token, _triggering_element_name, etc.).
I have created a custom method for it:
  /**
   * Clears form input.
   *
   * @param array $form
   *   The form.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The form state.
   */
  protected function clearFormInput(array $form, FormStateInterface $form_state) {
    // Replace the form entity with an empty instance.
    $this->entity = $this->entityTypeManager->getStorage('my_entity_type')->create([]);
    // Clear user input.
    $input = $form_state->getUserInput();
    // We should not clear the system items from the user input.
    $clean_keys = $form_state->getCleanValueKeys();
    $clean_keys[] = 'ajax_page_state';
    foreach ($input as $key => $item) {
      if (!in_array($key, $clean_keys) && substr($key, 0, 1) !== '_') {
        unset($input[$key]);
      }
    }
    $form_state->setUserInput($input);
    // Rebuild the form state values.
    $form_state->setRebuild();
    $form_state->setStorage([]);
  }

I am calling $this->clearFormInput($form, $form_state); in the MymoduleForm::save() method(the very last step of the submission).
Update 08.03.2021
If you have a created date field in the entity form, it will be cached in $form_state after submission. You will have to reset it's value for the entities. You can do it by overriding the \Drupal\Core\Entity\EntityForm::processForm:
 /**
   * {@inheritdoc}
   *
   * Resets default values for a new entity.
   */
  public function processForm($element, FormStateInterface $form_state, $form) {
    $element = parent::processForm($element, $form_state, $form);

    if ($this->entity->isNew()) {
      $this->entity->set('created', $this->time->getRequestTime());
    }

    return $element;
  }


Adding multiple taxonomy terms to a node via code I've been editing nodes in code (Drupal 8) like so:

$node = \Drupal\node\Entity\Node::load($nid);
$node->body->value = $body;
$node->title->value = $title;
$node->taxonomy_field->target_id = $value;

If the 'taxonomy_field' entity reference supports multiple terms, how do place them in the $node object? I have tried at least a dozen ways I found on other threads, but none worked. Either errors were thrown, of the code just silently failed.

The object orientated way would be to use appendItem() from FieldItemList:

$node->field_tags->appendItem([target_id => '1']);

But as the field object provides an array interface you can add items to the field the same way as in a php array:

$node->field_tags[] = '2';


Problem with using a taxonomy and taxonomy term referece field to organize my site content I have created a taxonomy called category in order to organize my website with Drupal 7.

I have tier 2s like cómo-aprender-inglés (how to learn English). If I create a basic page and select cómo aprender inglés as the term reference I create the following node http://www.brays.es/es/cómo-aprender-inglés/cómo-aprender-inglés. However, I would like the node to appear as http://www.brays.es/es/cómo-aprender-inglés. Is this possible?

At the moment:

I am hiding the node title so that a user navigating the site cannot access the full node view (cómo-aprender-inglés/cómo-aprender-inglés).
I have prevented that URL from being picked up by search engines by selecting this option in the Metatag module.
I think my solution is a bit messy and I don't think it is the best option. What can I do?

Thanks in advance.

When you want to automatically generate paths for nodes/taxonomies, using a specific 'pattern', the module Pathauto is the way to go.

By using the token of the selected/entered taxonomy term on the node, you can create the requested URL.


Class declaration error when using ResourceBase I tried following this guide: https://www.drupal.org/docs/8/api/restful-web-services-api/custom-rest-resources for the REST API.

However, when enabling the module, I get:

  Fatal error: Cannot declare class Drupal\my_module_rest_api\Plugin\rest\resource\MyModuleResource, because the name is already in use in [PATH]\modules\my_module\src\Plugin\rest\resource\MyModuleResource.php on line 0

It seems like it could be a simple class naming error, but I really tried following the guide to a tee. Here is MyModuleResource.php in full:

<?php

namespace Drupal\my_module_rest_api\Plugin\rest\resource;

use Drupal\rest\Plugin\ResourceBase;
use Drupal\rest\ResourceResponse;

/**
 * Provides a REST API Resource
 *
 * @RestResource(
 *   id = "my_module_resource",
 *   label = @Translation("My Module Resource"),
 *   uri_paths = {
 *     "canonical" = "/my_module_rest_api/my_module_resource"
 *   }
 * )
 */
class MyModuleResource extends ResourceBase {

    /**
     * Responds to entity GET requests.
     *
     * @return \Drupal\rest\ResourceResponse
     */
    public function get() {
        $response = ['message' => 'Hello, this is a rest service'];
        return new ResourceResponse($response);
    }
}

Here is the rest.resource.my_module_resource.yml file:

id: my_module_resource
plugin_id: my_module_resource
granularity: method
configuration:
  GET:
    supported_formats:
      - json
    supported_auth:
      - basic_auth

It looks like the problem was not with the REST API routes, but with the module name vs. namespace: in trying to pay attention to the details of the REST API extension, I missed that my module name was different from the namespace. In the above example, the module name is

  my_module

while the namespace is

  Drupal\my_module_rest_api\Plugin\rest\resource


How can I pass display exposed filter in views-view-unformatted.html.twig? I would like to display an exposed filter inside views-view-unformatted.html.twig rather than views-view.html.twig due to specific UI design?

Try using Views Exposed Filter Blocks.

Use the Twig Tweak module and embed the exposed filter block in your template with code like this: {{ drupal_block('views_exposed_filter_block:my_view_id-my_views_block_id', wrapper=false) }}.
You can also just place the exposed filter block in any region.


Saving user specific customization settings My module prints entries from the database,
I use Pager and ->limit to choose the number of records to show per each page,
instead of hardcoding limit, I'd like user to decide, between e.g. 10,20,50,100 entries per page.

I've got form with select, and the question is - how I can save and pass user defined value to ->limit.

use database - it works, but I'd like to avoid creating extra entry to database concerning such a silly setting like number of records per page
variable_set - if I'll set variable e.g. number_of_rows, change in the limit made by one user will affect rest of the users - not acceptable

maybe there's some solution concerning cookies/sessions?

The best place maybe the drupal user object's data array for tiny amounts of information, like preferences on a per user basis.

$user->data

I'm trying to solve this myself but these links seems useful:

drupal 6
drupal 7
http://www.braahm.be/node/7
http://randyfay.com/node/85


Help with node and field theming I am not particularly new to programming, but trying to theme how Drupal 7 outputs entity fields is giving me headaches. I think Drupal is great, but the documentation could be more organized and complete. I have sifted through a lot of material about this, but I'm still struggling to organize the bits and pieces of information into usable representation of how Drupal 7 treats and outputs field values.

This is an example output that one would like to obtain:

#field value#
                      // Suppose this is the node title

#field value#
       // Sub-title

                              // Attributes:

                        #field title#:

                        #field value#

                        #field title#:

                        #field value#

                        #field title#:

                        #field value#

                        #field title#:

                        #field value#    // e.g. Link to Taxonomy term page

#field title# and #field value#, represent where one would like Drupal to output the field titles and/or values submitted when creating entities/nodes.

The idea sounds straight-forward, but I find it to be immensely complicated in practice.

Some pitfalls I have encountered: Drupal makes presumptions, on how the field should be displayed, it gives it additional markup, which I have been unlucky in managing. When outputting through Panels the UI does not provide ways to separate field value and title. Am I under correct impression that I need separate template files or functions for all fields if I want the above structure?

Please shine some light on the matter. I bet many people would love to hear how more experienced developers approach these problems.

This is probably not a full answer, but you will need to use field template suggestions.

field--[type|name[--content-type]|content-type].tpl.php
base template: field.tpl.php
Theme hook suggestions are made based on these factors, listed from the most specific template to the least. Drupal will use the most specific template it finds:

field--field-name--content-type.tpl.php
field--content-type.tpl.php
field--field-name.tpl.php
field--field-type.tpl.php
Note that underscores in a Field's machine name are replaced by hyphens. Also remember to include "field-" in custom field names, e.g: field--field-phone.tpl.php.

The above is taken from https://drupal.org/node/1089656, so it for more information. As a side note, if there are a lot of fields being displayed or you are using a broad template, you would probably want to use a templating function instead, such an example can be seen in Bartik's bartik_field__taxonomy_term_reference (Link here). The functions have a similar naming scheme to the .tpl.php files but with underscors instead of dashes.

Update:
You can cover all fields of a certain type with field--field-type.tpl.php (or function theme_field__field_type()), or all fields on a content type with field--content-type.tpl.php (or function theme_field__content_type()). You can then override these functions by using a more specific template (They have an order of preference). This can really cut down on the number of theming templates or functions required, essentially if a content type has 100 fields, you could theme them all with one template or function, if you so wished.

So you could use 1 function to theme all the fields on a content type if you wished, no matter their type or name. Alternatively you could field all fields of a certain type (eg. taxonomy_term_reference in the case of Bartik) no matter what their field names are or which content types they are on.

You could override one of these more general templates or functions with one which is more specific, from the field.tpl.php documentation above field--field-type.tpl.php will be overridden by any of the ones listed above it, if a relevant function exists. While field--field-name--content-type.tpl.php has the highest preference and will not be overridden by any of the others. This is just core behaviour, custom modules may alter the list, including adding new ones, which can lead to quite a powerful set of themeing functionality.

Templates are easier for themers to work with, I am told. I prefer functions because it avoids what may be a large number of includes in some cases.


D6/views - Multiple nodes in one slide grouped by taxonomy I have the following taxonomy:

food

fruits

apples
pears
bananas

vegtables

tomatoes
carrot
cucumber

meat

chicken
beef
duck

...and a view that brings all those items, currently as an html list grouped by taxonomy term. I use fields for each item.

I need to change my view in order to split them in slides (or pages with prev/next) so that each slide/page will hold all the items of a food subcategory (the whole group). Ideally with a slider but pagination will also suffice.

To be precise I'd like a similar result as in this question. But in my case I have the above taxonomy tree to help distinct nodes I need in each slide

Thanks in advance!

You might add an argument to your view.

The url of your view should looks like: "my_site/my_views_url/11"
(#11 is the tid of "fruits")

This url will list all terms depth to "fruits" (so apples, pears, bananas)

To add a depth in your argument term in the view follow the views UI :


Adding components to a feature via Drush I understand using 'drush fu' to look for changes to any components of an existing feature, but is there a way to add a component to an existing feature using drush? Right now I have to use the /admin tools to recreate, download the files, upload, etc. Would be nice if there was a way to do this process via drush.

Update: there is a direct way to add components via Drush.

First, to list components drush fc (for features components) will list out all exportable components, including which, if any, feature they are currently exported to.

Next, drush fe foo_feature variable:foo_var views_view:foo_view will update, or create, a module named foo_feature. The output from drush fc can be used to populate the required component:name syntax.

Original answer

While there is no direct command, the quickest way to add components is by editing the .info file.

For example, to add a view foo_view, you would add this line:

features[views][] = "foo_view"

or, to add a variable that hadn't been added, you would add this line:

features[variable][] = "my_variable"

Once these have been added to the .info file, you can then run drush fu, and the additional components will be exported with your feature.

Update:

There is a command. See the below answer about the drush fe command.


A Module which describes other modules I am working on a module which is able to automatically generate a developer document based on the hooks, menus, files and other attributes it holds.

Often when we install a new module, We need to search for the configuration options provided by it. So by automatically generating a document, this issue will be solved.

I started working on this based on clive's suggestion in the post (Get a particular module's information programmatically)
I could retrieve the menu links created by a module as clive suggested in that post.
To retrieve hooks used in a module, I used the PHP function token_get_all() to get all function used in a file and checked whether its a hook.

  Now, I need some suggestions about what can you know by looking through a modules file. What else in a module file can help one
  understand a newly installed module better?

  Is there any API's to get information about a hook from drupal.org?

Now there is a module for that ;) It's the Developer Docs module.
Here's a brief description about it (from its project page):

Developer Docs is a module specially made for drupal developers (amateur). When a new module is installed, it is hard to find what changes it does unless we look into the code. This module provides an overview of "what it does" without looking into the code.
This Module generates a document automatically based on the drupal elements used in the module such as:

Administration menu
Hooks
Database Schemas
Themes
Variables
Blocks
Node types
Entity Types
Fields (Formatter, Widget)
Field Formatters
Field Widgets
Hooks Created

After enabling this module, list of installed modules will be available at admin/reports/developer-docs/


Rendering fields with node display settings I would like to take advantage of the settings I can set under admin/structure/types/manage/node_type/display when i render my custom fields in node--node_type.tpl.php but using the following code I just get some sort of default display setting:

<?php
  print render( field_view_field('node', $node, 'field_date', array('label' => 'hidden')) );
?>

This prints my date in the long format, but under /display I already set it to medium.
Also I have already set the label as hidden under the display settings.

How can I use those settings and only override them if I want to? Or is field_view_field() not the right function?

The content array should already contain an element for each field with the display settings applied. You can just print that directly:

<?php print render($content['field_date']); ?>


Different customer types Is it possible to have multiple customer types within Drupal commerce eg consumer and trade? These would then have different pricing stuctures

Yes, it's just up to you to add the fields or roles to your user accounts and then write product pricing rules to adjust prices through a calculation (10% off for role X) or price swapping from whatever price fields you've added to the product type (base price for normal customers, price 2 for role X, price 3 for role Y). This is just pretty standard Drupal stuff combined with Rules.


Dont save webform data to database For SPECIFIC webforms, how can I make it not save data to the database, but just send the email? It should however still save the files and link to them in the email.

Idk if I can use something like this: https://www.drupal.org/project/webform_clear since this seems to work on all webforms, while I wanna use it only on specific ones.

Thanks

What files are you referring to?

If there are files being generated from webform node content then the data probably has to be saved first in order to generate the files. In this case you should target to delete the nodes once the email has been sent (while allowing for them to be created at first). You can look into Rules module for that.

Webforms all have separate email settings so I'd expect the webform_clear to also offer per-form settings.


How to sync a taxonomy between Drupal and a 3rd-party system? I have a custom made system (non Drupal) that has a taxonomy like:

Element 1
   Element 1.1
   Element 1.2
   Element 1.3
Element 2
   Element 2.1
   Element 2.2
Element 3
   ...

And I have a Drupal site that I would like to be able to:

Use this taxonomy for tagging content, and
Add more terms that the non-Drupal system can use too.

Is there a popular way to sync a taxonomy in a Drupal system with an external system?

You can import taxonomies, and even nested taxonomies, with CSV data generated from your source data. I have been done before and it works quite well with module Feeds.

As for your taxonomy system, you must generate dynamical CSV files (in fact, a PHP or a Drupal node with some custom code), which feeds the Imports you generate in Drupal and which are associated to a vocabulary. In that way you can generate taxonomies with children.


Cannot add 'Page Title' and 'Main Content' blocks to panel Configuration:

Drupal 8.1.5
Panels 8.x-3.0-beta4
Page Manager 8.x-1.0-alpha23
Layout plugin 8.x-1.0-alpha22
Panelizer 8.x-3.0-alpha2

When I create a Panel variant for /node/{node} with Page Manager, I can add field blocks, like

entity_field:node:title
entity_field:node:body

These get rendered.

However, if I add blocks

CORE / Page Title (page_title_block)
SYSTEM / Main page content (system_main_block)

these render to nothing.
Can someone explain why?

Answering my own question after I found some more info.

This is indeed a bug, hopefully to be fixed soon: https://www.drupal.org/node/2626090


How do I create customer/order relationship with entities? I am fairly new to Drupal 7 and especially new to the entity concept.
I need to create a site which records customer data (name, address etc) as well as other objects/entities such as orders, which are related to the customer with a parent/child relationship. I don't know how to do this in Drupal 6 and definitely not in Drupal 7. I know you can create a node reference as a field, but that is not what I want.

I'm pretty sure this has to do with entities, as entities are paralleled to objects, and what I really need is an object to own another object. I am presently listening through tutorials about Entities, but can someone point me in the correct direction to see what exactly I should be looking for (and to perhaps clarify the Entity concept to me).

You should look at Drupal Commerce, a suite of modules that sets up e-commerce in Drupal.  You will have a much easier time adapting Drupal Commerce to fit your needs than you will writing a store from scratch in Drupal.


Good use of content profile I am using Drupal 6 and I have installed the Content Profile module.
First I made 3 extra fields, "gender," "seeking gender," and "dob." Now I want to create a multistep that users needs to fill in with other details.

I was wondering how I can do this using content profile module. I have read that this is a very good module in order to customizing user profiles.

One of the only ways I have been successful at making required multistep forms before having access to the website was using CTools to construct the form workflow, and submitting the data on submit callbacks into Drupal with node_save().

See Intro to Drupal 6 Multistep Form Domination Using Chaos Tools.


Notice: Trying to get property of non-object in my_module_get_nodequeue_id_by_name() (line 30 of my_module/my_module.module) /**
 * Gets the nodequeue id by nodequeue name
 */
function my_module_get_nodequeue_id_by_name($name) {
  $data = db_query('SELECT qid FROM {nodequeue_queue} WHERE title = :title', array(':title' => $name))->fetchField();
  return $data->qid;
}

The above code produced this kind of notice:

Notice: Trying to get property of non-object in my_module_get_nodequeue_id_by_name() (line 30 of my_module/my_module.module).

fetchField() returns a single value, not an object. You either want to use fetchField() like this:

$qid = db_query('SELECT qid FROM {nodequeue_queue} WHERE title = :title', array(':title' => $name))->fetchField();
return $qid;

or use fetchObject() instead:

$data = db_query('SELECT qid FROM {nodequeue_queue} WHERE title = :title', array(':title' => $name))->fetchObject();
return $data->qid;


how can I debug theme.theme file in my theme using phpstorm? I want to set breakpoints in the theme.theme file and debug some variables but I cannot do that as this file isn't a php file. How can I debug this file?

Go to Preferences -> Editor -> File Types
Scroll down the Recognized File Types list until you find PHP; select it
In Registered Patterns add *.theme
Save

You can now set breakpoints in *.theme files.


How to show like and dislike on a View? How I can show Like & dislike button on a view in drupal 8?

If the view is of content type then Like & dislike show but with all fields of content.

If we select views as a field type then there is no option to add Like & dislike.

You can use this module https://www.drupal.org/project/like_dislike. I just tested it with a view and it works perfectly.


How do I retrieve the user ID of the latest editor of a node? I know how to get the user who created a node after getting the node object.

$node = \Drupal::routeMatch()->getParameter('node');
$uid = $node->getOwnerId();
$user = \Drupal\user\Entity\User::load($uid);

Since an alternative to retrieving values of the node object is for example $node->nid->value, I tried to get the revision user ID this way.

$ruid = $node->revision_uid->value;

Unfortunately, this doesn't work, although I see with the Devel module that there is a value. So what is the equivalent in Drupal 8 to $node->revision_uid in Drupal 7?

$node->getOwnerID() returns the user ID for the user who created the node. If you need the user who created the revision, you need to use $node->getRevisionUser(), or $node->getRevisionUserId() for the user ID.


Resetting/reverting a custom module's update 'N value' In my custom module's install file I have a hook_update_N function. Let's say it's mymodule_update_7100. However, I've noticed that I've done it wrong and I want to change a line of code within this function. Seeing as I've already run updb/update.php the changes won't be picked up and I'd have to rename it to either mymodule_update_7101 or create a new function after it with that name. I'd really rather not have to do this, so I was wondering if there's a variable that tells Drupal exactly what "version number" a module is currently at and whether I can reset it to trick it into allowing me to run the update script again.

The actual effect the function has had on the database isn't important because it's just generating a taxonomy term that I can easily delete through the front-end afterwards.

The schema_version column in the system table contains the version of the last successful update. Manipulate that value and you can re-test your update.

The name column is the machine name of the module, same as the info file is named.

This query will do the trick for you.

UPDATE system SET schema_version = XXXX WHERE name = 'name_of_module';


How to Hide Specific Pages to Anonymous Users I need to be able to block the user's URL to be seen by anonymous users. Specifically:

http://www.mysite.com/users/user_name and http://www.mysite.com/user (which are the same page but different URLs).

The first can be done by not giving the permission to view user profiles to anonymous users. The latter is not the same page as for anonymous users that's where they login. Blocking it would prevent anyone from logging in.


Views permission does not work I have created a view by the name of news and there is an option under page setting by the name of access.

I have selected view any news content for the access option, then I have faced a problem. The problem is when I give any kind of view permission for news view, I cant access except give the permission of view any news content.

What do I have to do to give a permission of 'view own news content' so every person can see his/her news content?

Create a relationship between the current content type, and users.

Select Content: Author and click on Add and configure relationships. Leave the settings as they are and click on Apply (all displays).

Filtering the view

Now you need to filter the view to display only content authored by the current user.

Use the filter "User: Current".


Adding a file download link to a node I have a content type recipe and for each recipe type content I want to add a link which can download the recipe for the user.

How can this be done in Drupal 8.5.2?

I'm not sure if I should provide a field to attach the file or if it should be done in some other way like creating a template adding the values to it dynamically and then generating a PDF for the template and attaching a download link for it.

It sounds that you should be able to implement what you want like so:

Add a custom field to your recipe, assume you use a machine name like "file-containing-recipe" (change this name to whatever fits).
For the file-containing-recipe field, specify a field type "file", and combine it with whatever other configuration options that fit (eg: single value or multiple values, optional or mandatory, etc).

To verify your configuration, create a node of content type recipe, and use the newly defined "file-containing-recipe"-field to actually attach your file(s). After saving the new node, verify if the results are what you're asking for. If (still) not, go back to your "file-containing-recipe"-configuration to further tune any of its settings.

Done.


Menu theme suggestion ignored when cache turned on I have an alternative main menu that is used on specific node types.
When turning on the cache the menu block is cached. The theme suggestion for the menu is then ignored.

I tried to disable the menu cache by changing the block preprocess cache settings. But the menu block is not called when using hook_preprocess_block.

Also I tried to change the menu / block by using the hook_page_preprocess

function bootstrap_custom_preprocess_page(&$variables) {
   //disable caches for every top header element
   //we do this as the dynamic header menu can't be cached - because of the landing page node type

   if(key_exists('top_header', $variables['page'])){
      foreach ($variables['page']['top_header'] as $key => $value){
        if(substr($key, 0, 1) !== '#'){
          $value['#cache']['max-age'] = 0;
        }
      }
   }
}

No success.

function bootstrap_custom_preprocess_block(&$vars) {
    if($vars['derivative_plugin_id'] == 'header-navigation') {
        //-- This stops the block being cached in drupal 8
        $vars['#cache']['max-age'] = 0;
    }
}

This works for me. Block preprocess is correct.


Programmatically enable the entity view display I would like to programmatically enable the Layout Builder module. I  followed the instructions given on Layout Builder — building Drupal 8 layouts, but they don't seem to work. They might be outdated for Drupal 9.1. Specifically, I'm having a hard time getting the following piece of code to work.
$entityViewDisplay = \Drupal::entityTypeManager->getStorage('entity_view_display')
  ->load('ENTITY_TYPE.ENTITY_BUNDLE.VIEW_MODE');

Can anyone help me understand it? I just keep getting a NULL result.

I figured it out. You can enable Layout Builder by running the following code in a custom module:
$entity_type = 'node';
$content_type = 'article';
$view_type = 'default';

\Drupal\layout_builder\Entity\LayoutBuilderEntityViewDisplay::load("{$entity_type}.{$content_type}.{$view_type}")
  ->enableLayoutBuilder()
  ->setOverridable()
  ->save();

Hopefully this helps someone else. Having to do it via the UI is painful if you have a lot of content types. I'm actually surprised this isn't a Drush command yet. Oh well.
Source: https://www.drupal.org/project/drupal/issues/3158916


Possible permissions error with drush make I am trying to run drush make distro.make but getting the following error. The only thing I can see I did different was ran sudo drush make distro.make once. Any ideas?

copy(/http---updates.drupal.org-release-history-drupal-7.x): failed to open stream: Permission denied drush.inc:840                                                                                [warning]
Could not download project status information from http://updates.drupal.org/release-history/drupal/7.x                                                                                [error]
Non-existent project type  on project drupal

previously I was running without sudo and it was working fine.

Problem was that running sudo drush had probably added some unwanted permissions to the cache folder. Deleting the folder solved the problem.


How to have multiple instances of a field collection on single content type? I have a content type where I would like to use a field collection to group some fields (radio buttons and textfield). I need many of these on the content type with only the label being different.

I was hoping to make one field collection entity and have multiple instances of it on the one content type, but field collection does not support this.

Basically, I need many instances of a group of fields on a single content type. How can I accomplish this?

There is an issue for that: https://drupal.org/node/1569970
You can try and help that issue get moving.

Or you can give up and create several Field Collection bundles. If you go down that route, you could possibly use Bundle Copy, but it doesn't currently support Field Collections. Luckily, there is an issue for that: https://drupal.org/node/1589118
And that issue has some patches and some testing, so I'd probably just try it.


What is the equivalent of module_load_include()? I have a good amount of experience with D7 but not much with D8, so I'm wondering about the "proper" D8 way of doing things here.

So I've got ModuleA and ModuleB

ModuleB depends on ModuleA.

I need to call a function from ModuleA inside of ModuleB.

In D7, this was done by module_load_include(), and D8 appears to have both this function as well as the ModuleHandler class.

I am trying to instantiate this class and use the load method, but it is throwing an error because I am passing nothing to the constructor:

$module_handler = new \Drupal\Core\Extension\ModuleHandler;
  $module_handler->load('ilib_connect');

TypeError: Argument 3 passed to Drupal\Core\Extension\ModuleHandler::__construct() must implement interface Drupal\Core\Cache\CacheBackendInterface, none given, called in /var/www/company/web/modules/custom/ilib_sso/ilib_sso.module on line 31 in Drupal\Core\Extension\ModuleHandler->__construct() (line 109 of core/lib/Drupal/Core/Extension/ModuleHandler.php).

So I'm not passing anything currently to the constructor (not sure what precisely to pass), and calling the method statically is not a problem, because the load() method references its object and thus causes this error:

Error: Using $this when not in object context in Drupal\Core\Extension\ModuleHandler::load() (line 122 of core/lib/Drupal/Core/Extension/ModuleHandler.php).

So how am I supposed to use this particular class? Or should I just use module_load_include()?

What is the Drupal 8 way of doing things?

The answer is that the load method isn't the correct method, and there's a specific loadInclude() method.

\Drupal::moduleHandler()->loadInclude('ilib_connect', 'module');


creating subsites within my drupal site I'm trying to create a subsite within our current drupal site. The v1 pass is all static HTML, but very soon, like as soon as I get v1 up I'm going to have to add in a few blocks for dynamic content.

I was wondering what the best way to structure this would be. We currently have a "chromeless-html-page" content type which i'm working with. But I wasn't sure if was the most efficient way as I would have to create a chromeless-page object for each page and then link them together. I was wondering would it make more sense to create a subsite-content-type that would be a view and then display all of those subsite-pages?

not sure if that makes sense or if i'm even on the right track with my question. I'm truly lost any help would be wonderful.

If the subsites are spread across multiple sub/domains, you can use domain to display a different set of nodes per-domain.


How To Print Out a Webform Results? Using webform I have created a questionnaire and now I need to be able to print the results on paper. My first solution was going to the result page print out from the browser. Unfortunately, this does not look good on a print when print out.

Here is how it looks like browser.

And I think this looks very decent and acceptable, but when I print this out it will looks like this.

 The print out cut most of my webform results and without all my results this is useless for me.

My second solution was to try it out the Webform2PDF module. However, every time I try to used it does not work for me.

I have try to print out the e-mail I get from webforms but the results are on plain text and the results from the e-mail does not looks very professional. These results are have to be very presentable on paper.

So my question is what is the good approach of printing out the webform results.

You should be able to expose webforms results/submissions activating a complex (but effective) combination of Webform Mysql Views module, Data and Schema modules ...
as stated here for instance: https://www.drupal.org/node/1658784.
It works .. and you can just print your views results.

However, next time if I were you, would have assessed possibile alternatives to webforms.
Have you ever heard about Entity Forms Module?
It rocks, because it overcomes the above mentioned limitations, and also for other very good reasons, as mentioned here under:

Why Entityforms? The case for a Field and Entity based Survey System in Drupal
WHY ENTITY FORMS?


How to use CKEditor for basic HTML formatting with webforms automatic emails? How do I use CKEditor for the 'email template' field when setting an automatically generated email for a webforms submission.

The email template field is found when you go to Content of type 'webform' > Click the Webform Tab > Click the sub-tab Emails > And edit an existing automatic email.

I want to render this textbox as CKEditor and have the email follow through with any bold, underline and heading HTML formatting.

I think the main goal is to receive HTML-formatted emails triggered by Webform module, right? This is how I achieved it:

Create and tune a new Text Format, specifically for emails (admin/config/content/formats)
Install Mime Mail module. It enables you to send HTML-formatted emails. Make it use the just-created text format in settings.
Install Mail System module. It provides you the UI for changing mail system globally or per module, if needed. Simply speaking, with this module you can easily configure HTML mail e.g. for Webform, but leave plain-text format for system emails.
You can use HTML tags in Webform > E-mails > Edit > E-mail template textarea. Mails from the website will be HTML-formatted.

Yes, it does not bind CKEditor to E-mail template textarea, but do you really need it? (If yes, I believe it is possible by creating a custom module that overrides the webform-email-edit-form form changing the element type from "textarea" to "text_format", see e.g. this topic).

Upd. I have just found a separate module for doing the latter thing: Webform Email Input Filter.


JS and CSS image path Do I need to hardcode the image path to JavaScript and CSS files?

#mydiv { background: url(http://example.org/themes/mytheme/image/bg.png); }

I cannot use {{ base_path }}/image/bg.png in .js and .css files, which works in a template file.

Is there better way than hard-coding?

If I understand correct, no need to hardcode images: Add any image through the Drupal program itself via the API or background images via the css and a relative path:

For example, if your image is at theme/images, do {background: url(images/image.png);} or {background: url(../images/image.png);} if your css is situated in a folder of it's own inside the theme's folder.

You could filter or manipulate specific images with JS globally via a custom js file for your site as explained here.


Remove shortlink link and meta tag generator I try to remove shortlink and generator link from my site.

<meta name="generator" content="Drupal 7 (http://drupal.org)">
<link rel="shortlink" href="http://landberg.at/nl/node/109">

I used below code in template.php but when i look in my source code its still there?

function landberg_html_head_alter(&$head_elements) {
    unset($head_elements['system_meta_generator']);
    foreach ($head_elements as $key => $element) {
        if (isset($element['#attributes']['rel']) && $element['#attributes']['rel'] == 'canonical') {
          unset($head_elements[$key]);
        }
        if (isset($element['#attributes']['rel']) && $element['#attributes']['rel'] == 'shortlink') {
          unset($head_elements[$key]);
        }
    }
}

What is best way to remove this?

Above code is good but it didn't work because it was overwritten by Meta tag module. I adjust some settings in Configuration » Search and metadata and now generator tag and shortlink is gone.


How to specify granularity for the Access log Timestamp field to display access log entries using Views? Normally when you select a date field in Views there is the option to specify the 'granularity'. Ie: Day, Hour, Minute etc... ie: When you add the 'Post date' field from a node.

Does this functionality not exist at all for the 'Access log: Timestamp' field, when displaying access log entries using Views?

This would be really helpful for displaying simple custom statistics, but it doesn't seem to exist and I'm not sure where to even look to add the functionality to the relevant module!

Maybe the Views Date Format SQL module is what you're looking for. Here are some details (from its project page):

The Views Date Format SQL module allows to format date fields using SQL. This enables group aggregation for date fields using the choosen granularity.
The core functionality is to remove the date formatting from render() and put it in query(). I.e. format date values using SQL's DATE_FORMAT rather than PHP's format_date. This is achieved by assigning a new default handler to node 'created' and 'changed' date fields. This handler extends and overrides views's build in views_handler_field_date.
The UI is completely unobtrusive, only a single checkbox "Use SQL to format dates" is added to the handler configuration popup.

As an illustration, and/or to better understand the challenge here, you may want to look at Graph node input over time (support date formatting on a continuous axis) also. Comment #3 of that issue states: 'The trouble here is that neither Views nor Date modules provide aggregation options for date-based fields.'.


Use previously-submitted values as default values in a GET-method form I have a custom form defined by the class below :

class MyForm extends FormBase {

    /**
     * @see \Drupal\Core\Form\FormInterface::getFormId()
     */
    public function getFormId(){
        return 'my_form_id';
    }

    /**
     * @see \Drupal\Core\Form\FormInterface::buildForm()
     */
    public function buildForm( array $form, FormStateInterface $form_state ){
        $form['my_textfield'] = array(
            '#type' => 'textfield',
            '#title' => t('My textfield'),
            '#default_value' => 'I want the current value here !',
            '#description' => t('Description of my textfield.'),
            '#required' => true
        );

        return $form;
    }

    /**
     * @see \Drupal\Core\Form\FormInterface::validateForm()
     */
    public function validateForm( array &$form, FormStateInterface $form_state ){
        // Not implemented yet...
    }

    /**
     * @see \Drupal\Core\Form\FormInterface::submitForm()
     */
    public function submitForm( array &$form, FormStateInterface $form_state ){
        // Not implemented yet...
    }

}

The form is then built in my page controller, using \Drupal::formBuilder()->getForm(). It overrides the form's #method attribute to GET because I want the field state to be present in the URL.

I'm looking for a correct Drupal-friendly way to assign the #default_value of my fields with the previously submitted state of the form.

Edit:

If I use a classic POST-method form and I add $form_state->setRebuild(); in ::submitForm(), I can get my values in ::buildForm() using $form_state->getValues(). And the form is automatically rebuilt with the previously submitted values, without having to assign the default values programmatically...

Could-be-related posts

Access data from previously submitted values in buildForm in FormBase plugin
GET method form is not processed

You will have to set query parameters on submit and then you can fetch them and use as default values.

1] Redirect on submit

$form_state->setRedirect($route_name, $route_parameters, $options);

2] Fetch query parameters

$params = \Drupal::request()->query->all();


Resize Image for more than one Image Size profile automatically Here is my problem.

I have field BigPicture in a my Product Content Type.

Is there a way that When I upload an image from BigPicture Field that the current picture automatically resize in more than one image profile.

Here is the desire Image Resize Workflow:

1- Upload the image

2- Automatically Resize and Crop the image in more than one size property (Thumb :120px X 120px, Big : 250px X 250px, ExtraBig 1024px X 760px)

3- The Final File Name for each image should be like MyImageName_Thumb.jpg, MyImageName_Big.jpg, MyImageName_ExtraBig.jpg

I'am using Drupal 7

Thanks a lot

Image styles in Imagecache Actions should handle this for you. But as said above, it will do it on display, not on upload. It will scale/crop however you like (there are extra sub modules for this), and the styles will be sorted into folders by image style, but not rename them. But it will put them in folders like Thumb/MyImageName, Big/MyImageName, etc.

Imagecache actions does have a custom option, I'm not sure if it would let you rename the file:

  Custom Actions - Execute your own PHP/GD code in the middle of an
  imagecache generation process. Requires some familiarity with imageAPI
  internals.


Alter content translation page access based on content's field value I have a content type: Test
I want to alter the permission to translate it based on one of it's field value.
Take the following use-case (field type, and role doesn't matter):

If field_test == '1' then the Translate link task should not be displayed (because the current user role does not have permission to view it).

What do you suggest?

I think something like that already has been answered before:

Could you take a look and tell us if that helps you ?

https://drupal.stackexchange.com/a/208817/8375

Other outside resources: https://www.previousnext.com.au/blog/controlling-access-drupal-8-routes-access-checks


Create a view block on a node reference field (using Node Reference) Creating a related content block on a node reference field. I have two content types: Article and Author.

The content type Article has the field Label: Por 'field_autor' which is a node reference to an author node.

I want to be able to take that ID and lis other articles with the same NID.

The view is setup as such:

Format: HTML List
Fields: Title
Filter: Published;
Type (Article)
Order: Weight

Advanced Options

Contextual Filters: (field_autor) Content: Nid
Relationships: Content: Por (field_autor) - reverse

However, this isn't displaying articles with the same author. Looking for assistance!

UPDATE

There are some decent explanations on the internet

http://www.webomelette.com/related-content-block-views-drupal-7
http://www.webomelette.com/related-content-views-taxonomy-drupal

As well the eva module was suggested as being helpful in my situation, but I haven't tried it yet

Currently, this is still an issue for me.


Redirect Module doesn't redirect from node/{nid} to alias I installed the redirect Module in Drupal 8 but sorrily can't get it to work properly. I enabled all checkboxes in the settings, also the "Enforce clean and canonical URLs" option.

In my page source, the canonical is printed in a meta tag. But if I browse my page and enter a system URL like www.domain/node/5, no redirect to the autopath alias / canonical happens.

Does anyone have any suggestions? I also reinstalled it twice already. Nothing helped.

LEL - it's so stupid, I have to clarify this. The redirect module works without any problem. Everything's just like I wanted it. Maybe it's pointed out anywhere, but I didn't read it.

When the page is set to maintenance mode, it doesn't work. I have some dummy-users that can bypass the "maintenance-page" and use the site. While the site is in maintenance mode, the node/IDs are accessible. When I turned off maintenance mode, the module was redirecting...


Check if administration toolbar is visible How can I check in a theme-file.tpl.php if the administration toolbar is visible or not?

The easiest, but not nicest way to check that, if the user has certain user roles. But is there a way to check that, without checking the roles?

I think using the user_access function to see if they have the "access toolbar" permission should work.

Some example code:

if (user_access('access toolbar')) {
  // Your logic here.
}


What is the best method to allow a user to attach dynamic, custom content sections to a node? I am looking for a recommended approach for a customization in Drupal I am building.

The desired workflow:
A user will be able to attach N number of custom content sections (CCS) to a node. A user will be able to select the type of CCS (see example below), customize it, and arrange it's order amongst all other CCSs attached to a specific node.

Example CCS: Enter in the URLs for several Flikr images and the site outputs this as a nice gallery.

I know how to build the individual functionality for each CCS, but I'm wondering if there is any approach you would recommend for the broader functionality.

looks like you need to use comments module for it, you will modify comments by adding more fields to it (for rating etc), then you can attach unlimited such content to your node. if you're in D6 you need to convert your comments to node (using some module) and then add more fields to it by CCK, and if you're using D7 you can attach fields directly (i guess - b/c its entity now)


How do I control the visiblity of an exposed filter in a taxonomy term view? I've activated the "taxonomy term" (the one that has the description "A view to emulate Drupal core's handling of taxonomy/term.") view and I need to use it to:

expose a filter to the user
only display it on certain taxonomy
pages

My example is this: I've got two vocabularies that are both being controlled by this view. We'll call them Restaurants and Working Locations. Both are "places" with phyical locations and I use the taxonomy display pages to list the various locations. I've also added an exposed filter that users can use to select a particular region for different "restaurants", but I do not want that filter to be on the "working locations" at all. I'm not sure how to achieve this. I've looked at Views Dependent Filters, but I can't get it to work the way I'd like.

So my question is how can I use the exposed filter to show on some taxonomy view pages, but not on others? The traditional filters of content type have not worked.

I'm looking at Rules, and or Contexts to see if this might be an option but I've still not found anything.

Any reason why the "exposed filter as block" option is not available to me in this view?

Thanks in advance.

There is an option in views to display your exposed filters in a block. In this usecase, if you only have one exposed filter, it might work for you to put the exposed filter in a block and then identify the pages you want to display it on in the block administration page.

You could use url aliases and a wildcard * to isolate all terms of a certain vocabulary to save you listing each page in the block admin form.

To put the exposed view in the block: Click on the advanced tab over on the right of the views pane and change 'Exposed form in block:' from No to Yes.


Where does Drupal 7 store custom user account fields? I imported 8500+ external users from an external user table using Feeds module successfully. Now, I am trying to add some more attributes to these users (ie. age, gender, ...). I proceeded to create several new fields for my users under admin/configuration/account settings/manage fields (ie. Age, Gender, ...). However, these fields are now all empty and it would not be possible for me to manually edit these fields for all users.

Could someone please tell me where D7 stores these new fields in the database (which table)? I would like to use a SQL script to automatically update the users with these fields.

PS. Is using a SQL script to update these information the correct approach?

Assuming you're using the SQL storage backend they're stored in the field_data_field_FIELDNAME and field_revision_field_FIELDNAME tables. The field system in Drupal 7 is generic across all entities so field data for nodes/users/all entity types is stored in the same tables.

Rather than input directly into those tables, though, I'd suggest using the Drupal API to load, alter and then save each user instead. The code might look something like this:

// Grab all the uids in the users table
$uids = db_query('SELECT uid FROM {users}')->fetchCol();

// Load the users
$users = user_load_multiple($uids);

// Loop through and edit each user
foreach ($users as $user) {
  // Load the extra data from whatever source you're using
  $extra_data = my_function_to_get_extra_data_by_user_id($user->uid);

  // Update the fields
  $user->field_FIELDNAME1[$user->language][0]['value'] = $extr_data['FIELDNAME1'];
  $user->field_FIELDNAME2[$user->language][0]['value'] = $extr_data['FIELDNAME2'];
  // etc...

  // Save the user object
  user_save($user);
}

You'll probably want to change this code to process the users in batches as it's likely to take a long time to run.


Trigger Emails/Handlers on Webform submissions update Is there a way to trigger the Emails/Handlers, When webform submission has been updated. I'm using webform_mailchimp as a handler. When I'm submitting a new record, handler is working fine and  I can receive the data into my Mailchimp account. I have a function to update the submission via code. But it doesn't trigger, when I update the same record.  Following is my code to update the webform submission:

$webform = Webform::load('my_form');
$is_open = WebformSubmissionForm::isOpen($webform);
$sid = 2;

if ($is_open === TRUE) {
    // Load submission
    $webform_submission = WebformSubmission::load($sid);

    // Modify submission values
    $webform_submission->setElementData('preferred_date', $form_state->getValue('preferredDate'));
    $webform_submission->setElementData('preferred_time', $form_state->getValue('preferredTime'));

    // Validate submission.
    $errors = WebformSubmissionForm::validateWebformSubmission($webform_submission);

    // Check there are no validation errors.
    if (!empty($errors)) {
        drupal_set_message(t('Failed! Please contact the administrator.'), 'error');
    }
    else {
        // Submit values and get submission ID.
        $webform_submission = WebformSubmissionForm::submitWebformSubmission($webform_submission);
        drupal_set_message(t("Success! ".$webform_submission->id()), 'status');
    }
}

Is there a way to trigger the handler through code(programmatically)?
Is there a default configuration in the CMS?

Thanks guys,

The below code is untested but should point you in the right direction.

// Get a handler.
$webform_submission = WebformSubmission::load(WEBFORM_ID)
$handlers = $webform_submission->getWebform()->getHandlers();
$handler = $handlers[HANDLER_ID];

// Invoke submit form.
@see \Drupal\webform\Plugin\WebformHandlerInterface::submitForm
$form = []; // Might need to get the $form.
$form_state = new FormState(); // Might need to be build the form state.
$handler->submitForm($form, $form_state, $webform_submission);

@see \Drupal\webform\Entity\Webform::invokeHandlers

@see \Drupal\webform\Entity\WebformSubmission::invokeWebformHandlers


When I load an overlay to edit a node, how can I open a specific vertical tab? I have a content type with field collections. I want to open an overlay to edit a node but switch to a tab for a specific field collection. Does anyone know how I can do this?

I can open the overlay with #overlay=node/16/edit, but this will just go to the first vertical tab.

I took a look at vertical-tabs.js, and as best I can tell you'll have to add some JS to the page to trigger the click event on the correct link. On line 33, the Drupal.verticalTab object gets instantiated, but not assigned to a namespace where you can get to it later to run its focus() method. (This would be a good thing to fix in D8. Hmm.)

So basically, you need a .js file that does something like

(function ($) {
  Drupal.behaviors.yourModuleName = {
    attach: function (context, settings) {
      $('a:contains("Revision information")').click();
    }
  };
})(jQuery);

where "Revision information" is the actual text of the link that opens your vertical tab.

Note: There is some URL fragment handling in vertical-tabs.js, which I think is supposed to make it so that if you set the URL fragment to the id of a fieldset, that vertical tab will open automatically. It might be worth trying, but I couldn't get it to work even on a non-overlay page.


Moving a div down if a zone is present using jQuery I'm trying to move a <div> down if a zone is present, but I'm having a little trouble targeting the right classes, etc.

// See http://jsfiddle.net/xgbzm/.
(function ($) {

  if (!$(this).hasClass('responsive-layout-normal')) {
    if ($('.page .section-header .zone-ticker-wrapper', this).length < 0) {
      $('.qtip .qtip-wrapper', this).css('margin-top', '65px');
    }
  }

})(jQuery);

How can I achieve it?

At a guess I'd say your problem is context...$(this) won't be defined in your current code.

First thing to do is make sure the code runs on document ready so the elements you're targeting actually exist:

(function ($) {
  $(function() {
    // ...
  });
})(jQuery);

Next you need to handle $(this). In your current context you would need to check the <body> tag for that class, e.g.

if (!$('body').hasClass('responsive-layout-normal')) {
  // ...
}

And finally, since you're using a responsive theme you probably want that code to be responsive, and run when Omega changes its media query. Note that now, since you're binding to the <body> tag, and have proper context, $(this) will refer to the element you're expecting:

(function($) {
  $(function() {
    $('body').bind('responsivelayout', function(e, d) {
      if (!$(this).hasClass('responsive-layout-normal')) {
        // Make changes
      }
      else {
        // Undo changes
      }
    });
  });
})(jQuery);


How do I map active directory group membership (ldap authorization) to og groups in open atrium? I can successfully bind to the ldap server, and I have set up authentication successfully - ldap users can log in to my open atrium site. However, the authorization mappings for the groups aren't coming through.

I have this as a mapping under:
admin/config/people/ldap/authorization/edit/og_group

CN=Human Resources,OU=Groups,OU=Domain Users,OU=Domain Controllers,DC=domainname,DC=com|node:100:6

Where "100" is the node id for the open atrium space (og group), and "6" is a custom group admin role with a set of permissions defined in:
admin/config/group/roles/node/oa_space

However, when I log in with a user that is confirmed to have this "memberof" attribute in active directory, the user does not have the corresponding access to the organic group.

I have tried both "Convert full dn to value of first attribute before mapping" checked and unchecked with the same results.

The mapping is shown to be enabled here:
admin/config/people/ldap/authorization

I'm finding the documentation a little lax here. Am I mapping the correct og role id? Does the og role id translate to the role id in admin/config/group/roles/node/oa_space? Is this set somewhere else? Where? Is there anything else I have to do to bring these mappings over?

I had this same problem recently whereby this was originally working:

GroupA|IT:member
GroupA_Admins|IT:member
GroupA_Admins|IT:administrator member

During this course of development this stopped working and on alternate logins a user in that LDAP group would either be a member of the organic group, or not (but never an administrator of that group).

I eventually worked out that it had stopped working because I had since overridden the permissions of the space, which meant that the OG role ids were different, even though they had the same name.

Therefore:

GroupA|IT:member
GroupA_Admins|IT:member
GroupA_Admins|IT:administrator member

was being automatically converted to

GroupA|IT:member (raw: node:3:5)
GroupA_Admins|IT:member (raw: node:3:5)
GroupA_Admins|IT:administrator member (raw: node:3:6)

when actually since it was no longer using the default roles, it should have been using 8 and 9 instead of 6 and 7.

Rewriting the mapping to explicitly use the ids for the overriding roles rather than their names worked:

GroupA|node:3:8
GroupA_Admins|node:3:8
GroupA_Admins|node:3:9

I know this is a very old post to reply to, but I was struggling with this yesterday so hope it helps someone else in future.


Why ajax form submit stop working after set form submit #id? My question is related to https://drupal.stackexchange.com/questions/98501/why-ajax-form-doesnt-work-after-paging-by-views-infinite-scroll

I try to do workaround by setting my own submit button id.

   $form['mymodule_submit'] = array(
      '#type' => 'submit',
      '#value' => $value,
      '#ajax' => array(
        'callback' => 'mymodule_like_form_ajax',
      ),
      '#attributes' => array(
        'class' => array($class),
        'id' => 'mymodule-like-form-' . $node->nid),
      )
   );

But in this case ajax submit doesn't work at all...
What am I doing wrong here?

JS recognizes things by ID. But Drupal's AJAX only knows Drupal-generated ID. That's why when you change ID manually, it tries to attach click listeners to DOM nodes with IDs that are not there.

If you change ID to some custom value, you must also provide custom JS to attach all .on to the objects with new ID.


The web service endpoint returned a "HTTP/1.1 403 Forbidden" response There are 12 or so similar questions but not drupal related.
Here is my site on a digitalocean  droplet: http://104.236.27.226/

It is apache2 on ubuntu16 php7.
I am using: 000-default.conf:

ServerName casey.com
ServerAdmin webmaster@localhost
DocumentRoot /var/www/html
<Directory "/var/www/html">
  AllowOverride All
  Require all granted
</Directory>

I made file permission as permissive as possible:

drwxrwsrwx  4 casey    www-data 4096 Sep 20 12:15 www/

I put an echo in the settings.php, at the very end to show the user for  apache:

casey@dchouse02:/var$ tail -n 3 www/html/sites/default/settings.php
echo('
ECHO: from setting.php after databases array; and apache user is (via exec whoami): ');
echo exec('whoami'); echo ('
');

Knowing that settings.php is being read, I moved to indx.php for this D7 site:

casey@dchouse02:/var$ tail -n 3 www/html/index.php
echo('
from index.php: before menu_execute_active_handler:
');
menu_execute_active_handler();
echo('
After menu_execute_active_handler
');

At this point the error appears:

The web service endpoint returned a "HTTP/1.1 403 Forbidden" response

The list of apache processes look similar to what I get from the ubuntu on my laptop:

casey@dchouse02:/var$ ps aux | grep apache
root     16068  0.0  4.7 327752 23512 ?        Ss   16:59   0:00 /usr/sbin/apache2 -k start
www-data 16071  0.0 10.2 345548 51244 ?        S    16:59   0:00 /usr/sbin/apache2 -k start
www-data 16072  0.0 10.2 343656 51176 ?        S    16:59   0:01 /usr/sbin/apache2 -k start
www-data 16073  0.0 10.7 347648 53632 ?        S    16:59   0:00 /usr/sbin/apache2 -k start
www-data 16074  0.0 11.1 349660 55520 ?        S    16:59   0:01 /usr/sbin/apache2 -k start
www-data 16075  0.0 10.1 345548 50888 ?        S    16:59   0:01 /usr/sbin/apache2 -k start
www-data 16099  0.0 10.0 343428 50248 ?        S    16:59   0:00 /usr/sbin/apache2 -k start
www-data 16764  0.0 10.3 345600 51792 ?        S    18:37   0:00 /usr/sbin/apache2 -k start
www-data 17344  0.0  1.3 327784  6612 ?        S    21:38   0:00 /usr/sbin/apache2 -k start
www-data 17347  0.0  1.3 327784  6612 ?        S    21:38   0:00 /usr/sbin/apache2 -k start

I don't know what else to do to troubleshoot  this.

This is a pretty basic error most likely having to do with your digital ocean config than Drupal. You've got a named virtual host (casey.com) in your config file. Not sure how pointing us to an IP address helps us to help you.

Read through the digital ocean server set up documentation and make sure you've covered all your bases.


How can i add edit profile link dynamically? I have change the default user account page url to cms/dashboard and its redirect to custom page where edit profile link is not available. So i want to add the custom edit link, i add the block image and add the link to that image which is cms/[account:uid]/edit but its converting like cms/%5Baccount%3Auid%5D/edit. Is there any other way to add the Edit Profile link so that user can access the default edit page and change the profile information.

You can use the link directly as /user. It goes to the profile page which is similar to the /user/{$GLOBALS['user']->uid}

OR

Use Token module  to create a menu link with this path: user/[current-user:uid]/edit.


Hide "Submit"/"Save" button until file has finished uploading I'm having a problem where my site users are submitting a form before the files they are uploading into filefield are finished, this is causing an ajax error to pop up along the lines of "an ajax HTTP request terminated abnormally".

To stop this mistake from happening is there a way to hide the "Submit"/"Save" button until file has finished uploading?

Havent tried this, but you might be able to use jquery's global ajax event handlers, to hide the submit button, in particular the .ajaxStart() and .ajaxComplete() handlers. Something like the following, added in a .js file in a custom module (not tested):

(function ($) {
  Drupal.behaviors.YOURMODULE = {
   attach: function (context) {
     $(document).ajaxStart(function(e){
       $('#edit-submit').hide();
     });
     $(docment).ajaxComplete(function(e){
       $('#edit-submit').show();
     });
   }
  };
})(jQuery);

You'd have to edit that to work the way you need it to, save it in a js file, and add it to the node edit form (or any other form you need it for).

Aside from that, the "ajax HTTP request terminated abnormally" errors occur in D7 whenever a http request is made before an ajax request has completed. In my opinion this is undesirable behaviour. It's been discussed here, for example, and the prevent js alerts module suppresses such errors across your site.


Can I create a url alias for private files? Should we be able to add a url_alias (in D8 from /admin/config/search/path) for a private file?
Right now it allows me to add an alias (and I can see that it is being rendered in the front end) but it generates a 404.

In my particular case the path for the uploaded file is ...
/system/files/2017-08/1.pdf

A related, but different question, includes ...

How can I change the file private URL

Interesting question.

In theory, every routed path should be able to have an alias because it runs through \Drupal\Core\PathProcessor\PathProcessorAlias::processInbound() before routing, which converts it back to the system path.

However, private files, and image styles are special and quite weird. Because the routing system does not really support having an argument with / and doesn't know how to properly map that to a single argument (Not sure if that is still true or if there would be a better way now with more recent symfony versions), we have a workaround.

That workaround for private files is \Drupal\system\PathProcessor\PathProcessorFiles::processInbound(), which converts the full private path to just "/system/files" with file as a query argument.

The problem is now that those two run on the same event, and PathProcessorFiles runs first, at that point, the path is still the alias and does not match system/files/$something.

I'd say this is a bug and the priority of the service definitions should be adjusted for this. That is path_processor.files (currently 200) and path_processor_alias ( currently 100). Setting the first to 99 and clearing caches makes it work for me.

I'd suggest you open a core issue for this, I suspect nobody tried this yet.


Find entity field order and display names in code In PHP code, in Drupal 8, how can I get the display names and the order of entity fields to be displayed in a particular view mode.  I'm specifically trying to get the order of fields in node and paragraphs entities.

I've tried inspecting the node object, using the serializer service and REST interface.  I can find the fields and data, but not this metadata.

In Drupal, the display of fields is controlled by display mode configuration entities, which define the configuration for field formatters and the such.

You cannot get this metadata by viewing the node itself (or other entity). You would have to load the display mode for it.

The config object is entity_view_display and may be accessible over RESTful endpoints. An example output (in YAML) looks like so:

content:
  body:
    type: text_default
    weight: 0
    label: hidden
    settings: {  }
    third_party_settings: {  }
    region: content
  variations:
    type: commerce_add_to_cart
    weight: 1
    label: hidden
    settings:
      default_quantity: '1'
      combine: true
      show_quantity: false
    third_party_settings: {  }
    region: content
hidden:
  created: true
  stores: true
  uid: true


Edit Shipping Address on existing order Is there any way to edit the shipping address on an existing order? I only see the billing address in the edit screen.

Not sure if that works in all cases, but in mine - I managed to enable shipping form this way:

go to Home >> Administration >> Commerce >> Configuration >>
Order types >> Edit [your order type]
(/admin/commerce/config/order-types/[order_type]/edit/form-display)
select "Manage form display" there
find "Shipments" line there
switch it to Inline entity form - Complex

And instead of autocomplete for shipments I got form with edit button that allows me to change shipping address for order.

Order display settings screen:

Edit order page shipping block after update:


How do I filter a view page with contextual filter? I have an all events views page where I would like to put the links 'All Events', 'Upcoming Events', 'Past Events' in the header.

I would like to link them to the same views page but show filtered results. It seems possible by looking at contextual filters but not sure which way to go.

Thanks,

You could use this module to set up the date field for the events: http://drupal.org/project/date.

This video explains how to use arguments with the date module:
http://www.drupaltherapy.com/date_d7

Then create 3 view pages, with the only difference being the arguments of each page view to determine if the date is:
1) in the past
2) in the future
3) doesn't need to be filtered by date

Each view page would get its own path.
Then you could create a menu with the different paths as links.

Once you have your menu set up, go to Structure- Blocks - and you can configure the menu to be in the content area, and paste the paths of the 3 pages you've created, separated by commas in the section that says SHow Blocks on Specific Pages.

Hopefully that gets you on the right track.


User submitted content in drupal (Drupal Noobie) First off, I would like to state that I am a total noobie when it comes to Drupal and do not have a great deal of experience with web development in general.  On the other hand I have a good deal of experience programming in general and will not shy away from some serious PHP hacking.

I am trying to create a webpage that will allow users to submit project files (which will be .zip files) which need to be extracted, then analyzed, then stored.

I would like to have a main ladding page that will allow user to navigate to different types of projects or allow them to follow a link to submit their own project.

So far I have not been able to find many good resources that talk about challenges associated with user generated content.  Can anyone suggest any books, videos, tutorials, really anything that would help me get started on this specific topic?  I own the book Drupal 7 module development, which was a decent starting point but doesn't really offer much information about my specific problem.

Also, any modules that might be helpful for this task?

EDIT:

So far I have been able to create a new content type which can be added using add content and then will show up in one of the main tabs on my basic page.  So far I only allow the user to add screenshots and a title, one big thing I am wondering if how would I handle anything more complex?  So far I have created everything by using the GUI interface under structure->content types but I see no way that I could call some php code after the user has uploaded the project to unzip their project and do whatever else I need to do.  Am I going about this wrong?

Have you taken a look at Open Atrium? It is not a Drupal module, rather a Drupal distribution pre-configured with a set of modules to help you manage projects. It includes functionality to upload files into projects, allows users to create new projects, etc.

Open Atrium has been around for a few years now, and it is pretty stable. Since it is Drupal (and hence, GPL'd), if the features that it brings does not satisfy your needs, as always, you can create your own modules to extend the existing functionality, or as a minimum, you could use Open Atrium to provide you ideas on how you might structure your project, which modules might help you out, etc.

There's also Storm, but it is currently available only for Drupal 6.x, and it's 7.x version is still not stable.


Date/Time not saved correctly? I made a date range field, and after entering some values and saving on first glance it looks ok, if i entered 20:00:00h it will display the same, but in the DB when i look at the stored values it's -2h (so 18:00:00). Anyone know why?

Also this is a huge problem when manually retrieving the values from the node, i fiddled around the time zones etc but i always get the value stored in the DB.

$node = Node::load($node_id);
$date = $node->get('field_date_ept2')->getValue()[0];
$result = \Drupal::service('date.formatter')->format($date['value'], 'custom', 'Y-m-d\TH:i:s', 'Europe/Berlin);
echo $result; // 2019-12-12T18:00:00

p.s. the timezone in my drupal 8 site is "Europe/Berlin" and the same as in my php.ini file.

The datetime value stored in DB is the UTC value. Any built in date formatter should give you the correct local time on the page. However if you need to manually get it from DB you'll have to convert the timezone yourself.


When taking a copy of the node template do you need to maintain the article tag that is in there When taking a copy of the node template, should you keep/maintain the original code that is in the file?

Example the article tag.

nid; ?>" class=" clearfix"> etc..

What are the implications of removing this, if any?

Actually you're free to edit templates !

The theme's css might depend on some tags, especially the article tag, so you could lose layout/design
If you're a forward thinking brave drupalista you definitely want to keep title logic and the possibility of rendering all fields (and comments) and respect the view modes ;)


Display certain taxonomy terms in Select List? I have my content type set up something like this:

type (select):
  type1
  type2

taxonomy_term_reference (select):
  term1
  term2
  term3
  term4
  term5
  term6

When a user fills out my node and chooses type: type1, I want only these terms to show up as options:

  term1
  term4
  term5

When a user fills out a my node and chooses type: type2, I want only these therms to show up as options:

  term2
  term3
  term6

Is there any good way of doing this?  The only way I can think of is with custom code via hook_form_alter()?

Try reference-option-limit module. It has the ability to limit your reference field value.

Another approach is to use entity reference instead of term reference and add an entity reference display to a views and select what items you'd like.
Then in your content type reference field setting and under entity selection select the views you just created.

I hope this will help.


Drupal 6 querying multiple tables Having some trouble with the Drupal 6 query syntax. My query works fine on its own:

SELECT term_node.tid, term_data.name FROM term_node, term_data WHERE nid = 22640

Below is what I have when I convert it for use with drupal 6:

$currentTIDs = db_query("SELECT {term_node}.tid, {term_data}.name FROM {term_node}, {term_data} WHERE nid = 22640");

while ($cTids = db_fetch_object ($currentTIDs)) {
array_push($currentTIDsArray, $cTids);
}

drupal_set_message('<pre>' . print_r($currentTIDsArray, TRUE) . '</pre>');

This results in an empty query / array? Any Ideas?

I think you need a proper inner join.

Tweaking your snippet to:

$currentTIDs = db_query("SELECT tn.tid, td.name
                         FROM {term_node} tn
                         INNER JOIN {term_data} td
                         ON tn.tid = td.tid
                         WHERE tn.nid = 22640");

while ($cTids = db_fetch_object ($currentTIDs)) {
   array_push($currentTIDsArray, $cTids);
}

drupal_set_message('<pre>' . print_r($currentTIDsArray, TRUE) . '</pre>');

I digress, but worth mentioning Drupal coding conventions on variable names etc.. can be found here: http://drupal.org/coding-standards#naming