How to pass parameters to same form after form submission? I have created a module that creates and displays a table and with a filter element. What I would like to do is when the user enter a string into the filter can submits it, I then use that string to filter the results of the table. What I am having an issue with is how to pass that string back into the form creation function to filter the results.

This is what I have in the submit function:

function submission_list_form_submit($form, &$form_state) {

  $filter = array();
  if (isset($form_state['values']['filter_user'])) {
    $filter['username'] = $form_state['values']['filter_user'];
  }
  return $filter;
}

Which is not right obviously. How do I get the $filter variable to be passed back into the submission_list_form function that creates the page? This is being done with Drupal 7.

Thanks.

You can use the following code, to achieve what you want.

function submission_list_form_submit($form, &$form_state) {
  $filter = array();

  if (isset($form_state['values']['filter_user'])) {
    $form_state['filter']['username'] = $form_state['values']['filter_user'];
  }

  $form_state['rebuild'] = TRUE;
}

The form building function should then check if $form_state['filter'] is set.

function submission_list_form($form, &$form_state) {
  if (isset($form_state['filter'])) {
    // …
  }

  // …

  return $form;
}

If the code doesn't work, use another array index instead of $form_state['filter']; it is probable that in such case the array index conflicts with the one used by Drupal or a third-party module. I would rather prefix the array index with the short module name, to be sure to avoid conflicts with other modules or future Drupal versions.

References

drupal_build_form()


Calling a Method from another Module's Class I'm dumb and this is embarrassing, but I'm trying to figure out how I properly use a method from a class in other parts of my code. I need to understand the Drupal way, if not just the php way.
I have a class like this...
namespace Drupal\module_name\Utilities;

use GuzzleHttp\Exception\RequestException;
use Drupal\Core\Logger\LoggerChannelFactory;
use Drupal\Core\Messenger\MessengerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use GuzzleHttp\ClientInterface;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\DependencyInjection\ContainerInjectionInterface;

class Example implements ContainerInjectionInterface {

  private $client;
  protected $loggerFactory;
  protected $messenger;
  protected $config;

  public function __construct(
    LoggerChannelFactory $loggerFactory,
    MessengerInterface $messenger,
    ClientInterface $client,
    ConfigFactoryInterface $config
  ) {
    $this->loggerFactory = $loggerFactory->get('simple_mailchimp');
    $this->messenger = $messenger;
    $this->client = $client;
    $this->config = $config->get('module_name.settings');
  }

  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('logger.factory'),
      $container->get('messenger'),
      $container->get('http_client'),
      $container->get('config.factory')
    );
  }

  public function request() {
    return 'whatever';
  }
}

What's the proper way to use this class somewhere else? For instance, in another module, I want to call the request() method shown above.
  $example = new Example();
  $x = $example->request();

This doesn't work, as shown above. I get this...
ArgumentCountError: Too few arguments to function Drupal\module_name\Utilities\Example::__construct(), 0 passed... and exactly 4 expected

(Even though it seemed to have worked at one time.)
That said, what's the right way to go about this with Drupal, or in general, I guess?

If you want to instantiate a class implementing ContainerInjectionInterface you have to use the Drupal class resolver:
$example = \Drupal::classResolver(Example::class);
$x = $example->request();

The preferred way though is to use a service class instead and inject other services directly as container arguments, as @Kevin commented.


How do I split the CCK e.g. add node form into a wizard? I would like to split an /node/add form into multiple parts in a wizard format. Ive seen tutorials for doing this with registration but not with node/add. Any tips?

Check out multistep node form

  For each step you can define which fields should be included in this
  step. "Fields" includes core-fields like "Title", "Body" or "Authoring
  information" as well as fields defined by other modules (e.g. Date).


Drupal 8 Query Questions Is there a reason to be using \Drupal::database() vs \Drupal\core\Database\Database::getConnection()?

How do I know when I can chain my query methods and when I can not? For example

$db = \Drupal\core\Database\Database::getConnection();

$query = $db->select('node', 'n')
  ->fields('n', ['nid'])
  ->condition('type', 'blog');

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

vs

$db = \Drupal\core\Database\Database::getConnection();

$query = $db->select('node', 'n');
$query->fields('n', ['nid']);
$query->fields('nb', ['body_value']);
$query->join('node__body', 'nb', 'n.nid = nb.entity_id');
$query->condition('n.type', 'blog');

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

Is there a reason to be using \Drupal::database() vs \Drupal\core\Database\Database::getConnection()?

Yes. The former returns a correctly instantiated service object, with all required dependencies automatically injected. You would need to load up all the relevant services yourself and inject them manually if using the latter method.

  How do I know when I can chain my query methods and when I can not?

There are 2 common approaches:

Read the docs for the methods you're using.
Use an IDE with good code completion.


How do i attach a an element to user account? I have added a custom form element in login form. I need to link this new element to user account on logging in.

I need to add and get entry to the table "users_data" in Drupal 8.
This can be done by defining a class EmployeeDetails and then fetch the value like this :

$employee_details = new EmployeeDetails($account);
$employee_details->setEmployeeNumber($value);

My Question is in which file should i define EmployeeDetails class? What should be file name, should i use .inc extension and where in the module should be this file placed?

As reported in users.data column replaced with user_data API, the equivalent of using the user.data column, in Drupal 8, is using the user.data service.

So, if in Drupal 7 you used $value = $account->data['mymodule_xyz'];, in Drupal 8 you will use the following code.

$value = \Drupal::service('user.data')->get('mymodule', $account->id(), 'xyz');

The code to set its value is the following one.

\Drupal::service('user.data')->set('mymodule', $account->id(), 'xyz', $value);

As usual, when possible, use dependency injection to get the service, instead of using the \Drupal class.


How to Edit a contributed module I am using the Feedback Module, and I need to add an email field to the feedback form. How can I make the necessary edits to the Feedback Module in such a way that they stay when the module is updated?

You should never edit core or contributed modules if it can be helped (which it almost always can).  I haven't used Feedback, but the general Drupal way of extending forms is to use hook_form_alter from your own custom module.

Basically create a simple module.  All it needs is a mymodule.info file and a mymodule.php file inside of a folder in /sites/all/modules. Here is some more info on creating a module.

Then in your mymodule.php file, add a function that looks something like this:

/**
 * Implements hook_form_alter().
 */
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'FEEDBACK_MODULE_FORMID') {
    $form['custom_email'] = array(
      '#type' => 'textfield',
      '#title' => 'Email',
      '#required' => TRUE,
    );

    $form['#submit'][] = '_mymodule_feedback_form_submit';
  }
}

This will add a new field to the form, and register a submit callback for the form.

Finally write the _mymodule_feedback_form_submit function to actually do something with the value when the form is submitted.


kpr() in my form validation and submit function is not being called In my form validation and submit functions, kpr() is not being called. Is there a better way to check that I'm in those functions? If kpr() isn't ideal to output my $form_state array, then what is ideal?

Everything that is output with drupal_set_message() (the function that kpr() uses to output the message) could not be visible from the browser if code redirects the user to another page after drupal_set_message() is called and before the page is rendered. After a form is submitted, the users are redirected to a page whose URL is set in $form_state['redirect'] or $_GET['destination']; the latter takes the precedence over the former.
To avoid the users are redirected after the form is submitted, you can:

Set $form_state['rebuild'] to TRUE
Set $form_state['redirect'] to FALSE

Setting $form_state['no_redirect'] to TRUE would have the same effect, but form builder functions, form validation handlers, and form submission handlers should never set $form_state['no_redirect'].

A preferred method would be calling watchdog(). If you have the Database Logging module enable, then the message output from the module will be visible in admin/reports/dblog.

For debugging messages, you can call watchdog() passing WATCHDOG_DEBUG as value for the $severity parameter.

References

drupal_redirect_form()


How Do I change existing theme to a new one without losing content? Can someone lead me to documentation that explains how I can change an existing Drupal theme to a new one without losing all of my existing content?

The blog I manage is currently set up on the Omega 7.x 3.1 framework, with a semi-custom subtheme. We would like to install a new theme with more out of the box capabilities and a better design but it is important that the two years of published articles are maintained in the current chronological order and with their image content, etc.

Any help finding the instructions on how to accomplish this will be a great help.

Best wishes from Spain!

Technically you won't loose any of your content since Drupal's theme layer is seperate from the content. Depending on how your previous theme is set up (templates, theme functions, etc) it can however happen, that the display of some of your content might not work / work differently in another theme.

A good starting point for learning more about Drupal's theme layer is the Theming Guide which is part of the Community Documentation at drupal.org. A more advanced view on theming can be found in the chapter 'Themes' of the book Drupal 7 – the Essentials which you can actually read online at drupal.org.


how to set minimum quantity of products in the shopping cart? I want to set minimum quantity of goods that customer may order in the shop. For example minimum quantity is 20, so if customer order less then 20 his order won't process and there will be message telling him that he must purchase 20 or more and redirecting him to his shopping cart

You could try using the Commerce Minimum Order Quantity and Increment sandbox module.

  The module allow you set minimum order quantity and an order quantity
  increment. This quantity is for the entire order not each product line
  item. Your shoppers will not be able to check out until their order
  quantiy reaches the minimum and/or meets the increment.

  Download this module and install it. Go to admin/commerce/config/moqi
  to config.

Source: Twitter


How to make a sticky post on appear on top within a view I've created a view which is organised by date. All works fine, however I'd like to add the sticky functionality to it, where whenever a node is marked as sticky, it'll go to the top of the list regardless of the date. How can I achieve that?

Just sort by sticky and after that sort by date.

As simple as that, it should do the trick for what you want to do.


How to check Drupal distribution version from CLI? I have OpenAtrium2 instance and I want to check it version from CLI.

How can I do it?

Just run the following command from the root directory of your Open Atrium installation:

drush status-report

This should give you the output similar to the status report screen in the standard Drupal backend. In my Open Atrium installation, one of the lines reads:

Install profile            Info      OpenAtrium (openatrium-7.x-2.18)

So in this case I'm running Open Atrium version 2.18.


How do I create a link that points users to the edit profile page? I would like to create a link that leads each user to their edit profile page.

What should I use as URL? I get access denied on the paths I tried, including http://example.com/user/[uid]/edit.

You might want to try using the Menu Token module, so you could add a user id token in the path.

Otherwise you'd need to create a page callback in a custom module using hook_menu(), say to 'user/edit', and in that callback, redirect the user to 'user/[uid]/edit'. That way you could add a menu link to 'user/edit' and it would work. See this comment for an example.


How to add to index unpublished content by apachesolr? I use apachesolr module for index content.
As I understand, this module does not provide indexing unpublished content.
Is it some trick to avoid that?

I try to use this hook and change status callback, but it does not work.

function hook_apachesolr_entity_info_alter(&$entity_info) {
  // Validate each entity if it can be indexed or not. Multiple callbacks are
  // allowed. If one of them returns false it won't be indexed
  $entity_info['node']['status callback'][] = 'apachesolr_index_node_status_callback';
}

p.s. it duplicate with this issue, but there no activity and it's very old.

You may want to follow this thread: Index unpublished nodes. There is no available patch right now but you'll find some hints to build your own custom module if you need to.


How do I sort a view by content type? I use a View to show search results (core Search module). In the view I have grouped the grid on the field "Content type". This works fine, each content type is shown under it's own title.

But under "Sort" in the View I can only sort the content types by ASC or DESC. But I would like to use a custom sort order like "node type = product", followed by "node type = accessories" and so on.

How to do that? I have tried using hook_views_query_alter() and hook_search_api_query_alter() and a few other tings, with no luck.

If you're looking to arbitrarily order nodes, that is the use case of Weight module. The module lets you add a field to any node type with a customizable weight range. Once added to your node types, you can configure any View to use this field to sort your nodes.


How to programmatically delete all values in custom CCK field for a given node? I'm on Drupal 6, and I have a multiple value CCK field. I need a PHP function to delete all the values in that field so I can later repopulate it. I am currently doing this:

if (isset($node->field_received_email[0]['value'])) {
  foreach($node->field_received_email as $key => $value) {
    $node->field_received_email[$key]['value'] = NULL;
  }
}

However, sometimes when I later repopulate it, I get Drupal dblog errors like:

  Duplicate entry '16026-133' for key 'PRIMARY'
  query: INSERT INTO content_field_received_email (vid, nid, delta,
  field_received_email_value) VALUES (16026, 15888, 133,
  'whatever@email.com')

It appears that the primary key is remaining, and so when I go to write data again to the field it gives the duplicate primary key error.

Any suggestions on how to really delete all the values and keys from a multiple value CCK field in a given node so I can later re-write them?

Thanks a lot!

Try to unset item

if (isset($node->field_received_email[0]['value'])) {
  foreach($node->field_received_email as $key => $value) {
    unset($node->field_received_email[$key]);
  }
}


How to remove reference field value after delete its reference node Let say, I have 2 nodes.
In first node, I add a reference to an existing node, e.g. Test node [nid:2];   I delete the referenced node. When I edit the first node,the reference field shows [nid:2].

How can I make that reference field empty, once the referenced node is deleted?

Try using Reference Delete module..

Project page says

  Deletes values in reference fields created with Entity Reference or
  References when the referenced entity is deleted.


Expose Custom DB Tables to Drupal Views Error I am trying to display an already existing table to Drupal Views. This table exists within my current Drupal Database, along with my Drupal tables.
The table's name is ACCOUNT_PNL and I would like to expose the fields in this table to Drupal Views.
I've followed the instructions here, but when I go and enable this module, I get the following error from my site:
DatabaseSchemaObjectExistsException: Table ACCOUNT_PNL already exists. in DatabaseSchema->createTable() (line 657 of /var/www/drupal7/includes/database/schema.inc).

I understand that the table already exists, but isn't the tutorial code supposed to only "expose" it to Views so I can then use Views to display it?
Perhaps there is an error in my understanding, any help would be appreciated.

The tutorial you linked to implements hook_schema() which means Drupal will want to take care of the table implementation for you.

I don't know this for definite but I think Views requires that the table be under Drupal's control when you're exposing custom data.

I don't know of a way to tell the installer to ignore the schema installation, so the simplest thing to do would probably be to rename the custom table temporarily, install the module (allowing Drupal to create the table), then import the data from the temp table into the newly created one.

If you then uninstall the module (not just disable), your custom table and the data will be lost so it's worth keeping a backup if you think that's likely to happen.


Menu view does not render when editing profile2 profile I am using profile2 and "Menu Views". Why would a view that I have in the menu not return any results at all when editing a user's profile (at the url /user/XXX/edit)? The menu view works on every other page of my site.

Maybe it's because I am theming the profile editing page? I can actually display the menu theme that i'm trying to display on my site's menu on the page itself by putting code within the theme, but no matter what I do it will not display in the menu on this page.

The issue here ended up being that Drupal considers the page where a user edit's his profile in Profile2 an "admin" page. And, as of this writing, menu_views.module (line 159) does not process menu views on admin pages. This has been reported to the module in the form of re-opening http://drupal.org/node/1790444.

Hopefully this helps somebody else as this was a very tough one to trace down.


Upgrading Drupal 7 version from DEV to PROD I've updated from Drupal 7.22 to 7.34 on my Development Machine along with some Module updates. Now I am going to update my Production environment.

Question: Do I have to upload the entire root directory or can I just upload the Sites folder? I'm assuming I have to upload the entire root directory as this is a Drupal 7 version core update.

P.S. Got the database update stuff covered.
P.S.S Would use Drush, but I'm just not comfortable with it yet.

Regards,

John

Even thought you said that you are not comfortable with Drush. I would strongly suggest for you to used Drush to update your modules and core. Its just easier and faster. If you decide to give  a try you can update modules and core by running.

drush up -y

If you want to update just the core use drush up drupal -y

You can upload a copy of the latest Drupal version on your production website and then replace sites folder with your dev sites folders. And this would take care of Drupal Core updates.


Custom content entity route or url alias I'm not certain if I'm over-complicating something or just missing something or other.

Essentially, and in addition to a separate admin view of my custom entities, I want to assign a URL to them at the root of the site (i.e. /entity01).

I tried creating a URL property, but getting a route to respond to that is proving challenging. I tried adding a route like:

my_entities.entity_page:
  path: '/{entity_url}'
  defaults:
    _controller: '\Drupal\my_module\Controller\MyController::view'
    _title: 'Hello'
  options:
    parameters:
      entity_url:
        type: entity_url
  requirements:
    _permission: 'access content'

I have a custom a custom parameter converter set up as in:

https://www.drupal.org/docs/8/api/routing-system/implementing-custom-parameter-converters

... and in the convert method, I can use an injected service to load my entity, etc. But in the applies method, I would like to see if it even matches any of my entities and return true or false appropriately, but the applies method doesn't seem to have the value of the URL parameter like the convert method does.

And even if I solve that, the above example only works with a path like:

path: '/my/{entity_url}'

If I remove the /my it doesn't work - I assume because it is conflicting with another route?

Thanks for any help!

I think you can do this with the pathauto (path alias?) module.  Go to the Admin -> Config -> Search / Metadata -> URL Aliases.  In the settings tab, enable your custom entity type.

When you edit them, you should have a URL field added.  You can also use the patterns to define default paths if you want.

I did a quick test with an ECK custom entity and it worked.


How to add a folder to my site with media or media browser? My site uses media browser and media browser plus and when you upload a file you get a drop down of where to upload files. Where can i go to add a directory to this drop down list?

Turns out a a list of vocabularies is being used to generate the drop down. In other words look at taxonomies and find out which one is being used and add a new term vocabulary


ConfirmFormBase to FormBase Drupal 8.7.x

I have a Form button with a confirmation page to delete an ingredient. I'm trying to convert it to a standard Form that just deletes it without confirmation, however I keep getting an error.

Confirmation Form (works just fine) src/Form/DeleteIngredient.php:

 <?php

namespace Drupal\recipe_search\Form;

use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Form\ConfirmFormBase;
use Drupal\Core\Url;

/**
 * Class DeleteIngredient
 *
 * @package Drupal\recipe_search\Form
 */
class DeleteIngredient extends ConfirmFormBase{

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

  public $cid;

  public function getQuestion() {
    return t('Do you want to delete %cid?', array('%cid' => $this->cid));
  }

  public function getCancelUrl() {
    return new Url('recipe_search.recipes');
  }

  public function getDescription() {
    return t('Only do this if you are sure!');
  }
  /**
   * {@inheritdoc}
   */
  public function getConfirmText() {
    return t('Delete it!');
  }
  /**
   * {@inheritdoc}
   */
  public function getCancelText() {
    return t('Cancel');
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state, $cid = NULL) {
    $this->pid = $cid;
    return parent::buildForm($form, $form_state);
  }

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

    $database = \Drupal::database();
    $database->delete('ingredient_list')
      ->condition('pid', $this->pid)
      ->execute();

    $form_state->setRedirect('recipe_search.recipes');

  }

Tried this for normal form without confirmation src/Form/DeleteIngredient.php:

<?php

namespace Drupal\recipe_search\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;

/**
 * Class DeleteIngredient
 *
 * @package Drupal\recipe_search\Form
 */
class DeleteIngredient extends FormBase{

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

  public $cid;

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state, $cid = NULL) {
    $this->pid = $cid;
    return parent::buildForm($form, $form_state);
  }

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

    $database = \Drupal::database();
    $database->delete('ingredient_list')
      ->condition('pid', $this->pid)
      ->execute();

    $form_state->setRedirect('recipe_search.recipes');

  }
}

This is where I return the form to the twig template src/Block/RecipeSearch.php:

//FETCH THE INGREDIENTS TO MAKE AN API CALL
$result = $connection->select('ingredient_list', 'il');
$result->fields('il', array('ingredient', 'pid'));
$result->condition('uid', $uid);
$data = $result->execute();
$results = $data->fetchAll(\PDO::FETCH_OBJ);

foreach ($results as $field) {
  $delete = Url::fromUserInput('/delete/'.$field->pid);

  array_push($ingredients, ["ingredient" => $field->ingredient, "delete" => $delete]);
  array_push($ingredientsArray, $field->ingredient);
};

This is the Error I'm getting:

  Error: Cannot call abstract method
  Drupal\Core\Form\FormInterface::buildForm() in
  Drupal\recipe_search\Form\DeleteIngredient->buildForm() (line 32 of
  /var/www/html/web/modules/custom/recipe_search/src/Form/DeleteIngredient.php)

I guess you cannot use buildForm while extending FormBase but I don't know how I should solve this.

Thanks in advance!

There is no FormBase::buildForm() method. FormBase implements FormStateInterface, and the method FormStateInterface::buildForm() exists. So when you extend FormBase, you must implement buildForm(), however you do not/cannot call parent::buildForm(). Instead, you must build the form array yourself, and return that.

This differs from ConfirmForm which has a buildForm() method, which is why when you extend ConfirmForm you can call parent::buildForm().


private files are no longer private I have created a new content type with an Image field, and I've set it to save in private directory. In my configuration > File System, I have specified /sites/default/files/private as my private directory. File is saving to private directory as well. But when I open that private Image having url structure like /system/files/ in another browser. It shows up, It should not have shown in other browser. How can I make it private?

Drupal should have created an .htaccess file in that directory with Deny from All per the File documentation. Check to see if this is the case. This post may also be helpful: Noob question about private files and Content Access.


Is there a way to re-invoke #ajax on forms when the form itself is returned with ajax? I want to change the delete link on comments so that the delete confirmation is returned with Ajax and then the delete confirmation is executed with Ajax.

I have fixed the form so the delete confirmation at /comment/%cid/delete
so now the submit action is performed with ajax.

Here is the code I used to accomplish this:

function awesomesite_comments_form_comment_confirm_delete_alter(&$form, &$form_state, $form_id) {

  // Add the Ajax Submit Function
  $form['actions']['submit']['#ajax'] = array(
    'callback' => 'awesomesite_comments_ajax_delete',
    'progress' => false,
  );

}

function awesomesite_comments_ajax_delete($form, $form_state) {

  // Get rid of all of the messages that have been set
  drupal_get_messages();

  // Get the comment & node objects
  $comment = $form_state['comment'];

  // Put all of the Ajax Commands into an array
  $commands = array();

  // Place the comment above the form
  $commands[] = ajax_command_remove('#comment-'.$comment->cid.', comment-'.$comment->cid.' + .comment');

  // Return the Ajax Commands Array
  return array('#type' => 'ajax', '#commands' => $commands);

 }

This works perfectly on the delete confirmation page, however, when I return the form with Ajax, the submit no longer is processed with Ajax and a standard page refresh takes place.

Here is the PHP code I have to for delivering the confirmation form via Ajax:

function awesomesite_comments_menu_alter(&$items) {
  $items['comment/%/delete/ajax'] = $items['comment/%/delete'];
  $items['comment/%/delete/ajax']['delivery callback'] = 'ajax_deliver';
  $items['comment/%/delete/ajax']['page callback'] = 'awesomesite_comments_ajax_confirm_delete_page';
}

function awesomesite_comments_ajax_confirm_delete_page($cid) {

  // Get the HTML of the detele page.
  $data = drupal_render(comment_confirm_delete_page($cid));

  // Put all of the Ajax Commands into an array
  $commands = array();

  // Replace the HTML
  $commands[] = ajax_command_html('#comment-'.$cid.' + .comment', $data, array('effect' => 'fade'));

  return array('#type' => 'ajax', '#commands' => $commands);

}

And here is the Javascript I have for taking the "Delete" link on the comments and returning the form (from the callback above)

jQuery('a.ajax-link:not(.ajax-processed)').addClass('ajax-processed').each(function() {

        // Cret the element settings object
        var element_settings = {};

        // Get rid of the progress
        element_settings.progress = { 'type' : 'none' };

        // setup the click elements and add the href
        if (jQuery(this).attr('href')) {
            element_settings.url = jQuery(this).attr('href');
            element_settings.event = 'click';
        }

        element_settings.effect = 'fade';

        // Get the base
        var base = jQuery(this).attr('id');

        // Register the Ajax Request with Drupal
        Drupal.ajax[base] = new Drupal.ajax(base, this, element_settings);

    });

I believe what is happening is that Drupal is processing all the forms on the page for #ajax when the page is loaded, however, since the form is loaded via AJAX it isn't setting up the #ajax information (which I can confirm is present). How can you force Drupal to check for new forms after an Ajax request? Or am I missing something?

any help would be greatly appreciated!

I found the answer!

I simply was asking the wrong question. What I needed to do was re-attach the drupal behaviors with Drupal.attachBehaviors().

I added this code to my JavaScript code.

jQuery('.ajax-processed').once().ajaxSuccess(function() {
    Drupal.attachBehaviors();
});

Voilà! Everything works as it should.


Performance of site when loading 3000+ variables I test all modules (custom + contrib) in one drupal base itself which has resulted in lot of variables.
I was just curious what happens if live site had 3k variables ?
Since all variables will be eventually global variables will it not require huge amount of PHP memory ? or is it not limited at all  ?
What is the alternate here ? cache_get with new cache table instead of variable_get every where

Yes, large variable tables are a problem.

Variables should only be used for small configuration flags and settings and not to store large structures for example.

But given a large amount of modules, dynamic variables like per-content type things you will sooner or later get into trouble.

No, there is no solution to this problem. The variables system will be replaced with the new configuration system from the CMI initiative for Drupal 8 which will hopefully be better at dealing with this.


How to access User Picture field for a comment in Views? I have a Views table with each row showing the node title, node author, and node author picture. I am also adding the last comment title and last comment author to each table row. I would like to add the last comment user picture but that doesn't seem possible from looking at the code.

There is a database table called Node Comment Statistics which Views uses to query the last comment author name and UID.

I would like to somehow use that last comment UID to query the database for the user picture and render it through the theme_user_picture function adding it the View or attaching it someway to the Username with some markup.

Is this possible?

Add a relationship- Comments: User
Add a field- User: Picture (assign Relationship: User)


200 OK on every page after updating the content i have uploaded my localhost site to online, my site was working ok at localhost, but after uploading online whenever im upadating any content it shows me this error message on every page.Please help...

OK
The server encountered an internal error or misconfiguration and was unable to complete your request.

Please contact the server administrator, [no address given] and inform them of the time the error occurred, and anything you might have done that may have caused the error.

More information about this error may be available in the server error log.

HTTP/1.1 200 OK Date: Fri, 25 May 2012 05:40:26 GMT Server: Apache/2.2.22 (Unix) FrontPage/5.0.2.2635 X-Powered-By: PHP/5.3.8 Expires: Sun, 19 Nov 1978 05:00:00 GMT Cache-Control: store, no-cache, must-revalidate, post-check=0, pre-check=0 Last-Modified: Fri, 25 May 2012 05:40:26 GMT Keep-Alive: timeout=5, max=399 Connection: Keep-Alive Transfer-Encoding: chunked Content-Type: text/html; charset=utf-8 5527

I found the solution: Just uncomment the line containing the RewriteBase / directive in the .htaccess file.


How does page.tpl.php come into action? When the line <?php print $page; ?> is encountered in the html.tpl.php template, what happens that make the page template (page.tpl.php) come into action?

It's actually the other way around; it's the theming of the page template that invokes the theming of the html template (as strange as that might sound).

When Drupal goes to serve a normal HTML page (through drupal_deliver_html_page()), it calls drupal_render_page(). To get the basic render array for the page, that function invokes hook_element_info() with the 'page' argument.

The system_element_info() function defines that type like this:

$types['page'] = array(
  '#show_messages' => TRUE,
  '#theme' => 'page',
  '#theme_wrappers' => array('html'),
);

When the drupal_render_page() function eventually gets around to calling drupal_render() on the $page array (once it's been populated with the page content/blocks/etc), theme_page() is called with the $page element as it's 'render element', and the return from that call is passed to the theme wrapper (theme_html()).

It's that return value that populates the $page variable in html.tpl.php


I am trying to enable the jQuery UI module, but I am hitting with error I am trying to enable the Jquery UI module in drupal 7, but I am hitting with error: The jQuery UI plugin is missing. Download and extract it to your jquery_ui module directory. (Currently using jQuery UI Not found)

I downloaded and extracted the plugin from the link into my Jquery_UI folder in sites/all/modules/jquery_ui. still I could not enable the module.

Looks like the module is expecting this structure:

modules/jquery_ui/jquery.ui/(actual jquery ui files)

However, it looks like jQuery UI library removed the version.txt file that this module checks for. If it does not find that text file, it considers the plugin 'not installed' which is kind of a bad check.

People are talking about it here, with a fix for Drupal 6 (and some talk for 7): https://www.drupal.org/node/1954136

However the project page advises you to use jQuery Update instead:

  Drupal 7+ Since Drupal 7 ships with jQuery UI, the jQuery UI module
  has been deprecated and moved to the jQuery Update module.

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

You should dump this module and use jQuery Update and go from there.


Translate module strings In a custom D8 theme, we have some strings in twig using |t filter and in php using $this-t() funtion.

example :

{{'More Headlines'|t}}

$this->t('replies')

These strings are not listed in /admin/config/regional/translate. What's the right way to translate it via the administration interface like it was possible with D7?

You just need to first visit the page rendering the string you want to translate while using any other language.

Drupal only adds this string to the database once it has been rendered once, and you will be able to see it in the /admin/config/regional/translate page.


Creating a drupal-composer/drupal-project gave me an outdated version of core When I ran

composer create-project drupal-composer/drupal-project:8.x-dev mysite --no-interaction

it installed drupal/core:8.8.0-alpha1.  Then to see what was wrong, I ran

composer prohibits drupal/core:8.8.5

and the output was

drupal/core-dev 8.8.0-alpha1 requires drupal/core (self.version)
drupal/core 8.8.5 requires zendframework/zend-diactoros (^1.8)
drupal-composer/drupal-project dev-master does not require  zendframework/zend-diactoros (but 1.7.2 is installed)

What should I do next to get the most recent stable version?
Was I supposed to run composer create-project drupal-composer/drupal=project:8.8.5?

Installed Drupal using this instead: composer create-project Drupal/recommended-project mysite and everything is current and correct.


Uninstalling the module from drupal-7 I had installed module Commerce and it was giving me error whenever I try to display product.Then I went through forums to find out solution. And reason mentioned in forum was commerce module might not installed properly due to maximum execution time.So I decide to uninstall commerce module and  I have done. Also removed it from the sites\all\modules. I have cleared all the caches.

But question is that after removing the module, product(which is part of the commerce module) is still showing up in admin navigation bar at top.

I know it is not coding related question but still any help would be appreciated.

Follow these steps. From these steps I think your query may solved.

Clear caching from the drupal.
Clear caching from the database.
Clear browser caching.

& check. If the menu again shows then
Goto

Admin -> Structure -> Menu -> Management -> list links

& check

Clear Caching from the database (local server)

TRUNCATE TABLE cache;
TRUNCATE TABLE cache_advagg_aggregates;
TRUNCATE TABLE cache_advagg_info;
TRUNCATE TABLE cache_block;
TRUNCATE TABLE cache_bootstrap;
TRUNCATE TABLE cache_field;
TRUNCATE TABLE cache_filter;
TRUNCATE TABLE cache_form;
TRUNCATE TABLE cache_image;
TRUNCATE TABLE cache_menu;
TRUNCATE TABLE cache_page;
TRUNCATE TABLE cache_path;
TRUNCATE TABLE cache_update;
TRUNCATE TABLE cache_views;
TRUNCATE TABLE cache_views_data;


How to know if my XML Sitemap being submitted? I've configured the XML Sitemap and Site verification modules, but I don't see the sitemap being submitted to Google. If I enter the Google Webmaster tools it says no sitemaps were submitted, but maybe it doesn't show those posted via API or something.

How could I know if it's being actually submitted? Thanks.

If you are using Drupal 7, it will show that your sitemaps have been submitted in your log messages at Admin > Reports > Recent Log Messages (/admin/reports/dblog)

Click on "Filter log messages" and select "xmlsitemap"

If you do this, it will show when the last sitemap was generated and when it was submitted the the search engines that you have configured it to submit to (in my case, Google and Bing).


Building a contact form from scratch Is there a way to force Drupal not to base any contact form on the native Personal contact form that comes with it, and thus freely creating contact forms from scratch as done with Webform in Drupal 7?

Here are 2 possible paths. I used the first one:

Path 1:

Stage A:

Go to Structure > Contact forms, and there to "Personal contact form".

Under "Manage fields" delete any custom fields you might have added.
Under "Manage display", make everything as hidden (under both labels && formats).
Optional - Under "Manage form display", make everything hidden.

This will totally hide the native personal contact form.

Stage B:

Create a new form, from scratch; Add desired fields to it under "Manage fields", and under "Manage form display" && "Manage display" hide all automatic fields taken from "Personal contact form".

Link to the new form from a menu, and that's it.

If you are new to Drupal in general and using Drupal 8, check Youtube for video tutorials on how to create basic contact forms and make sure to use the steps above if you want to build your contact-form from scratch.

Path 2

It is best to use the native "Personal contact form" and its native fields that are auto-replicated for other secondary forms if you pursue a minimalist approach, and I, as one who pursue such approach would gladly use it if I could have its fields auto-translated to my sites default language, but without the well known bug in the current Drupal 8 branch (8.1.x) yet to be fixed:

Due to the bug, you can't use the management interface in English and forced to have a XYZ language translated management interface - In some cases it's problematic from at least one reason).

Until this bug will be fixed I personally will use the first path, and might change to path B sometime in the future (in any case its a matter of minutes).

Notes

I suggest creating your block names only as a singular-phrase names, that doesn't contain any non-letter characters.


Clean URLs work*, but not when I submit forms? I have a local dev site configured (Ubuntu 14.04.1 LTS), and I copied a production website to play with there. Everything appears to work great. Clean URLs seem to work and I can navigate the site. It's all wonderful... until I try to login.

When I login at /user, submitting the form returns me to the login as if nothing happened. I was able to login by visiting /?q=user .

After that, if I attempt to clear the cache under performance settings, I get a similar result where the performance page loads as if nothing happened (clearing cache manually via mysql doesn't help). If I disable clean URLs altogether, all is well.

I tried replacing the .htaccess file with Drupal's default to prevent special config issues (no effect). I didn't see anything set as $base_url in settings.php (I'll try setting that to see what happens next).

Any thoughts on why a site with clean URLs enabled seems fine until POST data is involved? Thanks for the feedback in advance!

I think you need to enable Apache's rewrite module using a2enmod rewrite or with sudo if you get permission errors and added the Apache directive AllowOverride All for VirtualHost.


How to merge two different vocabulary in one auto-complete text-field? I have two taxonomies like below:

Content--- editor pick
       --- recommended
       --- today high
Sources--- sky
       --- earth
       --- water

to attach these with blog-post i need to make 2 different auto-complete text-box.
I want to make a single text box and both the taxonomy should be suggested in that.

You can do it using Entity Reference module. You can able to reference multiple vocabulary terms using this module.

See the screenshot of field settings of field type "Entity Reference" and Widget types "Auto-complete (Tags Style)"


How to create link libraries? Is there a way around to build link library repository on a drupal site, so that there can be one place to edit the links and changes will reflect in the instances used else where (like body field of a content type)

Any starting pointers?

I can't answer that exact question, but to solve that problem we typically use the Linkit module.

This will add an additional button to the WYSIWYG for creating links.  When you click it, you get a popup which lets you choose a link (somewhat similar to the entity reference autocomplete widget), and also set link options.

It will then build a link in the markup using a token.  When the page is rendered, the token gets replaced with the path alias for what you selected.  So, if the path for a node changes, the token replacement will take care of fixing everything.


ubercart 2 with smtp - sending unformatted emails Recently I had to switch sending emails to be sent using smtp. https://www.drupal.org/project/smtp
The problem is that all system emails are sent ok regarding formatting. All emails sent by ubercart are unforatted and basically unreadable.
Any idea how is it possible to fix that? Thank you

I tried phpmailer module https://www.drupal.org/project/phpmailer and all messages (even created by ubercart) are displayed as formatted to end users.


Related Products block Hai am working on an ecommerce site using ubercart module. I have created a view for listing products in a particular category. each product direct to a page which consists of its details and add to cart buton. In the bottom of this page i have a related products block which list all the other products in this category.but in this block it repeats the main product once more. how can i remove it? can anyone help me to solve this issue?

You need to add a Contextual Filter field w/c would be the Content: Nid
In contextual filter Content: Nid configuration, under WHEN THE FILTER VALUE IS NOT IN THE URL, use Content ID from URL for the Type.
In contextual filter Content: Nid configuration, scroll down and toggle open the More fieldset and check Exclude


How to change field attributes of Content Entity? In a custom module, I have a content entity in which I have defined this field:

$fields['formheader'] = BaseFieldDefinition::create('string')
  ->setLabel(t('Header'))
  ->setSettings([
    'max_length' => 255,
    'text_processing' => 0,
  ])
  ->setDefaultValue('')
  ->setDisplayOptions('view', [
    'label' => 'above',
    'type' => 'string',
    'weight' => $weight,
  ])
  ->setDisplayOptions('form', [
    'type' => 'string_textfield',
    'weight' => $weight,
  ])
  ->setDisplayConfigurable('form', TRUE)
  ->setDisplayConfigurable('view', TRUE);

I'd like to change its type from string to string_long and max_length from 255 to 1024.
How can I do that without uninstalling my module, changing my source code and installing my module again (there is already content in this entity)?

You don't need to uninstall the module, you can write some update hooks instead.

Since it's not possible to update the field type, you have to manually move the field values to a new field.

First create a new field for the cloned values:

$fields['formheader_clone'] = BaseFieldDefinition::create('string_long')
  ->setLabel(t('Header'))
  ->setSettings([
    'max_length' => 1024,
    'text_processing' => 0,
  ])
  ->setDefaultValue('')
  ->setDisplayOptions('view', [
    'label' => 'above',
    'type' => 'string',
    'weight' => $weight,
  ])
  ->setDisplayOptions('form', [
    'type' => 'string_textfield',
    'weight' => $weight,
  ])
  ->setDisplayConfigurable('form', TRUE)
  ->setDisplayConfigurable('view', TRUE);

Then add this update hook:

function mymodule_update_8000() {
  $entity_definition_update_manager = \Drupal::service('entity.definition_update_manager');

  // Migrate the fields and create the new field.
  $field_definition = BaseFieldDefinition::create('string_long')
    ->setLabel(t('Header'))
    ->setSettings([
      'max_length' => 1024,
      'text_processing' => 0,
    ])
    ->setDefaultValue('')
    ->setDisplayOptions('view', [
      'label' => 'above',
      'type' => 'string',
      'weight' => $weight,
    ])
    ->setDisplayOptions('form', [
      'type' => 'string_textfield',
      'weight' => $weight,
    ])
    ->setDisplayConfigurable('form', TRUE)
    ->setDisplayConfigurable('view', TRUE);
  $entity_definition_update_manager->installFieldStorageDefinition('formheader_clone', 'my_entity', 'my_module', $field_definition);

  drupal_flush_all_caches();

  $entities = \Drupal::entityTypeManager()->getStorage('my_entity')->loadMultiple();
  foreach ($entities as $entity) {
    $entity->formheader_clone->value = $entity->formheader->value;
    $entity->save();
  }

  // Delete the storage definition if it was defined before.
  $storage_definition = $entity_definition_update_manager->getFieldStorageDefinition('formheader', 'my_entity');
  if ($storage_definition) {
    $entity_definition_update_manager->uninstallFieldStorageDefinition($storage_definition);
  }
}

Now run drush updb

Now you have to update the formheader field in your custom entity, this is what it must look like:

$fields['formheader'] = BaseFieldDefinition::create('string_long')
  ->setLabel(t('Header'))
  ->setSettings([
    'max_length' => 1024,
    'text_processing' => 0,
  ])
  ->setDefaultValue('')
  ->setDisplayOptions('view', [
    'label' => 'above',
    'type' => 'string',
    'weight' => $weight,
  ])
  ->setDisplayOptions('form', [
    'type' => 'string_textfield',
    'weight' => $weight,
  ])
  ->setDisplayConfigurable('form', TRUE)
  ->setDisplayConfigurable('view', TRUE);

Now add this update hook:

function mymodule_update_8001() {
  $entity_definition_update_manager = \Drupal::service('entity.definition_update_manager');

  $field_definition = BaseFieldDefinition::create('string_long')
    ->setLabel(t('Header'))
    ->setSettings([
      'max_length' => 1024,
      'text_processing' => 0,
    ])
    ->setDefaultValue('')
    ->setDisplayOptions('view', [
      'label' => 'above',
      'type' => 'string',
      'weight' => $weight,
    ])
    ->setDisplayOptions('form', [
      'type' => 'string_textfield',
      'weight' => $weight,
    ])
    ->setDisplayConfigurable('form', TRUE)
    ->setDisplayConfigurable('view', TRUE);
  $entity_definition_update_manager->installFieldStorageDefinition('formheader', 'my_entity', 'my_module', $field_definition);

  drupal_flush_all_caches();

  $entities = \Drupal::entityTypeManager()->getStorage('my_entity')->loadMultiple();
  foreach ($entities as $entity) {
    $entity->formheader->value = $entity->formheader_clone->value;
    $entity->save();
  }

  // Delete the storage definition if it was defined before.
  $storage_definition = $entity_definition_update_manager->getFieldStorageDefinition('formheader_clone', 'my_entity');
  if ($storage_definition) {
    $entity_definition_update_manager->uninstallFieldStorageDefinition($storage_definition);
  }
}

Now run drush updb again

It's important to do it in the correct order


Private files missing filename I recently upgraded Drupal from version 7.12 to 7.23. After the upgrade, I noticed that when downloading private files, I no longer get the correct filename when I select "Save As" in the browser.

These are the steps I follow:

I upload a file ("testfile.pdf") in a file field for a node
I view the node, right click the file and choose "Save As"
The filename in the download dialog (which should have been "testfile.pdf") now depends on the browser

Chrome: download.pdf
FF: [random string].pdf
IE: [domain name].pdf

I am using private files to be able to restrict access to files. In the release notes for Drupal 7.22, I read that a "Content-Disposition" header was removed from private file downloads.

Could this be the reason that private files no longer retain the filename when downloading?

If server does not provide content-disposition,  especially filename part of it, browser is free to choose suggested name. FF defaults to what appears to some kind of UUID, IE to domain, Chrome bases it's guess on the script being called, as far as I can tell. On the other hand adding content disposition can prevent inline viewing of PDF files, and confuse browsers in a few more ways.

You can use hook_file_download to conditionally add header with a file name where it needs to be added:

  If the user has permission, return an array with the appropriate headers.


How can I moderate user's edits of user profile? I need to create approval for editing a user's profile - I want all revisions to a profile to be subject to moderation.
I have found module called User Revision, but that is not a solution for me as it's only revisioning.
Is this possible with Workbench or something similar?
I am not using Profile 2; and I am working on the newest Drupal 7 version (7.23 at time of writing).

There is drupal module Profile2 Moderation to achieve this. It enables moderation on user profiles.

  A "quite hackish procedure"™ to enable moderation on user profiles but it works


Add epsacrop to programmatically added image field I'm adding an image field to my theme form in order to setup a default image for the user.
I'd like the user to be able to use EPSAcrop to crop the image he uploads here.

Is this possible, if so; How?

This is what I have now:

function MYTHEME_form_system_theme_settings_alter(&$form, &$form_state, $form_id = NULL)  {
  $form['header_images'] = array(
    '#title' => t('Header image'),
    '#type' => 'managed_file',
    '#description' => t('The default header image on every page. Unless a header image is selected in the node of the page.'),
    '#default_value' => variable_get('header_images', ''),
    '#upload_location' => 'public://header_images/',
    '#upload_validators' => array('file_validate_extensions' => array('png, jpg, gif')),
  );
}

I had the same problem. If you change managed_file to media, you will have availability to manage EPSA cropping for the form image.


Can't see User fields as options for a context filter I was following this video to add a contextual filter so the page I'm creating would display content created by the logged-in user only.

However, when I scroll down the list of contextual filters, I don't see the User: options. How can I see them? Am I missing some module or option? My Drupal 7 setup is almost all by default.

The tutorial you're watching is out of date (I watched it too); it was created when Views was in beta/RC and things have changed a bit since then.

You just need to add the user as a Relationship under the "Advanced" options...then you'll get the user filters as you'd expect.


Is there a field tpl for body and/or title fields? I need to add some data- attributes and I am hoping to change it for the body and title fields on article content types. Do the title/body have tpl's that I can modify to add these? Or another method I could try? I've tried adding a field--body--article.tpl.php and it doesn't appear to work.

NOTE: This needs to be done in PHP as the search engine we're using needs it to be done server side.

Title does not use a template, but is rendered directly in page.tpl.php by default.

Display Suite can be used to override this behavior. Many examples available. Here's one for D8, but the principal is the same in D7: https://www.webwash.net/using-display-suite-drupal-8-how-to-use-display-suite-fields/

You may also find using preprocess hooks in template.php to be useful.

https://www.drupal.org/docs/7/theming/overriding-themable-output/setting-up-variables-for-use-in-a-template-preprocess-and

Proprocess hooks give you control over the entire render pipeline, so it's hard to give better guidance without knowing more specifics of your use case.


Wordpress to Drupal: Wordpress Migrate I have a fresh install Drupal 7.34 on WAMP. Token and Pathauto are already installed. The Theme, if it is relevant, is Stanford Open Framework.

I have Wordpress_migrate, migrate, migrate_extras intalled and then included features, media and media_youtube as low level diagnostic.

I follow through the instructions to use wordpress_migrate that seem self-explanatory and get this string of errors

Passing a group object to a migration constructor is now deprecated - pass through the arguments array passed to the leaf class instead.
The DynamicMigration class is no longer necessary and is now deprecated - please derive your migration classes directly from Migration.
The field mapping arguments() method is now deprecated - please use subfield notation instead.
The field mapping arguments() method is now deprecated - please use subfield notation instead.
The field mapping arguments() method is now deprecated - please use subfield notation instead.
No migration found with machine name WordPressAuthor
No migration found with machine name WordPressBlogEntry
No migration found with machine name WordPressPage
No migration found with machine name WordPressAttachment
No migration found with machine name WordPressComment
Passing a group object to a migration constructor is now deprecated - pass through the arguments array passed to the leaf class instead.
The DynamicMigration class is no longer necessary and is now deprecated - please derive your migration classes directly from Migration.
The field mapping arguments() method is now deprecated - please use subfield notation instead.
The field mapping arguments() method is now deprecated - please use subfield notation instead.
The field mapping arguments() method is now deprecated - please use subfield notation instead.

The migration does seem to complete but the list of imports under the blog name is  0  0 0 throughout.

I can see that a partial XML file has been transferred from Wordpress.
I have also tried exporting the Xml file from Wordpress and uploading that. I get the same errors.

The string of red errors suggests the entire module is borked. Is that correct? In which case, what is the best strategy to migrate a Wordpress blog to Drupal.

If the module is not borked then any suggestions what I might have missed or misunderstood?

I clearly do not understand the underlying problem, so please do not bite my head off.  A clear orientation will be received with sincere gratitude though.

The module is pretty borked.

Beebee is right.  When you install using Drush, you will get the latest non-dev Wordpress_migrate and the latest Migrate - clash!  You also get no warning about needing migrate_extras features and media.

So the trick is install the latest Migrate with Drush but as of today's date, download the latest dev version of Wordpress_Migrate.

I was able to download my blog from its url. It did hang and I exited expecting a mess but all the content is there.  As I am trying to sort out content, that suits me.

So the principles --
--download migrate, migrate_extras, media, features and ctools
-- manually download the dev version of wordpress_migrate

If your blog is large, be patient. If the download borks, then try to increase the execution time or try exporting your blog to a file from inside Wordpress, use the Wordpress file splitter and try uploading by file.

Thanks Beebee.


comment pager not showing in bootsrap theme I create a new theme based on Bootsrap and the below template files, I limit  show comment on every page on 50 comment in edit of content type in comment section, I have 126 comment in one of my node form that content type, but only see 50 comment and there is not any pager.

My question is that how can I add comment pager in below of comment?**

comment-wrapper.tpl.php

    <div id="comments" class="<?php print $classes; ?>"<?php print $attributes; ?>>
      <?php if ($content['comments'] && $node->type != 'forum'): ?>
        <?php print render($title_prefix); ?>

<?php print t('Comments'); ?>

        <?php print render($title_suffix); ?>
      <?php endif; ?>

      <?php print render($content['comments']); ?>
      <?php if ($content['comment_form']): ?>

<?php print t('Add new comment'); ?>

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

and    comment.tpl.php

<div class="<?php print $classes; ?> clearfix"<?php print $attributes; ?>>

    <?php print $picture; ?>

        <?php print $author; ?>

        <?php print $created; ?>

        <?php print $permalink; ?>

    <?php if ($new): ?>
      <?php print $new; ?>
    <?php endif; ?>

    <?php print render($title_prefix); ?>
    <h3<?php print $title_attributes; ?>><?php print $title; ?>

    <?php print render($title_suffix); ?>

    <div class="content"<?php print $content_attributes; ?>>
      <?php
        // We hide the comments and links now so that we can render them later.
        hide($content['links']);
        print render($content);
      ?>
      <?php if ($signature): ?>

        <?php print $signature; ?>

      <?php endif; ?>

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

Any idea?

Adapted from this post on putting pagers above and below comments:

function mytemplate_comment_wrapper($content) {
  $comments_per_page = _comment_get_display_setting('comments_per_page');
  $content .= theme('pager', NULL, $comments_per_page, 0);
  return theme_comment_wrapper($content);
}

should render a pager for you if placed in comment-wrapper.tpl.php


Get an Un-submitted/Active Form Field Value in $form_state? I am unsure how to get unsubmitted/active form field values from a number/textfield into $form_state. field_count could be saved as 4, then is changed to 115, how do I pass that change to $form_state before a submit during $form_state->setRebuild(TRUE);?

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

  $config = $this->config('MYMODULE.settings');

  $form['#tree'] = TRUE;

  $form['fieldset'] = [
    '#type' => 'fieldset',
  ];

  $form['fieldset']['field_count'] = [
    '#type' => 'number',
    '#default_value' => $config->get('field_count') ?: 1,
  ];

  // This doesnt get a usable value.
  $form_state->set('field_count_state', $form['fieldset']['field_count']);

  $form['fieldset']['rebuild'] = [
    '#type' => 'submit',
    '#value' => 'Rebuild',
    '#submit' => ['::rebuildFormSubmit'],
  ];

  $form['fieldset'] = [
    '#type' => 'fieldset',
  ];

  for ($i = 0; $i < $config->get('field_count'); $i++) {

    $form['fieldset']['field'][$i] = [
      '#type' => 'textfield',
      '#default_value' => $config->get('field')[$i] ?: '',
    ];

  }

  return parent::buildForm($form, $form_state);

}

/**
 * {@inheritdoc}
 */
public function rebuildFormSubmit(array &$form, FormStateInterface $form_state) {
  $form_state->setRebuild(TRUE);
  // ???.
  $this->messenger()->addMessage($form_state->get('field_count_state'));
}

MYMODULE/src/Form.php:

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

  // get form config.
  $config = $this->config('MYMODULE.settings');

  // Set our count. Used in for loop below.
  if (!empty($form_state->getValue(['fieldset', 'field_count']))) {
    // get $form_state count value.
    $defaultCount = $form_state->getValue(['fieldset', 'field_count']);
  }
  else {
    // Get config count value.
    $defaultCount = $config->get('field_count');
  }

  $form['#tree'] = TRUE;

  // Fieldset item.
  $form['fieldset'] = [
    '#type' => 'fieldset',
    '#prefix' => '
',
    '#suffix' => '
',
  ];

  // Field count item.
  $form['fieldset']['field_count'] = [
    '#type' => 'number',
    '#title' => 'Number',
    '#required' => TRUE,
    '#default_value' => $config->get('field_count') ?: 1,
  ];

  // Rebuild submit item.
  $form['fieldset']['rebuild'] = [
    '#type' => 'submit',
    '#value' => 'Apply number',
    '#submit' => ['::rebuildFormSubmit'],
    '#ajax' => [
      'callback' => '::fieldCallback',
      'wrapper' => 'fieldset-wrapper',
    ],
  ];

  // Loop through our count and create form items.
  for ($i = 0; $i < $defaultCount; $i++) {

    $form['fieldset']['field'][$i] = [
      '#type' => 'textfield',
      '#default_value' => isset($config->get('script')[$i]) ? $config->get('script')[$i] : '',
    ];

  }

  return parent::buildForm($form, $form_state);

}

/**
 * {@inheritdoc}
 */
public function fieldCallback(array &$form, FormStateInterface $form_state) {
  return $form['fieldset'];
}

/**
 * {@inheritdoc}
 */
public function rebuildFormSubmit(array &$form, FormStateInterface $form_state) {
  $form_state->setRebuild(TRUE);
}

This part in the $form['fieldset']['rebuild']:

'#ajax' => [
  'callback' => '::fieldCallback',
  'wrapper' => 'fieldset-wrapper',
],

along with:

/**
 * {@inheritdoc}
 */
public function fieldCallback(array &$form, FormStateInterface $form_state) {
  return $form['fieldset'];
}

Are the ajax options.


Checkboxes in a simple form are not displayed I have a simple form in a custom module that works well and is displaying my select as it should.

$form = \Drupal::formBuilder()->getForm('Drupal\efq\Form\FilterForm');
$form["container"] =  array(
    'categories' => array(
        '#title' => t('Select a Category'),
        '#type' => 'select',
        '#options' =>  array(
            1 => t('Option 1'),
            2 => t('Option 2'),
            3 => t('Option 3'),
        )
    )
);

I would like to change Select for Checkboxes. According to this, "Checkboxes" structure is the same as per "Select".
But when I change '#type' => 'select' for '#type' => 'checkboxes' there are no checkboxes created and I got the 2 following warnings:

Notice: Undefined index: #title_display in Drupal\Core\Render\Element\Checkboxes::preRenderCompositeFormElement() (line 20 of core/lib/Drupal/Core/Render/Element/CompositeFormElementTrait.php).
Notice: Undefined index: #id in Drupal\Core\Render\Element\Checkboxes::preRenderCompositeFormElement() (line 30 of core/lib/Drupal/Core/Render/Element/CompositeFormElementTrait.php).

Adding these in an array makes the notice messages disappear but the checkboxes are still not showing.

Any idea of what's going on ?

You code works for me. I used the exact following code and got checkboxes in my form using Drupal 8.3.4:

$form['container'] = [
  'categories' => [
    '#title' => t('Select a Category'),
    '#type' => 'checkboxes',
    '#options' => [
      1 => t('Option 1'),
      2 => t('Option 2'),
      3 => t('Option 3'),
    ],
  ],
];

return $form;


Trying to install Drupal modules and themes: keep getting error "does not contain any .info.yml files." I am new to Drupal. I am running Drupal 8. I have tried to install three different themes and modules, and keep getting this error:

  does not contain any .info.yml files

Including with the Beale Street module with a 8.x release.

Why am I seeing this error? Are .info.yml files a newish requirement that most themes don't have yet? Where can I get themes that include .info.yml files?

TL;DR you're trying to install a theme or module in Drupal 8, which doesn't contain the required files. You might be trying to install a Drupal 7 (or earlier) module by mistake, or it may not be a Drupal module at all.

The 8.x-dev branch of the Beale Street theme is most definitely not Drupal 8 compatible. It's a straight copy of the current 7.x-dev branch, so it hasn't been converted yet. The maintainer has said as much.

Converting a module/theme from 7.x to 8.x requires a lot more work than just adding a yaml file, and if you don't find one in a particular release you can safely assume it hasn't been converted yet.

There are lists of modules and themes on Drupal.org that are tagged with 8.x. As you've seen, not all of them are ready yet. Bear in mind quite a few will still be in -dev, so they're not expected to be useable.


How to keep Views 2 RSS feed output from stripping out video, embeds, etc.? I've got a basic blog built on Views 2 on a D6 site, with a couple displays built using the views style plugin 'RSS Feed'. Our content team frequently posts various embeds using iframes or flash objects which work fine, except when viewed through an RSS reader where these items (and other basic HTML tags like  or ) are stripped out.

I've already tried creating a separate template for my view from the default template:

  <item>
    <title><?php print $title; ?></title>
    <link><?php print $link; ?></link>
    <description><?php print $description; ?></description>
    <?php print $item_elements; ?>
  </item>

but I'm not able to modify the $description variable or catch it before the input format filter is applied. What is the best way to do this?

Figured this out -- client request was to not eliminate any of the html markup (embeds, videos, emphasis tags, etc.) even though some of the RSS readers would continue to strip it out on their own. I worked through this by creating a views-view-row-rss.tpl.php for my specific view and then adding the following code in:

<?
 $index = $variables["view"]->row_index;
 $nid = $variables["view"]->result[$index]->nid;
 $node = node_load($nid);

 $teaser = check_markup($node->teaser);

 $description = "<![CDATA[".$teaser."]]>";

?>
  <item>
    <title><?php print $title; ?></title>
    <link><?php print $link; ?></link>
    <description><?php print $description; ?></description>
    <?php print $item_elements; ?>
  </item>

Hope this is helpful to someone else, welcome any suggestions on improving this.


Add Javascript with 'id' attribute? I've been asked to add the following to a page :

<script id="dsxc_script" type="text/javascript" src="https://www.docserver1.co.uk/dsxc/client.js?acc=xx&integrated=true"></script>

However I don't think the drupal_add_js() function will allow me to set an 'id' attribute.

How should I proceed ?

drupal_add_js does not support an ID attribute as it seems.
However, as a workaround, you can use drupal_add_html_head to add stuff to the head section.

Ex:

$element = array(
  '#tag' => 'script',
  '#type' => 'html_tag',
  '#attributes' => array(
    'src' => 'https://www.docserver1.co.uk/dsxc/client.js?acc=xx&integrated=true',
    'type' => 'text/javascript',
    'id' => 'dsxc_script',
  ),
);
drupal_add_html_head($element, 'dsxc');

//dpm(drupal_render($element)); Gives the following:
// <script src="https://www.docserver1.co.uk/dsxc/client.js?acc=xx&amp;integrated=true" type="text/javascript" id="dsxc_script" />

You can always embed these scripts in your html.tpl.php file, but if you want to add the stuff conditionally, I think this will work.


Print custom user fields I want to display a custom field, and i've done it with this code

<?php
 global $user;

 $user_fields = user_load($user->uid);

 $customfield = $user_fields->field_navnn['und']['0']['value'];

 print  t("Custom field value is " . $customfield. ' ') ;
?>

but it dosn't show when im logged out.
Thanks

You are using the global variable $user which represents the logged-in user.

  An object representing the user currently visiting the site.

  Contains preferences and other account information for logged-in
  users. When a user is not logged-in, the $user->uid property is set to
  0.

You could use the user id from the URL on the user profile page by calling arg(1).
Here is the possible fix for your code:

<?php
 $uid = arg(1);

 $user_fields = user_load($uid);

 $customfield = $user_fields->field_navnn['und']['0']['value'];

 print  t("Custom field value is " . $customfield. ' ') ;
?>

I do not concern with your user profile template. This is just for your code fix.


How to add a Login / Logout link in Main navigation menu? How can I add a Login link to the "Main navigation" menu?

When a user clicks on the link, it should take them to the /user/login page. Once they login, the link should change to say "Logout" instead of "Login".

Is there any way to add such a link?

We don't need to depend on Bootstrap theme or our programming skills to move system "Log out" link on any other menu. Drupal allows us to make it easily.

Additionally we can just create two custom "Log in me here please" and "Get me out of there" links with /user/login and /user/logout paths relatively. This is better because unlike the system "Log out" link it gives us to create as many log in/out links as we want with custom attributes. As the user logged in they'll see only "Log out" link and vice versa. The only caveat is that you will see probably both links together because you are logged in at the time of testing the links. And this is normal as you have "Link to any page" permission as administrator. Disable this permission and try again.


Get list of available updates I need to be able to easily get a list of available updates for a site.

I've come across the update_get_update_list() function, but that only returns an array of " information about database updates that need to be run, and any updates that are not going to proceed due to missing requirements." I want the list that gets displayed on the admin/modules/update page, but can't seem to find any way to do that through the core update module, and want to avoid using grep on a drush up -n call (as that feels kind of hacky.)

As far as I'm concerned there are three ways you can achieve this:

You can use the Drupal UI /admin/reports/updates
You can use Drush drush ups
You can use a Third Party Service Drupal Status.

I wrote an article that explains how to integrate multiple Drupal website with Drupal Status.


Search index only part of custom content type If I add a search index  display on all my custom types, and set visible only a few columns, those columns will only be included in the search index ?

My problem is that i have columns i don't want to index (like file names), and i don't know how to do it.

The search index is a view mode, but it is hidden by default (for some unknown reason).

Goto the Manage Display page for your content type.  Expand the Custom Display Settings at the bottom.  Tick Search Index and save.

A new tab, Search Index will appear.  Click this, and then configure your content type to show / hide the fields you want indexed.

You may need to dump the search index (admin/config/search/settings) and then reindex the site.  I can't recall if saving the search index does this automatically, of if I normally form alter that form to do it.  The easiest way to do this is with drush:

drush -y search-reindex
drush -y search-index

As a side note, I will be releasing a small module to help debug search issues and check things like this.  I am test driving it on a few sites now, and think it will be ready soon.


How can I construct an HTTPS POST with drupal_http_request? I want to do a post request to an HTTPS server address... I have this example code that demonstrates sending a POST request -

$data = 'name=value&name1=value1';

$options = array(
                'method' => 'POST',
                'data' => $data,
                'timeout' => 15,
                'headers' => array('Content-Type' => 'application/x-www-form-urlencoded'),
        );

$result = drupal_http_request('http://somewhere.com', $options);

and also on drupal_http_request, there is this code -

case 'https':
  // ***************
  // Note: Only works when PHP is compiled with OpenSSL support.
  // ***************
  $port = isset($uri['port']) ? $uri['port'] : 443;
  $socket = 'ssl://' . $uri['host'] . ':' . $port;
  $options['headers']['Host'] = $uri['host'] . ($port != 443 ? ':' . $port : '');
  break;

to demonstrate sending a POST to an HTTPS connection. Problem is, I can't figure out out to implement the HTTPS options in the POST example code above. Can someone please help me and explain how to do this? I'm quite new to PHP code writing and Drupal and could definitely use the guidance. The drupal_http_request documentation are great as an index, but it doesn't help you a lot if you want to learn things from scratch.

edit-

after your comment's, i got to this code -

    $data = 'access_token=455754fhnaI&href=fb&template=You have people waiting to play with you, play now!';

$options = array(
                'method' => 'POST',
                'data' => $data,
                'timeout' => 15,
                'headers' => array('Content-Type' => 'application/x-www-form-urlencoded'),
        );

$result = drupal_http_request('https://graph.facebook.com/1000721/notifications?', $options);

but its still dosen't work... if i post via FIREFOX poster with this patten -

https://graph.facebook.com/1000080521/notifications?
     access_token=45575FpHfhnaI&
     href= fb &
     template=You have people waiting to play with you, play now!

it's working... so i am probably not constructing the request properly in drupal... thanks a lot everyone... really hope someone could help me  figure this out...

You should only need to set it in the protocol.

$result = drupal_http_request('https://somewhere.com', $options);

Parameters

$url:
A string containing a fully qualified URI.

array $options:
(optional) An array that can have one or more of the following elements:

headers: An array containing request headers to send as name/value pairs.
method: A string containing the request method. Defaults to 'GET'.
data: A string containing the request body, formatted as
'param=value&param=value&...'. Defaults to NULL.
max_redirects: An integer representing how many times a redirect
may be followed. Defaults to 3.
timeout: A float representing the maximum number of seconds the function
call may take. The default is 30 seconds. If a timeout occurs, the error
code is set to the HTTP_REQUEST_TIMEOUT constant.
context: A context resource created with stream_context_create().


fresh install drupal using drush I get an access denied on the front page with a fresh install using drush. I can get to the user page fine and login as admin. I read that it might be permissions. Not sure why be default its set like this though. Any thoughts?

Update:

Let me clarify what I need to understand. So previous deployments of drupal using drush I get a fully working site with permissions set correctly. Now I am not sure what is going on wrong but when I run

drush si standard (database info)

I get a freshly installed site with no permissions on the front page. Now I guess what I am trying to understand what is causing this using drush. From what I know and experienced drush si should install the site to a state in which drupal has permissions of anonymous set correct.

I can manipulate the database after deployment but I'd rather not do that if I can make it work with drush right away.

So what could be causing this issue? Am I using drush incorrectly when deploying it?

update:
I think it was a timing issue between mysql and drupal. In any case this is solved.

It may just be your content permissions are not configured.

Go in your admin,  people->permissions->node and look in the "View published Content" permission, make sure anonymous and authenticated user is checked.


Can I add the value of a field in a checkout pane to a completed order email? I would like to add a select list box to a checkout pane in drupal commerce that will allow me to use the selected value as a token to be added to the completed order email?

Typically, you'd alter a form via hook_form_alter() and then sort out through a custom validate / submit handler how to process and save the data so it could be used later. However, I'd recommend something different, because in that approach you'd have to also create a place to store the data and a way to render it in a token, field, Rules data selector etc. yourself.

The easiest way to collect data and use it later in these various scenarios is to use a field. So instead of altering the form directly, I'd figure out how to get a custom field into the checkout form. You have two basic options:

If the data has something to do with customer profile information, like billing or shipping information, simply add the field to the customer profile type and it will appear on the checkout form. I'm not entirely sure how the token system works with respect to the Rules e-mail action, but the data will be there and field tokens will be there to make it happen somehow. Might require further investigation or a module.
If this data is stand alone and you just need it to appear on the form in its own checkout pane, I'd add the field to the order in a fieldgroup and use the Commerce Fieldgroup Panes module to make it into a checkout pane. Then you'd have the field data on your order usable from a token as well.


Drush set block setting only working for one value If I disable the powered by block, and use drush to enable it, the block shows back up again. I use:

root@vagrant-ubuntu-trusty-64:/var/www/drupal# drush config-get
block.block.bootstrap_powered status
'block.block.bootstrap_powered:status': false

root@vagrant-ubuntu-trusty-64:/var/www/drupal# drush config-set
block.block.bootstrap_powered status true
Do you want to update status key in block.block.bootstrap_powered config? (y/n): y
root@vagrant-ubuntu-trusty-64:/var/www/drupal# drush config-get
block.block.bootstrap_powered status
'block.block.bootstrap_powered:status': true

root@vagrant-ubuntu-trusty-64:/var/www/drupal#

However, disabling doesn't work and the block continues to show:

root@vagrant-ubuntu-trusty-64:/var/www/drupal# drush config-set
block.block.bootstrap_powered status false
Do you want to update status key in block.block.bootstrap_powered config? (y/n): y
root@vagrant-ubuntu-trusty-64:/var/www/drupal# drush config-get
block.block.bootstrap_powered status
'block.block.bootstrap_powered:status': true

root@vagrant-ubuntu-trusty-64:/var/www/drupal#

Thoughts on what I'm doing wrong here? Using Drupal 8.

Ended up having to use:

drush config-set block.block.bootstrap_powered status --value=''


Rebuild features on cache clear I have a distro with many preinstalled features (Panopoly).

Since I have upgraded core to 7.24 I can see an additional setting at admin/structure/features/settings, see attachment.

On production, is it best to disable the "Rebuild features on cache clear"? This is active by default.

Yes, it is best to disable this in production for the performance reasons mentioned.

I think the only times you would want to rebuild the feature list is when you are using the features and/or modules lists (as designed). Spending the resources to reload that when clearing cache for themeing purposes would be unnecessary.


Does the #cache property for render arrays cache content from a query when used in a controller? I have a custom page displaying a query result from the database. Before I attempt to cache it myself, I am trying to see if Drupal 8 render arrays support caching in anyway for authenticated users. My use case is a route and a controller on the node entity. Users go to node/id/something that displays a list of entries in a table. I would like to cache this in the controller.

I am using the following code.

public function displayContent(NodeInterface $node) {
  // query the DB to generate content.
   $content['#markup'] = $result_of_db_query;

    $content['#cache'] = [
      'keys' => ['entity_view', 'node', $node->id()],
      'tags' => ['node:' . $node->id()],
      'max-age' => Cache::PERMANENT,
    ];
    return $content;
}

It doesn't work: The database query is executed on every page request.
I am not sure if this is due to the fact this page is an administrative page and users must be authenticated.

Now that the topic is open again I will try to answer the questions:

  Does the #cache property for render arrays cache content from a query
  when used in a controller?

Yes, it does. The cache metadata will be used to cache the render array if you set cache keys and the metadata bubbles up to page level.

  The database query is executed on every page request. I am not sure if
  this is due to the fact this page is an administrative page and users
  must be authenticated.

On page level this is true, as for now it is presumed that admin pages are not cacheable, see Change Dynamic Page Cache's response policy from "deny admin routes" to "deny html admin routes"

  I expect the content to be cached and the query that generate the
  result to not run on every page request.

See the comments from @Berdir and this blog post how to do this by moving the query to a #pre_render callback:

https://dev.acquia.com/blog/drupal-8-performance-render-caching


Composer Not Getting Latest Version of Module I am one of the maintainers of Bootstrap Paragraphs. The module is currently set as the 2.0 branch to be the default and the 1.0 branch is set to unsupported.  The 1.0 had a Beta Release but the 2.0 is currently in Alpha.

When I run composer require drupal/bootstrap_paragraphs composer downloads the 1.0 release ("drupal/bootstrap_paragraphs": "^1.0@beta",) instead of the 2.0 release.

What do we have to do to make the 2.0 branch be downloaded when running composer require drupal/bootstrap_paragraph.  Want to avoid as many people as possible from using the 1.0 branch.

Composer does not default to the "latest" it defaults to the "Most stable" when there isnt a stable release. In this case 1.0-beta1 is "more stable" than 2.0-alpha1.


Pathauto and forum paths I can generate urls to forum topics fine, but pathauto appears to be stubbornly refusing to generate urls for Forums and containers no matter what patterns I try to use.

I even tried to alias them in core alias - as suggested for Drupal 7 here -  but aside from the fact that the pages then returned 404 results I will probably have users adding forums in the future so really need to be in a position to generate them.

I want my forum urls to be of the form /private/discussion/forum-name and I would like to be able to have my container point to /private/discussion and see a list of the available forums there. Or at least alias the main forum output page.

I believe this is due to the issue reported here: https://www.drupal.org/project/drupal/issues/2010132. See the patch in comment #107 for a patch.

I've confirmed that the patch applies to the current Drupal 8.4 branch, the tests pass, and the aliases get generated as expected.


how do I add extra classes to a date field at views? I am using Drupal 7. I created a view, that is using a date field. I would like to create extra classes to the date field for that specific view.

For example,

 10
 June
 2011
  8:00

Now I have a code:

 10 June 2011, 8:00

How can I do it step by step?

You can do this without any additional modules.

Add the date field. Exclude this from the display.  Choose custom, and write d in the box (as in php date for the day).  Change the 'Style Settings' - Customize field HMTL (set to none) and  Customize field and label wrapper HTML (set to none).
Add the date field again.  Exclude this also from the display. Choose custom, and write M in the box (as in php date for the month).  Change the 'Style Settings' - Customize field HMTL (set to none) and  Customize field and label wrapper HTML (set to none).
Add the date field again. Exclude this also from the display.  Choose custom, and write Y in the box (as in php date for the year). Change the 'Style Settings' - Customize field HMTL (set to none) and  Customize field and label wrapper HTML (set to none).
Add the date field again (LAST TIME!).  DO NOT EXCLUDE THIS FROM THE DISPLAY. Choose custom, and write G:i (as in php date for the hours and minutes). Change the 'Style Settings' - Customize field HMTL (set to none) and  Customize field and label wrapper HTML (set to none).
Rewrite the results of this final date field.  Using the replacement patterns, you can then write something like this:

    [created]

    [created_1]

    [created_2]


How to get language prefix in Drupal 8 I am building internal in my custom module that I am porting to Drupal 8:
https://www.drupal.org/project/taxonomy_facets

I need to get a current language prefix so I can prepend it to the link. I Drupal 7 it was as simple as:

global $language;
$prefix = $language->prefix;
$mylink = $prefix . '/example/something';

How can do this in Drupal 8?

EDIT: My issue specifically is that I have a language prefix set to NONE for the default language at Home >> Administration >> Configuration >> Regional and language >> Languages >> Detection and selection. (admin/config/regional/language/detection/url)

For the default language, I want the code to return the real prefix, i. e. NONE, not en (the code for the default language, English).

In Drupal 8, you use the languageManager class to get the language code:

$languagecode = \Drupal::languageManager()->getCurrentLanguage()->getId();

EDIT: If you want to return NONE if the current language is the default language, you probably need to make a helper function:

$languagecode = \Drupal::languageManager()->getCurrentLanguage()->getId();
$default_languagecode = \Drupal::languageManager()->getDefaultLanguage()->getId();
if ($languagecode == $default_languagecode) {
  return "NONE";
}
else {
  return $languagecode;
}

helper function to ge it from settings

function getLanguagePrefix() {
    if($prefixes = \Drupal::config('language.negotiation')->get('url.prefixes')) {
      $language = \Drupal::languageManager()->getCurrentLanguage()->getId();
      return "/". $prefixes[$language];
    }
    return null;
  }


How do I find out the machine name of a view in hook_preprocess_views_view_field? In Drupal 8, I am trying to use hook_preprocess_views_view_fields to process certain fields of certain views. I know how to test for the field name via $variables['field']->field, but I can't find any similar way to test for the view's machine name. Is there a similar way to do it for the view?

The view itself is in the $variables array for all of the views hooks.

/** @var \Drupal\views\ViewExecutable $view */
$view = $variables['view'];
$view->id();

should give you what you are looking for.


How to start view chart on last page I am using the Charts module and Google Charts API with Views. I want my view to display with the last page of the view showing on page load. How can this be accomplished? For more explanation of what I'm trying to do: I have a view displaying a line chart with historical data, but I want the view to load with the most recent data first and the pager to allow the user to go back (using previous button) to view data in the past.

Thanks in advance.

Not familiar with charts, but in views SORT you could try using the opposite.

Ex: Sort Descending instead of Ascending. (so it reverses the order).

Then all you would have to do is override the pager so it says previous instead of next. I found some documentation here.


One view for multiple pages I have nodes from a content type that are put in a paged view (show 1/page)
You can see it here:
http://stage.e-clear.eu/en/chemicali%C3%ABn
http://stage.e-clear.eu/en/Energie
As you see this are multiple views for multiple pages (in example chemicals and energy)

I want a view that creates multiple pages like a published filter but invisible with nice url's like /energy.

I know what you're trying to do with Views, and it's easier than you think once you get comfortable with Views Contextual Filters.

Check out this video (or the text version article) that clearly walks through how to use Drupal Views Contextual Filters. The linked examples use Pets (Dogs, Cats) as sample data, so you'll see how to filter Cats versus Dogs quickly.

VIDEO: https://www.youtube.com/watch?v=lJFMTDuaxy8 (YouTube video short-url: lJFMTDuaxy8)

ARTICLE: http://www.metaltoad.com/blog/using-drupal-contextual-filters-views


How to skip the description step when uploading a file for a specific field? in the media module's settings, there's a checkbox called "Skip available fields" that lets you skip filling out fields that are attached to your media when you add one.

In some cases, we need to let users enter a description for files that are uploaded and in other cases, no.

Does anybody know how to skip the available fields for a specific field of a specific content type ?  What kind of code or hook implementation is required, etc. ...

Thanks !

You could probably acheive that by implementing

hook_field_attach_form

and setting the required values (e.g #required => TRUE or unsetting the description element.).

The entity_type and entity values are available for conditionally showing / hiding data there.


Create taxonomy reference field programatically in Drupal 8 How to create taxonomy reference field programatically in a custom form?

$tags = array();// get taxonomy terms from a vocabulary.

$form['custom_tags'] = array(
  '#type' => 'select',
  '#options' => $tags,
  '#title' => $this->t('Preffered Tags'),
  '#default_value' => $this->store->get('custom_tags') ? $this->store->get('custom_tags') : '',
);

How can I get taxonomy terms from a vocabulary? Or how to create a term reference field in custom form?

I did it by following method. If any other better way to achieve this, please suggest.

$tag_terms = \Drupal::entityManager()->getStorage('taxonomy_term')->loadTree('tags');
$tags = array();
foreach ($tag_terms as $tag_term) {
    $tags[$tag_term->tid] = $tag_term->name;
}

$form['custom_tags'] = array(
  '#type' => 'select',
  '#options' => $tags,
  '#title' => $this->t('Preffered Tags'),
  '#default_value' => $this->store->get('custom_tags') ? $this->store->get('custom_tags') : '',
);


Cannot read nodes containing an email address $email = "example@addresss.com";

    if (valid_email_address($email)) {
      $query = new EntityFieldQuery();
      $query->entityCondition('entity_type', 'node')
        ->entityCondition('bundle', 'my_content_type')
        //->fieldCondition('field_user_email_address', "email", $email)
        ->propertyCondition('status', 1);

      $result = $query->execute();
      dpm($result,"result");
      if (!empty($result['node'])) {
        $nids = array_keys($result['node']);
        $nodes = node_load_multiple($nids);

        foreach ($nodes as $node) {
          dpm($node,$node->title);
        }
      }
    }

The problem I have is with the fieldCondition (commented out above).  When it's commented out, the $result returns all of the matching nodes, as expected.  Looking at the second dpm output I can see results for "example@addresss.com" in $var->field_user_email_address[LANGUAGE_NONE][0]['email'] = "example@addresss.com".

However, when the fieldCondition is included in the search, it always returns zero results.   i.e. $result is an empty array

I'm not sure why you're having trouble with the bundle condition, but as an alternative you could use a propertyCondition and query on the node type instead:

$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
  ->propertyCondition('type', 'my_content_type')
  ->fieldCondition('field_user_email_address', "email", $email)
  ->propertyCondition('status', 1);


Rewrite SQL on a specific content type node on Drupal 7 I'm trying to rewrite SQL on a specific node type on Drupal 7. I found this, But it only works on Drupal 6-. What's about Drupal 7? Thank you.

https://api.drupal.org/api/drupal/includes%21database.inc/function/db_rewrite_sql/6

While the question is vague as to your purpose, you may be interested in

hook_query_alter
hook_query_TAG_alter

to alter queries in Drupal 7.


How do I display taxonomy content from taxonomy category? I have fields in taxonomy under category taxonomy. Attempted views but couldn't find taxonomy fields to add as fields :(

Do not want node fields.

What I did is:
1. Create taxonomy, category
2. Add terms, dog, cat, etc
3. Add fields such as image, description, etc

So on view, all terms under category taxonomies appear in a view with description, images and more.

How do I display all taxonomy terms' content under category?

Updated

Vocabulary: Categories
Taxonomy: Body Contouring for example.
Inside, it has the description and image.

So wanted to list taxonomies with their details in grid layout. Attempted views, but it is only all content type related to taxonomies' id.

I only need content from taxonomies. How do I display taxonomies' content?

Not sure of your full requirements as it is a bit confusing but it sounds like you are trying to output all the fields of a specific Taxonomy.

If you are using Drupal 7, just create a view of 'Show' Taxonomy Terms.

Then from there add the taxonomy fields that you require by searching from the 'add field' dropdown.

Finally create a filter for taxonomy term 'category'.

Hopefully that is what you are after.

Do you not see this filter when creating your view. What version of Drupal are you using?


Add class to all labels in a comment form Pretty straight forward.  For every label within a comment form, I wish to add a particular class to it.  Using only functions in template.php, in Drupal 7, how can this be done?  If it can't be done this way, what is the most straight-forward alternative?

Can't come up with a cleaner solution than implementing theme_form_element_label and adding the classes there depending on the elements name (comment_body) etc.

Maybe an option is to implement hook_form_comment_form_alter() and add specific identifiers to the elements you want to change the css class for the labels on in theme_form_element_label().


Disable payment if Drupal Commerce Order Balance Total is <250 I am trying to disable a payment option if the order balance total is over $250. I currently have the following, but it throws an error as there is nothing to drill down into after "order-total:"

Actually the correct condition is called: Price Comparison and not Balance total

see here:


Set entity reference revision field value? How do I set entity reference revision value for a field? I have two fields, field_test_entity_reference and field_test_entity_revision. field_test_entity_reference is of field type entity reference and field_test_entity_revision is of type entity reference revision. Both are referring to the same content type. I have created a node of this content type and its id is 7747. I am trying the below code and it sets value correctly for the field which is of type entity reference but not for entity revision version.

$node-field_test_entity_reference->target_id=7747;
$node-field_test_entity_revision->target_id=7747;
$node->save();

You need to store also the revision id, see Programmatically append multiple paragraphs to entity reference field on node.

Or simply set an entity, from which the field can get the data it needs in both cases:

$node->field_test_entity_reference->entity = $target_node;
$node->field_test_entity_revision->entity = $target_node;
$node->save();