Delete/ Deactivate account in a separate block I want the authenticated users on my site to be able to delete their own account or temporarily block/de-active. I give the necessary permissions for this. Well and good for now. However, the tricky part is that i want these as separate forms in a page different that user edit. Something like shown in the image below: So that when the user navigates to this page say node/100 then the above is displayed. Any suggestions how to achieve this.

Regards

What you are describing will require a custom module that will provide the non standard functionality.

You will need to provide hooks for blocks (hook_block_info and hook_block_view) producing forms using the FAPI to produce the forms as you are showing in your mock.

Deleting an account would require using form validation to test that the username and password is correct and matches the content that you are viewing as well matches the user that is logged in. Once validated you would call the user_delete function, however be aware that this will delete all content owned by the user.

Disabling or Deactivating account will require a hook_block_info and hook_block_view  as well the form using the FAPI as well a subset of the  validation mentioned above, then calling the user_cancel function passing in the appropriate arguments.

The forms could be rendered using...
1. the blocks ui with conditional visibility settings.
2. at the theme level using a preprocess_page hook in template.php
3. other...

As Drupal is like a swiss army knife and this is one of many ways to solve the issue.

You can the try the following Drupal plugin and use the permissions within drupal admin page to set it so users can select functions on if they want to delete their account.

http://drupal.org/project/user_delete

It allows you to do the following:

block a user
block a user and unpublish all submitted content, including nodes and comments
delete a user and reassign the submitted content to the anonymous user
delete a user and delete all submitted content including nodes and comments

Also have a read of the following: http://groups.drupal.org/node/252233


How do I configure the REST API? A couple months back I successfully setup a development site to learn about the Drupal 8 REST API with version 8.0.x using the REST UI module for configuration. When I heard about the improvements to the REST Services in Drupal 8.2 I was pretty excited (from my understanding it is now possible to access configuration data such as content types and taxonomy terms) so I setup a new install using version 8.2.1. However, understanding the configuration for 8.2 is pretty daunting, and since it's so new there are very little resources around the setup and configuration.

I was able to locate this resource and I imported the example configuration provided, but was still unsure on how to configure other REST Endpoints.

I used the default configuration provided in the above resource. It looks like this:

langcode: en
status: true
dependencies:
 module:
   - basic_auth
   - hal
   - node
id: entity.node
plugin_id: 'entity:node'
granularity: resource
configuration:
 methods:
   - GET
   - POST
   - PATCH
   - DELETE
 formats:
   - hal_json
 authentication:
   - basic_auth

How do I edit the configuration once it's imported via the configuration manager?
Where can I find the available plugin_id's so that I can configure other resources? Where can I learn more about plugins?
How would I begin to implement my own REST endpoint?

I know this is a lot to ask, but at the time of writing there is little to no information covering these topics so I figure other people might be confused as well. I would like to create a guide on this, but that would first require that I understand it first.

I search a lot too after 8.2x and this is how i got it working :

Example for a custom user ressource :

  myModule/config/install

  rest.resource.user.rest_ressource.yml

langcode: en
status: true
dependencies:
  module:
    - basic_auth
id: user.rest_ressource
plugin_id: 'user_rest_ressource'
granularity: resource
configuration:
  methods:
    - GET
  formats:
    - json
  authentication:
    - basic_auth

  In myModule/src/Plugin/rest/resource

  UserRestRessource.php

<?php

namespace Drupal\myModule\Plugin\rest\resource;

use Drupal\Core\Session\AccountProxyInterface;
use Drupal\rest\Plugin\ResourceBase;
use Drupal\rest\ResourceResponse;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Psr\Log\LoggerInterface;

/**
 * Provides a resource to get view modes by entity and bundle.
 *
 * @RestResource(
 *   id = "user_rest_ressource",
 *   label = @Translation("User Rest"),
 *   uri_paths = {
 *     "canonical" = "/api/user/getInfo"
 *   }
 * )
 */
class UserRestRessource extends ResourceBase {

  /**
   * A current user instance.
   *
   * @var \Drupal\Core\Session\AccountProxyInterface
   */
  protected $currentUser;

  /**
   * Constructs a Drupal\rest\Plugin\ResourceBase object.
   *
   * @param array $configuration
   *   A configuration array containing information about the plugin instance.
   * @param string $plugin_id
   *   The plugin_id for the plugin instance.
   * @param mixed $plugin_definition
   *   The plugin implementation definition.
   * @param array $serializer_formats
   *   The available serialization formats.
   * @param \Psr\Log\LoggerInterface $logger
   *   A logger instance.
   * @param \Drupal\Core\Session\AccountProxyInterface $current_user
   *   A current user instance.
   */
  public function __construct(
    array $configuration,
    $plugin_id,
    $plugin_definition,
    array $serializer_formats,
    LoggerInterface $logger,
    AccountProxyInterface $current_user) {
    parent::__construct($configuration, $plugin_id, $plugin_definition, $serializer_formats, $logger);

    $this->currentUser = $current_user;

  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static(
      $configuration,
      $plugin_id,
      $plugin_definition,
      $container->getParameter('serializer.formats'),
      $container->get('logger.factory')->get('restimadiff'),
      $container->get('current_user')
    );
  }

  /**
   * Responds to GET requests.
   *
   *
   *
   * @throws \Symfony\Component\HttpKernel\Exception\HttpException
   *   Throws exception expected.
   */
  public function get() {

      $responseResource=new ResourceResponse(
          array()

      );
    return $responseResource;
  }

}

Since posting this, the documentation on drupal.org/docs/8/ has been updated appropriately.


How can I manually send order details email to customer in Ubercart? I have a cron job to read orders from the Ubercart database table, and manually send the order email to the customer.

Usually, when customers checkout in Ubercart, they will get their order email straight away. But in my situation we don't want to automatically send the order to customer because we have some process that needs to be completed before we programmatically send the order email to customers.

How can I manually send the customer's order email in Ubercart?

You can try hook_cron in a custom module and get all orders using uc_order_status_list the return value may contain the email address of the buyer. If not get the order id, use uc_order_load to load the order. Get the email of buyer.

And you're done.

Yes, you can. In the Ubercart store administration section go to orders and you can see your orders there then select the order you want to email and go to invoice and there is the option to email the order:


How to hide an exposed filter block if the view results are empty? I have an exposed filter block on the sidebar on my page. I want to hide the exposed filter block if the result of the view is empty. What is the best was to do it ?
Right now i am having some Jquery code in a no result behaviour textfield wich hides some block elements. But i dont like this solution. I prefer if the code is clean and the html code is completely removed.

@pierre's answer is a good one, however $view->total_rows is not always populated.

So you could do something like this instead, which will work no matter what:

function MODULE_views_pre_render(&$view) {
  if ($view->name == 'VIEW_NAME' && $view->current_display == 'DISPLAY_NAME') {
    if (empty($view->result) && empty($view->getExposedInput())) {
      $view->exposed_widgets = NULL;
    }
  }
}

Go to the advanced tab of you view
Add contextual filters
Select Global: Null
When the filter value is NOT available: Select 'Hide view'


Why doesn't my form submission handler work? I am new to drupal and require help from Gurus.

I am adding some form elements in the status share form by using hook_form_alter(). These elements are getting displayed in the form, but my submission handler is not working. I am using $form['#submit'][] = 'my_module_form_submit'; to add it to the form.

function my_module_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == "statuses_box") {
    $form['tech2'] = array(
      '#type'=>'select',
      '#title' => '',
      '#attributes' => array('class' => array('tech2')),
      '#options' => array('All'=>'All','New'=>'New',),
      '#multiple' => false,
    );

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

function my_module_form_submit($form, &$form_state) {
  // Do something here.
}

The issue I am getting is my_module_form_submit is not getting called. The debugger break-point is not getting hit in this function
I am not getting error message neither on page nor in admin/reports/dblog
What I want is to add a new row in my custom data table, which this code is supposed to create.
Default form handling is running perfectly.

Check your form id. I doubt your form id is not correct. Even you can try this also -

function my_module_form_submit($form, &$form_state) {
  // Do something here.
  echo "<pre>";
  print_r($form);
  exit;
}


Image field is not showing up in view/block I am currently using Drupal 7, and I am trying to get my images to be displayed in a view on the main page. So far I have created:

Created a content type containing a title, body and image field
Created two nodes that both contain an uploaded image
A view and a block that has

fields: title, nid, and image
filtered by: published and type (set to the content type I created)

When I look at my content type I can see the name, body and the image that I uploaded. When I go to the main page, I can see my view with the content, but it only shows the name and the body; it doesn't show the image.

Is there anything I can download and/or do to make this work? I just want the images to appear within the block (in my view).

check admin/user/permissions page. if you use imagecache check view imagecache permission and set it. and set view image field permission.

When you create a node, below the body field there is the "Text format" combobox; choose "Full HTML," and everything will be ok.


Use a database specific function in dbtng (e.g. uuid in db_insert) I have a table that contains a char(36) field for a uuid. It seems like I can insert data into that field with a mysql query like: INSERT INTO mytable (uid, event_guid) VALUES (1, uuid());. I'd like to make a query like that in DBTNG syntax, but I believe I will just insert the string "uuid()" into the column.

db_insert('mytable')
  ->fields(array('uid' => $uid, 'event_guid' => 'uuid()'))
  ->execute();

So...do I just use db_query? Is there some magic in dbtng to handle this?

Here's what I ultimately did:

db_query("INSERT INTO {mytable} (uid, event_guid) VALUES (:uid, uuid())",
array(':uid' => $uid));

And that works to use the mysql uuid() function in an insert.

I've created an issue to add this to Drupal 8 http://drupal.org/node/1858188

You can use function calls in the fields array.  The following code should just work:

db_insert('mytable')
  ->fields(array('uid' => $uid, 'event_guid' => uuid()))
  ->execute();

If you wanted to insert multiple entries in a loop something like this would work:

$event_guid = uuid();
foreach($entries as $entry) {
  $entry['event_guid'] = $event_guid;
  db_insert('mytable')
    ->fields($entry)
    ->execute();
}


First attempt to adding states to a custom Content type // sample code
/**
 * Implementation of hook_form_FORM_ID_alter()
 */
function demo_form_sport_node_form_alter(&$form, &$form_state, $form_id) {
    $form['field_winter_sports'] = array(
    '#states' => array(
        'visible' => array(   // action to take.
            ':input[name=field_season]' => array('value' => t('winter')),
        ),
    ),
);

}

i am trying to alter a form from a "sport" node type. my "sport" node type has 2 fields.

field_season List (text)    Check boxes/radio buttons
field_winter_sports List (text) Check boxes/radio buttons

there are two options in field_season, summer or winter.

if someone selects winter in field_season, i want to make field_winter_sports visible, otherwise remain hidden.

with my current code, when i select winter right now, nothing happens.

There are two things to consider:

The name of the input element is visible in the HTML output of the page, and that could not match with the ID used for that form element from the form API. That happens with form elements created with the field API too.
I created a field_season field, which allows just a value to be select (which means it is rendered with radio buttons); the input element name that appears in the HTML output, which is the one jQuery sees, is field_season[und], not field_season.

If I change the field to allow three choices (which means the form field is rendered as checkboxes), the input element name changes to field_season[und][1], field_season[und][2], and field_season[und][3].

When you want to tell to Drupal to alter the state of a form element when a radio buttons are used, you should not use t(), and the string to use as value in the state is not the string that appears to the users, but the value assigned to the value attribute of the <input type="radio"> tag. For example, for the form element added from the following code, those values are 0, 1, and 2.

$form['registration_cancellation']['user_register'] = array(
  '#type' => 'radios',
  '#title' => t('Who can register accounts?'),
  '#default_value' => variable_get('user_register', USER_REGISTER_VISITORS_ADMINISTRATIVE_APPROVAL),
  '#options' => array(
    USER_REGISTER_ADMINISTRATORS_ONLY => t('Administrators only'),
    USER_REGISTER_VISITORS => t('Visitors'),
    USER_REGISTER_VISITORS_ADMINISTRATIVE_APPROVAL => t('Visitors, but administrator approval is required'),
  ),
);

Since the input element name contains und, which is the string value for the LANGUAGE_NONE constant, I suspect the input element name could change basing on the language associated with the field, even if I suspect it would always be und, for radio buttons and checkboxes.

As side note, learningxm is correct when it says that you should use `:input[name=""]' since that is what the example in the drupal_process_states() page shows.

$form['toggle_me'] = array(
  '#type' => 'checkbox',
  '#title' => t('Tick this box to type'),
);
$form['settings'] = array(
  '#type' => 'textfield',
  '#states' => array(
    // Only show this field when the 'toggle_me' checkbox is enabled.
    'visible' => array(
      ':input[name="toggle_me"]' => array('checked' => TRUE),
    ),
  ),
);

As noted by Clive, you are overriding the form element added using the field API; to change the states associated with the form element, you should just use the following code.

$form['field_winter_sports']['#states'] = array(/** Add here your states. **/);

I assume field_winter_sports is the correct form element ID.

I would also investigate using hook_field_widget_form_alter(), which is the hook thought to alter the form elements used for a field.

change  ':input[name=field_season]' => array('value' => t('winter')),

add commas "" to field_season like this:

':input[name="field_season"]' => array('value' => t('winter')),


Why am I getting undefined is not a function when using jquery? HTML

more code here...

<script type="text/javascript" src="//code.jquery.com/jquery-1.10.2.min.js"></script>
<script type="text/javascript" src="https://example.com/sites/all/modules/ac_modules/ac_exercise/ac_exercise.js?nkuo2r"></script>

more code here...

<div class="form-item form-type-textfield form-item-time-start">
  <label for="edit-time-start">Time Start </label>
 <input type="text" id="edit-time-start" name="time_start" value="11:28:12" size="4" maxlength="8" class="form-text" />
</div>

more code here...

Javascript - ac_exercise.js

$(document).ready(function(){
  $("#edit-time-start").on("change paste keyup", function() {
     alert($(this).val());
  });
});

In Chrome's console I get the following error:
Uncaught TypeError: undefined is not a function - ac_exercise.js?nkuo2r:1 which is this line of code:

$(document).ready(function(){

(function ($) {
  $(document).ready(function(){

  your code here

  });
})(jQuery);

Please check your current JQuery library may not have any conflicts.

However, you can use the JQUERY at the bottom. Please refer this article


Custom page template for content pages Is there any way to make a custom page.html.twig template in Drupal 8?

By default, Drupal generates some suggestions, but I'm looking for something like page--node--content-type.html.twig.

You are looking for hook_theme_suggestions_HOOK_alter().

HOOK is the name of the template, in your case, page. You should be able to add the following to your theme in the .theme file.

In there, do something like this:

function yourtheme_theme_suggestions_page_alter(array &$suggestions, array $variables) {
  if ($node = \Drupal::routeMatch()->getParameter('node')) {
    $suggestions[] = 'page__node__' . $node->getType();
  }
}

It's like:

node--[content-type].html.twig ex: node--article.html.twig
node--[content-type]--[display-format].html.twig, ex: node--article--full.html.twig

Here the screenshot of template suggestion:


How to set the default "Show as expanded" to true in a custom menu item I am creating a series of menus in a custom module. This site also has a custom theme. Is there a way in the theme, or in the module, to set a menus "Show as expanded" to true. This way, if I move my site, uninstall, or whatever, it comes back the way it should right out of the box.

I couldn't find it anywhere on the Drupal documentation, but adding

expanded: TRUE

in the module.links.menu.yml file works.

According to Drupal API for hook_menu:

  "expanded": Optional. If set to TRUE, and if a menu link is provided for this menu item (as a result of other properties), then the menu link is always expanded, equivalent to its 'always expanded' checkbox being set in the UI.

So while writing your custom hook simply add expanded option.

$items['examples/page_example'] = array(
    'title' => 'Page Example',
    'page callback' => 'page_example_description',
    'access callback' => TRUE,
    'expanded' => TRUE,
  );


How to unpublish nodes which are missing in migration source? I have a CSV file with two rows. I executed the migration and two nodes are imported.
Now I deleted one row from the CSV and execute the migration again.
I now want to unpublish the node which is missing in the CSV.
Is it possible? How will I do that?

I have used an EventSubscriber for this. Here is my code.
/**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents() {
    $events = [];
    $events[MigrateEvents::PRE_IMPORT][] = ['archiveMissingNodes'];

    return $events;
  }

  /**
   * Archives the missing contact persons.
   *
   * @param \Drupal\migrate\Event\MigrateImportEvent $event
   *   The migration import event.
   *
   * @throws \Drupal\Core\Entity\EntityStorageException
   */
  public function archiveMissingNodes(MigrateImportEvent $event) {
    $migration = $event->getMigration();

    if ($migration->id() === 'my_migration_id') {
      $id_map = $migration->getIdMap();
      $id_map->prepareUpdate();

      // Clone so that any generators aren't initialized prematurely.
      $source = clone $migration->getSourcePlugin();
      $source->rewind();
      $source_id_values = [];

      while ($source->valid()) {
        $source_id_values[] = $source->current()->getSourceIdValues();
        $source->next();
      }
      $id_map->rewind();

      while ($id_map->valid()) {
        $map_source_id = $id_map->currentSource();

        $destination_ids = $id_map->currentDestination();

        if (!empty($destination_ids['nid'])) {
          $node = $this->nodeStorage->load($destination_ids['nid']);

          if ($node instanceof NodeInterface) {
            if (!in_array($map_source_id, $source_id_values, TRUE) && $node->get('moderation_state')->getString() !== 'archived') {
              $node->setNewRevision(TRUE);
              $node->set('moderation_state', 'archived');
              $node->set('revision_log', '');
              $node->setRevisionCreationTime($this->time->getRequestTime());
              $node->setRevisionUserId($this->currentUser->id());
              $node->setRevisionTranslationAffected(TRUE);
              $node->save();
            }
          }
        }

        $id_map->next();
      }
    }
  }

Follow these steps

modify your migration code
first of all - run a select query to fetch all the nids of that content type or bundle for which you are migrating the data
next, run migration
identify the nodes which are not part of migration but exist in your select query
in while loop, load these nodes
mark them as unpublished
save these nodes

done!


Next/Previous button for nodes within a book I want to have Next and Back buttons for nodes within a book.

What is the easiest way to achieve this?

ok, this can be achieved by overriding of modules\books\book-navigation.tpl file. Copy this file to your Theme and change following:

 <?php if ($has_links): ?>

      <?php if ($prev_url): ?>
        <a href="<?php print $prev_url; ?>" class="page-previous" title="<?php print t('Go to previous page'); ?>"><?php print t('‹ ') . $prev_title; ?>
      <?php endif; ?>
      <?php if ($parent_url): ?>
        <a href="<?php print $parent_url; ?>" class="page-up" title="<?php print t('Go to parent page'); ?>"><?php print t('up'); ?>
      <?php endif; ?>
      <?php if ($next_url): ?>
        <a href="<?php print $next_url; ?>" class="page-next" title="<?php print t('Go to next page'); ?>"><?php print $next_title . t(' ›'); ?>
      <?php endif; ?>

    <?php endif; ?>

to:

<?php if ($has_links): ?>

      <?php if ($prev_url): ?>
        <a href="<?php print $prev_url; ?>" class="page-previous" title="<?php print t('Go to previous page'); ?>"><?php print t('Back') ?>
      <?php endif; ?>
      <?php if ($parent_url): ?>
        <a href="<?php print $parent_url; ?>" class="page-up" title="<?php print t('Go to parent page'); ?>"><?php print t('up'); ?>
      <?php endif; ?>
      <?php if ($next_url): ?>
        <a href="<?php print $next_url; ?>" class="page-next" title="<?php print t('Go to next page'); ?>"><?php print t('Next'); ?>
      <?php endif; ?>

    <?php endif; ?>

You could try one of the following modules: http://drupal.org/project/prev_next or http://drupal.org/project/custom_pagers. We've been using the Prev/Next module for a while in a project.


Delay ajax call on textfield to allow for typing I would like to delay ajax from firing in the same way that the autocomplete seems to work. For example, if a user it typing, the ajax will not run until 500ms has elapsed since the last keyup.

I am currently looking at drupal.behaviors but not able to make it work.

Drupal.behaviors.mymodule = {
  attach: function(context, settings) {
    $('input.andtimer', context).delay(500).ajaxStart();
  }
};

This is the form element to which the behavior is attached.

$form['my_input'] = array(
  '#type' => 'textfield',
  '#default_value' => $value,
  '#ajax' => array(
    'callback' => 'my_callback',
    'event' => 'keyup',
    'wrapper' => 'my_wrapper',
    'trigger_as' => array(
      'name' =>  'my_button',
  ),
  'progress' => array('type' => 'none'),
  ),
  '#attributes' => array(
    'class' => array('andtimer'),
  ),
);

This jsfiddle shows what I am trying to achieve.

Would How to override Drupal.ajax.prototype.beforeSend? be a route to take this down?

The following works for the first 'set' of inputs with the class .andtimer. It is not working for any other set, the ajax always continues with the first set. Any ideas how to fix this?

(function($, Drupal) {
    Drupal.behaviors.bform = {
        attach : function(context, settings) {

            var events = $('.andtimer').clone(true).data('events');
            $('.andtimer').unbind('keyup');
            var typingTimer;
            var doneTypingInterval = 300;
            $('.andtimer').keyup(function() {
                clearTimeout(typingTimer);
                typingTimer = setTimeout(doneTyping, doneTypingInterval);
                function doneTyping() {
                    $.each(events.keyup, function() {
                        this.handler();
                    });
                }

                return false;
            });
        }
    };
})(jQuery, Drupal);

Using $form['my_input']['#ajax']['event'] = 'finishedinput' as suggested and

var typingTimer;
var doneTypingInterval = 600;

$('.andtimer').on('keyup', function (e) {
  clearTimeout(typingTimer);
  if ($(this).val) {
    var trigid = $(this);
    typingTimer = setTimeout(function(){
      trigid.triggerHandler('finishedinput');
    }, doneTypingInterval);
  }
});

Works for each 'group' of inputs where the count of filled inputs needs to be obtained.

One option is to use a custom jQuery event, eg. something like finishedinput. Set $form['my_input']['#ajax']['event'] = 'finishedinput' and provide some JS to trigger your custom event after an appropriate delay (similar to the JS in the fiddle).

This is the code I wrote:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="pt-br" lang="pt-br">
<head><title>Submit after typing finished</title>
<script language="javascript" type="text/javascript">
function DelayedSubmission() {
    var date = new Date();
    initial_time = date.getTime();
    if (typeof setInverval_Variable == 'undefined') {
            setInverval_Variable = setInterval(DelayedSubmission_Check, 50);
    }
}
function DelayedSubmission_Check() {
    var date = new Date();
    check_time = date.getTime();
    var limit_ms=check_time-initial_time;
    if (limit_ms > 800) { //Change value in milliseconds
        alert("insert your function"); //Insert your function
        clearInterval(setInverval_Variable);
        delete setInverval_Variable;
    }
}

</script>
</head>
<body>

<input type="search" onkeyup="DelayedSubmission()" id="field_id" style="WIDTH: 100px; HEIGHT: 25px;" />

</body>
</html>


Change class on the div wrapper of a form element Is there a way to add or change a class to a form wrapper (the div's) using the form api?

Or is that just done with the theme function ?

If so which theme function is used to change that?

You can override theme_form_element() normally if you want to change the theming globally. If you're interested in modifying just one specific form element then I'm aware of a couple of choices.

You can register a new theme function for the particular type of form element you're interested in (eg. textfield). You then create this theme function (based on the original, eg. theme_textfield()) but that doesn't call theme('form_element', ...) at the end (you could either handle both the wrapper and the element in the one theme function, or you could make a separate wrapper theme function and use that). Finally you add a #theme property to a particular form element, and that element will get your custom theming.
You can create a template file called form_element.tpl.php which just has the default behaviour of theme_form_element() and then use hook_preprocess_form_element() to add a template suggestion. Then you create the new template that matches the suggestion. You often hear people mentioning that templates are slightly slower than functions, and for such a frequently used theme call I can imagine people balking at using a template. I've never done any measurements for this myself however. Also, you need to have enough context at the preprocess stage to be able to make the suggestion.

<?php
    $form['#attributes'] = array('class' => 'your-class-name');
?>

You can use the above way to add a class on the form element.


display list of pages of content type using views + edit and delete option I've installed the Views Bulk Operations module (VBO). Using this I want to create a block/page to  load all the pages of particular content-type. But it should include options like update + check boxes, edit/delete. See the screenshot below.

I couldn't find the built in view 'content', so I've to create from scratch. Please give me solutions.

I got the solution by installing Admin VBO Views module


Boolean checkbox in sytems_settings_form I have written the following code

$form['checking'] = array(
    '#type' => 'checkbox',
    '#default_value' => variable_get('checking',0),
    '#title' => t('title'),
    '#required' => TRUE
  );

  return system_settings_form($form);

the checkbox preserve its checked and unchecked state in the form but I can't get value of the checkbox.

I'm printing its value

dsm(variable_get('checking);
print_r(variable_get('checking',0));

Whether a checkbox is checked or unchecked, in both cases it returns me 1

How can I know whether the checkbox is checked or not?

Have you tried removing the "#required" => TRUE line? If you uncheck the checkbox and the form item is required the form won't validate and your submit callback will not be called.

Also, you should check that your variable isn't overridden in settings.php https://www.drupal.org/node/1525472

hmmm, looks like you're print_r'ing the result from variable_get() - ie. you're unwillingly asking "did variable_get() run correctly?"

try storing the result from variable_get in a variable then print_r'ing that. or use dsm() instead (from the Devel module).

cheers,
Luco


Get the actual query executed by a view I need to find out the SQL query that is executed by a certain query. Views module can show the SQL when configuring the view but apparently the query is not the actual query that gets run in all cases.
I am aware that the Devel module can show the database queries, but there is no way with devel to show the actual queries except clicking the associated 'A' link with every query and there are hundreds of them.

How can I find out the actual query that the view executes? The view is displayed as a block.

You have to use hook_views_pre_execute and with Devel installed use dpq to view the SQL String:

function hook_views_pre_execute(&$view) {
  dpq($view->build_info['query']);
}

//Get The Results by View Name and Contextual Filter nid here

    $viewr = views_get_view('your_view_display');
    $args[] = $myarg;
    $display_id = 'default';
    $viewr->set_arguments($args);
    $viewr->set_display($display_id);
    $viewr->execute();
    $view_content = $viewr->result;

See the doc for more reference: https://api.drupal.org/api/views/views.module/function/views_get_view_result/7.x-3.x


Paid membership plans on registration page I am creating a registration based website that has five membership plans.

Based on the selected membership plan, users have to pay the membership fee using Stripe payments.

How can I create membership plans and this kind of payment functionality?

For membership process you can use the (paid for) Moneyscripts module.

  Membership Suite is the most comprehensive subscription software for
  Drupal on the market and it is designed to seamlessly integrate your
  site with all of the features of a professional Paid Membership
  Subscription site. There is no other software available for Drupal
  that can provide the stability, ease of use, and features that
  Membership Suite offers.

Why don't you make use of the Commerce distribution and the Commerce stripe contrib module? With commerce you can attach roles to products, so when a user buys your membership plan "A" he/she will automatically get assigned role "A".


Content types disappear In some lists my content types all disappear. This especially affects Apache Solr for me. But also Views and Rules dont show the content types in some lists.

Interesting is that:

One content type is shown("Rezept") which is created by a custom module
All content types are shown correctly the moment i clear the cache.

Views:

Apache Solr Module:

The moment i clear the cache they show up correctly. But as soon as the cache clearing is finished and i reload the page, they disappear again:

Views while clearing the cache:

Apache Solr while clearing the cache:

The problem was caused by Domain Access Module. Since i didnt needed it anymore, i deactivated it.


how to customized user login page My question is when i  browse  my admin site www.example.com/user a simple login page will appear.

Here in this login form there is no option for forget password .so I need option to request new password and new password can be send through email.

You can make a template to alter your user login form.

In template.php:

function YOURTHEMENAME_theme(){
    return array(
        'user_login' => array(
            'arguments' => array('form' => NULL),
            'render element' => 'form',
            'template' => 'templates/user-login-form',
        ),
  );
}

Then create user-login-form.tpl.php in your template folder and print the login form using

print drupal_render_children($form);

Don't forget to clear cache

Customizing the user login, register, and password reset pages is fairly simple, and uses the following concepts:

preprocessing to set variables
registration of functions in the theme registry
creation of one or more theme templates.

Step 1.
In the site theme directory, create or edit your template.php file.

Step 2.
The first step is to implement hook_theme for your theme. In the template.php file for your theme, look for a function named yourtheme_theme() and modify it to add these return values. If the function doesn't exist, add the following:

For D6:

 array(
      'template' => 'user-login',
      'arguments' => array('form' => NULL),
    ),
    'user_register' => array(
      'template' => 'user-register',
      'arguments' => array('form' => NULL),
    ),
    'user_pass' => array(
      'template' => 'user-pass',
      'arguments' => array('form' => NULL),
    ),
  );
}
?>

Notes about that code:

Change the function name by replacing "yourtheme" with the name of your theme
The template can be the same for all three. The example above uses a different template for each case: user-login, user-register, and user-pass
The template names must use a dash, not an underscore
Note: It's user_pass not user_password

For D7:

 'form',
    'path' => drupal_get_path('theme', 'yourtheme') . '/templates',
    'template' => 'user-login',
    'preprocess functions' => array(
       'yourtheme_preprocess_user_login'
    ),
  );
  $items['user_register_form'] = array(
    'render element' => 'form',
    'path' => drupal_get_path('theme', 'yourtheme') . '/templates',
    'template' => 'user-register-form',
    'preprocess functions' => array(
      'yourtheme_preprocess_user_register_form'
    ),
  );
  $items['user_pass'] = array(
    'render element' => 'form',
    'path' => drupal_get_path('theme', 'yourtheme') . '/templates',
    'template' => 'user-pass',
    'preprocess functions' => array(
      'yourtheme_preprocess_user_pass'
    ),
  );
  return $items;
}
?>

Notes about the D7 version:

The 'path' lines tell Drupal where to find the .tpl.php files. This is optional, and in the code above, 'path' tells Drupal to find the files in the templates subdirectory of the theme's base directory.
Note the "_form" added to the user_register element.
Note: As it is the case for D6, it's user_pass not user_password

Step 3.
Now you implement three preprocess functions. There may be more concise ways to code this, but this works very well and is easy to read, so here we go!

For D6:

Notes about that code:

Change the function name by replacing "yourtheme" with the name of your theme
The line $variables['intro_text'] adds the text that follows to the $variables array, which gets passed to the template as $intro_text
The second line renders the form and adds that code to the $variables array, which gets passed to the template as $rendered

For D7:
The code is even simpler for D7 because we don't need to pass a variable containing the form content we want rendered. The variable exists already in the $vars array and can be rendered in the .tpl.php file.

The above preprocess functions simply add a variable into the $vars array that is then displayed in the .tpl.php file. Much more complex manipulation of the content of the render array is possible.

Please note, that the preprocess functions should go into the template.php file.

Step 4.
Create template files to match the 'template' values defined above.

For D6
We need the following template files (make sure to use a dash, not an underscore) :

user-login.tpl.php
user-register.tpl.php
user-pass.tpl.php

For D7
As for D6 but with user-register-form.tpl.php for the register form.

Step 5.
Paste the following into user-login.tpl.php. Modify as necessary for user-register.tpl.php (D6) and user-register-form.tpl.php (D7):

For D6:

For D7:

Add the forgot password link, HTML Tags, Css & JS.

Note the change to the syntax for causing Drupal to render the form. Also, the D7 sample uses a different class for the div, but that's just a matter of preference.

Step 6.
Save your template.php file to the theme's main directory. Save your .tpl.php files in the same place for the D6 examples, or, in the case of the D7 examples, to the directory you specify in the 'path' element of the $items array.

Step 7.
Rebuild the cache. Go to Administration > Performance and click on "Rebuild Cache" on the bottom of the page.

Now, the user login page will contain the new text from the preprocess function, and the tpl.php file(s) can be modified to suit the site's needs.


Specific field tag based naming conventions (overriding views-view-field.html.twig for specific fields) I've scoured the documentation and I simply cannot find an answer to this question regarding naming convention for twig files given a tagged view with the override of a specific field.
Let me create a scenario to explain the problem.

Given Viewname with tag viewtag with a block display and a fieldname field.

I can override the theme as follows

Original file --> Overridden file name

views-view-unformatted.html.twig --> views-view-unformatted--viewtag.html.twig
views-view-field.html.twig --> views-view-field--fieldname.html.twig
views-view-field.html.twig --> views-view-field--viewname--block--fieldname.html.twig
views-view-field.html.twig --> views-view-field--block--fieldname.html.twig

I cannot figure out how to override views-view-field for a specific fieldname by specifying the viewtag. The following names do not work:

views-view-field--viewtag--fieldname
views-view-field--viewtag--block--fieldname
views-view-field--fieldname--viewtag
views-view-field--block--fieldname--viewtag
views-view-field--block--viewtag--fieldname

I've run out of possible combinations and yet I'm simply not able to get the viewtags to override the specific field. Surely there has to be a way to do this given that you can use the viewname to override the templates. I'd rather avoid having 50 versions of a view template when 1 could do the same thing.

I am able to use the tag to create template files for everything other
  than the specific field templates. – John Millnik

Your comment gave me the following thought: When you tag something, you tag the node and not the fields themselves. Fields do not have any tags, which makes me think that what you're trying to do is not possible.

I am pretty sure you cannot target a specific field in a view. Is this view being pulled into a global sidebar or into the content area of a specific content type? If it's being pulled into the content area then you can add the view block as an entity reference field in the content type itself and target the field that way, like targeting a field inside of a field. Let me give an example and explain.

Let's say you want track titles (field_track_title) and their albums (field_album) to appear on a bio page. (The bio page and the tracks are separate content types, bio page machine name being bio.) Create your view block displaying the track titles and albums as normal. Go ahead and place this block in a hidden region under block layout- this must be done in order to render it anywhere.

Then, in the bio content type, create a field referencing "other."

On the next screen select Block as the type of item to reference and set allowed number of values to 1.

When you get to the edit field screen you can select your newly created view block as the default (so you don't have to select it each time you create a new content type instance) and save. Make sure to place this field somewhere in your Manage Display screen.

Finally, to answer your question, you now can target this view's field because it renders as a field in the content type.

field--node--field_album--bio.html.twig


Drupal entity metadata wrapper no bundle property Using <?php
$wrapper = entity_metadata_wrapper('node', $nid);
?>

When I $wrapper->title->value(); I get error msg that property Title does not exist....

Using Entity 7.x 1-8 and D7.56. I am aware that $nid can be a node (from node_load) or a node id.

What am I missing?

I solved it applying this patch:
https://www.drupal.org/project/entity/issues/2819665

although I to be honest don't understand why...


Get User ID (not current) in a overridden views.tpl.php I'm using Drupal 7.
I'm creating a view based on profile. It will show a list of all the people.
Now I'm overriding the file views-view-unformatted--MYVIEW-page.tpl.php and I would like to add in the class of the row the ID of that user.
If I write

global $users;
$user->uid;

of course it's giving me the id of the current user and not the uid of that profile.

I would like to create something like this:
FIRST EXAMPLE:

    <?php
    $this_uid = I NEED THIS TOKEN;
    ?>

    <?php foreach ($rows as $id => $row): ?>
      <li class="<?php print $classes_array[$id]; print " ".$this_uid;?>">
        <?php print $row; ?>

    <?php endforeach; ?>

I could create a custom text field in the view a put all the field inside the
 tag
like:
SECOND EXAMPLE:

[name] [gender]

and the file tpl.php will become

<?php foreach ($rows as $id => $row): ?>
            <?php print $row; ?>
        <?php endforeach; ?>

But in this way I will lose the default row classes...

How can i get the first example? Do I need to create a view based on user instead of profile? Or should I use the second example?

Thanks in advance.

You should have a $views variable available with an array similar to $rows called $view->result[] that contains the unrendered/raw view results and just as long as you have a field in your output that has the uid in it, you will be able to access it directly here.  (It can be a hidden field if you don't want it rendered later on) Put a drupal_set_message('<pre>' . print_r($view->result, true) . '</pre>'); or its equivalent in your template to take a look at it, but basically you should be able to use something like $view->result[$id]->FIELDNAME to access it or any other raw data.

Use views PHP field, set it as hidden, then use PHP to save needed value in this field. After that, views template will be able to get that value.

Make sure you clear cache and rebuild theme registry.


How to access the node title within a field template? I'd like to know the node title within the file link template. How can I get it?

For the current example I use the bootstrap file-link.html.twig template. In it, I have the following variables:

{#
/**
 * @file
 * Theme override for a link to a file.
 *
 * Available variables:
 * - attributes: The HTML attributes for the containing element.
 * - link: A link to the file.
 * - icon: An icon.
 * - icon_only: Flag to display only the icon and not the label.
 * - icon_position: Where an icon should be displayed.
 *
 * @see \Drupal\bootstrap\Plugin\Preprocess\FileLink::preprocessVariables
 */
#}

I dont know if a preprocess function is the correct way to go. I didnt even found a respective hook for drupal 8 for that. I dont even know if this is a field template. But still, the question would also be interesting for other templates than file-link.

He wants to get the node title in the file link template (I assume that is file-link.html.twig).
You can implement the hook template_preprocess_file_link() in your mytheme.theme file, get the current node and pass its title to twig, something like:

function mytheme_preprocess_file_link(&$variables) {
   $node = \Drupal::request()->attributes->get('node');
   $variables['node_title'] = $node->getTitle();
}

Then, in file-link.html.twig:

{{ node_title }}

I assume, you are using Drupal 7 and we're talking about a node.tpl.php:

<h2<?php print $title_attributes; ?>>
 <a href="<?php print $node_url; ?>">
  <?php print $title; ?>

*Edit: Just realized, you're using Drupal 8:

For a node.html.twig you could try:

  {{ title_prefix }}
   {% if not page %}

     {{ label }}

   {% endif %}
 {{ title_suffix }}


The website encountered an unexpected error. Please try again later (WSOD). Debugging scenario After updating Drupal using drush my website says 'The website encountered an unexpected error. Please try again later'. with white screen(WSOD).

Then when I tried to rebuild-cache using drush there was a drush fatal error originating with rules module. I got it rectified by replacing rules module with 3.x dev version.

I could rebuild the cache and update database using drush. But still the wsod is there

My next move was to enable error reporting. So I added the line

$config['system.logging']['error_level'] = 'verbose';
it did not return any errors on the the screen.
I like to know a debugging scenario for D8 as i faced this same issue for my another D8 installation but that was rectified after rebuilding the cache. I have came across posts by user with similar issues but reasons for their issues were different. So I strongly believe that there should be a debugging scenario that can apply to all.

1- Install Drush if you have not installed it already.

2- Clear cache using drush.

3- Still if you are facing issues start debugging with error logs as following.

Add the following lines to your settings.php

error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);

While editing settings.php change its default file permission to writable.
And you may also add following to your settings.php

$config['system.logging']['error_level'] = 'verbose';

Additional information is available here!

4- If you see any error related to any custom/contributed module after enabling error reporting service.You may overwrite the particular module folder with its latest release or even try with its dev release

5- You can read the server log messages for additional error informations. These log files may vary as per the server configurations. Some information about the server log file available here!

Simply run the below command to rebuild your site, when you encountered an issue "the website encountered an unexpected error. please try again later" after any new module installed with fatal error.

drush cr


Why does user_load($id) NOT return FALSE when an invalid id is passed in? I'm making a module that lets users manage database records for various organizations.  I'm using Drupal 7 and an very new at it.  I'm logged in as the admin user. I have a menu item 'cb' that checks args and returns content generated by various functions, here it is in the menu:

function org_menu() {
  $items['org'] = array(
    'title' => 'My Orgs',
    'page callback' => 'org_show_orgs',
    'access callback' => TRUE,
  );
  $items['org/create_org'] = array(
    'title' => 'Create New Org',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('org_create_form'),
    'access callback' => TRUE,
  );
  $items['org/search_orgs'] = array(
    'title' => 'Find Orgs',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('org_search'),
    'access callback' => TRUE,
  );
  $items['org/cb'] = array(
    'type' => MENU_CALLBACK,
    'page callback' => 'custom_callback',
  );
  return $items;
}

And this is the cb function that determines what I am trying to do, and calls the appropriate content function:

function custom_callback () {
  if ( arg(2)=="edit" )
    return org_edit_org();
  if ( arg(2)=="view" ) {
    return org_show_orgs();
  }
  return "
Invalid callback function: '".arg(2)."'";
}

and the actual org_get_orgs function:

function org_show_orgs() {
  global $user;
  $acctid=arg(3);
  if ( !$acctid && $user->uid==0 )
    return array('my_content' => '
My Orgs
Please log in to view your orgs.'.
                    '

Find Orgs
', drupal_get_form('org_search'));

  if ( $acctid ) {
    //return "case1 arg0=".arg(0)."
arg1=".arg(1)."
arg2=".arg(2)."
arg3="
    //              .arg(3)."
arg4=".arg(5)."
acctid=$acctid

";
    $account=user_load($acctid);
    //return "case2 arg0=".arg(0)."
arg1=".arg(1)."
arg2=".arg(2)."
arg3="
    //              .arg(3)."
arg4=".arg(5)."
acctid=$acctid

";
    if ( $account===FALSE )
      return "
Invalid acctid "+$acctid+"
";
    else
      return "
account was not FALSE
";
  }
}

cb() gets called correctly and the org_show_orgs() function gets called as expected.  arg(3) is the user id, so I can allow a user to view another user's orgs.

I hit the url
http://example.com/?q=org/cb/view/1
and it works - I see admin's orgs.  If I pick a userid for another user, it works - I see their orgs as well.  The problem is when I tinker with the url and pass in an id of a user that doesnt exist - then I get all kinds of weirdness.  For example, if I hit

http://example.com/?q=org/cb/view/4

If I uncomment that case2 line, I clearly see all my variables are correct:

case2 arg0=org
arg1=cb
arg2=view
arg3=4
arg4=
acctid=4

but if I try to test if $account===FALSE, I get the maintenance page.  If I change the id to 3, I get an 'access denied' page.  If I change the id to 2, I see a 'page not found' page.  If I try return print_r($account,TRUE); I get the menus and a completely blank content cell.  No error, which I'd get it it was a non-array object.  If I try get_class($account) after I retrieve it, I get the menus but no css, and everything is just listed down the left side, no regions, themes, nothing.

Besides the $account issue, is there a better way to be doing this than that callback menu, or is that the drupal way?

The account test probably is working, but this is wrong:

return "
Invalid acctid "+$acctid+"
";

If the $acctid is an integer, it's evaluating that and returning an integer.  The proper php concatenation operator is '.' (without the quotes), change your return statement to

return "
Invalid acctid ".$acctid."
";

It'll evaluate to the string you're presumably expecting.

Actually, the value returned by user_load() is an array. If the $id is not valid, it will return an empty array.

Try changing your test to if (empty($account)).


How can I override the search result page title dynamically? In my Drupal 8 site, I am using the default search page. If I enter a keyword, for example article, the search result will be listed under Search result.
I want to change that to Search result for Article (keyword).
How can I achieve this?

Here comes an example snippet on how to override the page title by URL query:

/**
 * Implements hook_preprocess_HOOK().
 */
function MYTHEME/MYMODULE_preprocess_page_title(&$variables) {

  $current_path = \Drupal::request()->getpathInfo();
  if ($current_path == '/search/node') {
    if (\Drupal::request()->query->has('keys')) {

      // Get the searched string.
      $keywords = \Drupal::request()->query->get('keys');

      // As of https://drupal.stackexchange.com/a/232304/15055 we probably
      // need to ensure the cache gets busted.
      $variables['#cache']['contexts'][] = 'url.query_args:keys';

      // Set the new title.
      $new_title = new \Drupal\Core\StringTranslation\TranslatableMarkup('Search result for Article (@keywords)', ['@keywords' => $keywords]);
      $variables['title'] = $new_title;
    }
  }
}

The hook mentioned above does not work in d8.Instead you can use hook_preprocess_page(&$variables).
Also you can use hook_preprocess_views_view(&$variables)
and continue with the same logic .
function themename_preprocess_page(&$variables) {
 $current_path = \Drupal::request()->getpathInfo();
//echo $current_path;
if ($current_path == '/search/node') {
  if (\Drupal::request()->query->has('keys')) {
    $keywords = \Drupal::request()->query->get('keys');
    echo "Search Results for " . $keywords;
    }
  }
}


how to change the weight of a moderation state transition outside the database how can I change the weight of a Moderation state transition in code?  is it possible?  This is for Drupal 8

Change the weight in the admin panel, then export the yaml files with drush config-export


I can't turn off/pause automatic slideshow when there is only 1 picture (using lightbox2) I am using lightbox2 and it is a wonderful module. The only issue that I have is that I cannot seem to find a way to turn off the automatic diashow when there is only 1 picture.

When 5 pictures are added to a blogmessage there is a slideshow, 1 by 1 the pictures are shown. This can be paused in case someone wants to have a longer look at a picture.
When there is only 1 picture it is not possible to pause. It is possible but I have to configure a button, standard is Space button. But my users do not know this. How can achieve this without a keyboard key?

What I want:
I want to make sure that when there is only 1 picture it can also be paused. So you don't have to click on the thumbnail of the picture again to see it in deatil.

I hope that is somewhat clear.
Thanks in advance!

when there is only one picture then it won't go off untill click somewhere else on the screen ... for better understanding go to lightbox configurations...


Entity Reference of multiple types I would like build out page content using entity references. The problem is I would like to reference multiple types of entities (nodes and terms) plus content that is not an entity (views.)

I've explored this and what I have now is a field for both Node Reference and Term Reference and another with a View Reference which is not a very user-centric. Is there a more succinct way to achieve this?

While relation can handle multiple entity types in a single relation type it can't reference Views. It's a challenging problem for two reasons: the view_id is a string unlike say nid so a database schema made to refer numeric IDs won't be able to copy with views. Also, views is not stored in the database necessarily so the utility of such reference is limited.

It should be possible to maintain an entity in the database that has a numeric ID and all it contains is the Views ID. Your only problem becomes when someone changes the machine of a view that is maintained in code -- how do you plan to be notified of such a thing when it happens outside of Drupal?

How about https://drupal.org/project/entityreference and https://drupal.org/project/entityreference_view_widget for nodes and terms and https://drupal.org/project/views_field_view for embedding views?

Entity reference has nice usage statistics. I quickly tested Entityreference view widget, and it looks convincing (see the inspirational screen capture https://drupal.org/files/images/view_widget.png). Views field view I didn't test, but its usage is around 10 000.


Add a page to nodes with comment form I'm using Drupal 7.

I would want to add a page to my nodes, with the comment form (only), and a link in the tab menu to reach it :

I tried with views but I did not arrive there.

Do you know the simplest way to reach there?

I believe Display Suite module will do the trick.


Actual output in view is different than preview I have set up a view to display all nodes for 1 taxonomy term. Something got messed up and now the final view drops one node (which is also a different content type).

I cannot find rhyme or reason why the content type with images is being left out.

I have deleted the old view and copied a working one that has been set up for a different model again, changed taxonomy term, path and link and BANG the gallery node missing again.

The preview of the view shows it as it should be.

The page affected is this one:
http://www.riverlakesea.com/smartwave/skippa

A pointer where I must check would be much appropriated since I have been through node/content type/view gazillion times and cannot spot the problem.

Many thanks,
Susanne

Change your filter to include content of that particular content type. Does it pull just that gallery?

Also, screen shot of your view admin panel would be helpful.


Load login / register block in custom template I've created my own homepage template [page--front.html.twig] and want to add the drupal default login and register form. I was looking for something like

{% include 'themes/bootstrap/templates/block--system-login.html.twig' %}

But it looks like none of these kind of blocks exist.

If I go to user/login and take a look into the source code (with devel enabled) I also do not see any block hint:

<div class="region region-content">

<!-- THEME DEBUG -->
<!-- THEME HOOK: 'block' -->
<!-- FILE NAME SUGGESTIONS:
   * block--flowers-content.html.twig
   * block--system-main-block.html.twig
   x block--system.html.twig
   * block.html.twig
-->
<!-- BEGIN OUTPUT from 'themes/bootstrap/templates/block--system.html.twig' -->

<!-- THEME DEBUG -->
<!-- THEME HOOK: 'form' -->
<!-- BEGIN OUTPUT from 'core/modules/system/templates/form.html.twig' -->
<form class="user-login-form" data-drupal-selector="user-login-form" action="/user/login" method="post" id="user-login-form" accept-charset="UTF-8">

How can I add the login and register form in my (homepage)-Template? I did not find any useful information related to Drupal 8.

Any help is much appreciated. Thanks!

The user/login page is different from the the user login block. To add the user login form to an arbitrary page, then you would need to add the user login block to a region you want, and configure it to display only on the front page. This can be done using the Block administration page (documentation).

this is for register form in block

<?php
$entity = \Drupal::entityTypeManager()->getStorage('user')->create(array());
$formObject = \Drupal::entityTypeManager()
  ->getFormObject('user', 'register')
  ->setEntity($entity);
$form = \Drupal::formBuilder()->getForm($formObject);
print  \Drupal::service('renderer')->render($form);

tnx from otarza ♥♥♥


Comment form above comments? Is there a simple way to move the comment form above the comments in Drupal 6?

You can use the Comment form above comments module which adds option to place comment form above the comments thread.

The simplest way I found was with CSS
Note: I only want to do this with a specific Content type with the class ".node-chat-with-a-character" the height/padding of 200px was specific to my solution, and was a number I arrived at after removing a lot of extraneous things from the comment form.

/*put comment submit above comments*/

.node-chat-with-a-character #comments {
   position: relative;
   padding-top: 200px;
}

.node-chat-with-a-character #comments .comment-form{
   position: absolute;
   height: 200px;
   top: 0px;
}


How to render an Image Field as a URL in node.tpl.php I have an image field called field_body_image

I want to render it in my tpl.php file with a custom image style. I am using the following code (from this thread) to do this:

<?php $view = field_view_field('node', $node, 'field_body_image', array('settings' => array('image_style' => 'thumbnail')));?>
<?php print render($view); ?>

However, I want to display the URL of the image. How can I do that?

This thread has a solution, but it is for user photos and so you cannot specify a custom field.

Image Url Formatter is a module that can do this, but I would rather achieve it without an extra module.

This page has some advice, but apparently it is not best practice.

You can do this by getting the path to the file.

<?php $file = file_load($node->field_body_image['und'][0]['fid']); ?>

Then render the path:

<?php print file_create_url($file->uri); ?>

I tested this and it works. In my case I had an event image in my local dev site and it rendered:

http://events.dev/sites/default/files/event-images/imagefield_7tgPJ7_0.jpg

In your tags, you did not specify Drupal 6 or 7 but my code above would be for Drupal 7.

first enable devel module, and add this to top of your tpl file:

<?php dpm($node); ?>

then clear your cache, and refresh your node. then you probably see an orange box at top of your page, click to collapse it, and start looking for your image cck field (ex. field_products_image), click on that to see if there is any more array beneath that or not, what you are looking for is a string named "filepath". now you have to render your image URL like this:

<?php print $node->field_products_image[0]['filepath'] ?>

let me know if it works or not.


Why does drupal use .yml and not officially recommended .yaml Per yaml page https://yaml.org/faq.html they recommend .yaml as file extension but I see drupal uses almost exclusively .yml, how so? And does adding .yaml to file extension even work for drupal 8 or will it be skipped?

Drupal uses '.yml' because Symfony uses '.yml'

This was discussed in https://www.drupal.org/project/drupal/issues/2091669

I am assuming that '.yaml' would not work, but I haven't tried it. For consistency reasons it is best to stick to '.yml'.

EDIT: Looks like Symfony has started recommending '.yaml' from version 4.0. Can be seen by comparing this page https://symfony.com/doc/4.0/routing.html with the 3.4 version

because drupal 8 based on symfony 2 and .yaml is not recomended in symfony 2 , it's recomended just for version 4 of symfony 4


How do I find the role id from role name? On log in I want to check a third party data source (table in the db) for a user, and if found I want to add a role to that user.

I don't want to guess the rid of the role, I want to get it from the role name.

Knowing the machine name of the role, it is enough to use user_role_load_by_name().

if ($role = user_role_load_by_name('Role Name')) {
  // The role ID is in $role->rid.
}

If the Role might not exist...

$role = user_role_load_by_name('Role Name');

$role_id = $role ? $role->rid : NULL;

The best way to identify role and its id is from SQL. Run this query in your SQL editor.

select * from roles;

And you will get the list of Roles including the id and weight.


Patching .htaccess file I need to patch .htaccess file which is located in project's root (docroot in this case), my project is written using composer and I created a patch using git, added it to the /patches directory and wrote a composer.json entry:

"drupal/drupal": [
          {
            "title": "htaccess patch",
            "url": "docroot/profiles/laeg/patches/redirects.patch"
          }
        ]

Sadly after running composer update my patch doesn't appear in the patches list therefore it is not applied. I was told that I should patch drupal/drupal but it seems to not be a case, has some done anything like this and could suggest me something? Project is running Drupal 7.

For drupal 8, use the following.
In the 'scripts' section of your composer.json, add

"post-drupal-scaffold-cmd": [
  "patch -p0 < patches/htaccess.patch"
]

A little late, but check out https://github.com/drupal-composer/drupal-scaffold/issues/45. They give a few solutions for handling the issue.


How can I add pager to the comments of advanced forum in drupal 7? I use the drupal 7 core forum with advanced forum module.

This works perfectly except the forum topic page show only post comments what number is defined on the content type, and no pager on the comments, therefore the users can't jump to the next few comments.

My question: how can I add pager (first, prev, next, last, etc.) to the advanced forum post comments?

I didn't found any solution until yet.

In your style directory, you should have a *.topic-header.tpl.php file. Make sure the following is where you want the paging to display:

<?php print($pager); ?>

Then, in *sites/all/modules/advanced_forum/includes/theme.inc*

Approximately line 446:

  pager_default_initialize($variables['node']->comment_count, variable_get('comment_default_per_page_forum'));
  $variables['pager'] = theme('pager');


How to improve Drupal speed when developing in localhost I'm looking for tips from other Drupal developers to make Drupal faster when developing (specially Drupal 7)

Taking in consideration that during development you don't want cache, so you can see the result of changes in code php/css/js. (See some answers here to flush cache / disable cache permanently)

Googling for "drupal slow localhost" will give some tips... but I want yours :)

The best tip you can use (this really change my life) is adding a line in your my.cnf file:

innodb_flush_log_at_trx_commit = 0

You can find this file in your wamp folder or if your on linux server: /etc/mysql/my.cnf

Regards

Get a faster machine.

Not only are you running apache/php/mysql on it you are also running a GUI and a IDE, probably multiple web browsers, skype, itunes all of which compete for resources. Making you drupal install and your whole machine slow.

Alternatively, have a separate machine with the Drupal install on to help spread the load.


add title to front page teaser news feed I would like to add a title to my news feed. I have tried to edit node--teaser.tpl.php and added

<?php if($page['feed-title']): ?>
<!-- start feed title -->
<?php print render($page['feed-title']); ?>
<!-- end feed title -->
<?php endif; ?>

on top, then I added

regions[feed-title] = Feed Title

in my theme.info file. I created a block which is assigned to this region but still, nothing is being displayed, why not? Am I doing something wrong or can I not add regions into a region template file?

Thanks!

If you look at the page.tpl.php template file used by the Bartik module, you will notice it uses code like the following to render a region.

  <?php if ($page['triptych_first'] || $page['triptych_middle'] || $page['triptych_last']): ?>

      <?php print render($page['triptych_first']); ?>
      <?php print render($page['triptych_middle']); ?>
      <?php print render($page['triptych_last']); ?>

  <?php endif; ?>

node--teaser.tpl.php is not used to render a page, but a node into a page. It is hierarchic, someway: html.tpl.php wraps the content of page.tpl.php, which wraps the content of node.tpl.php.
Regions are part of a page, not a node; therefore, the template file where to render the regions is page.tpl.php or any suggested templates used instead of that one.

When you add a region in theme.info file, you have to render the region in page.tpl.php.

That's where you are doing wrong. You are doing it in node.tpl.php.

Don't forget to clear the cache after you render your region in page.tpl.php.


How to clear cache externally? I'd like some help how to clear the cache using an external script. I have a script that adds nodes each night, and I'd also like it to clear the views cache so - without having to make out by myself the MySQL query.

If you are running a script, you'll likely benefit from using Drush.  With the Drush php-eval and php-script commands, you can easily call a snippet of php code (such as the examples shown in other answers to this question) after bootstrapping Drupal.  Without Drush, you would have to set up a web service and use wget or curl to run your code, or try to call the Drupal bootstrap code yourself.  Better yet, Drush even comes with a built-in command to clear the cache, so you don't need to worry about writing any php code at all, if that's all you want to do from your script.  Just use:

cd /path/to/drupal/sites/default && drush cache-clear all

You may also wish to learn about site aliases; if you define an alias called @site, then you can instead use:

drush @site cache-clear all

TRUNCATE the cache_views table in the database.


Custom Field Plugin With Image Field I have been working on a custom field plugin with which the aim is to create a custom field to be used for content and will consist of a link field and a file field through which a thumb image is to be uploaded. I'm ok with the first part is i.e. the link field for which I have declared a uri data definition with a varchar storage schema and a url type for the form element. But I cannot (based on the available documentation) figure out the proper way to manage the file field. I have used a managed_field type as for the form element but cannot figure out what is the correct datatype and storage schema to use.

Edit: The documentation I have found deals with three parts,

The field class where the propertyDefinitions method is overridden and the properties are defined (ex. $properties['link'] = DataDefinition::create('uri')->setLabel(t('Video Link'));)
Also in the field class where the schema method is overridden and the storage properties are defined (ex. $columns['link'] = [ 'type' => 'varchar', 'length' => 255, ];)
the widget class where the formElement method is overridden to define the input form (ex. $element['link'] = [
        '#type' => 'url',
        '#title' => t('Link'),
        '#default_value' => isset($items[$delta]->link) ? $items[$delta]->link : null,
        '#empty_value' => '',
        '#placeholder' => t('Insert a url'),
    ];)

what should the equivalent parts for an image/file field property be defined?

any input would be appreciated, thanks

I hope I understood correctly:

FileItem.php

Have a look at public static function defaultStorageSettings() and public static function schema(FieldStorageDefinitionInterface $field_definition)

Why don't you try the Paragraphs module? This looks like a simple combination existing of field types, which is exactly Paragraphs' point.


Drupal 7. Webform textarea with a html editor I am using drupal 7.56
I used the webform module to create a custom form which contains a textarea.

I want to add a html editor to my textarea.

I tested webform_html_textarea but it's not what I need.

How can I configure CKEditor module for this issue?

This is fixed by enabling wysiwyg, ckeditor and webform_html_textarea

Thank you


Is there a way to figure out the block machine name? In Drupal 8, is there a way to figure out what current block or view machine name you should use?

For example, with the following code, I noticed that 'machine_name_to_determine' could change depending on how many times you have used your block.

$block_id = 'machine_name_to_determine';
$block_config = \Drupal\block\Entity\Block::load($block_id);

I need a way to retrieve this at run-time. How can I retrieve it?

You can query the blocks by the plugin id. This is the id of a block plugin or for derivatives like a view block (which you probably are looking for as you've mentioned a view machine name) with additional parameters:

$plugin_id = 'views_block:' . $view_id . '-' . $display_id;

Where $view_id is the view machine name which you find in the Views UI and $display_id is the display machine name, usually block_1 for the first block of the view.

Then get all blocks placed for this plugin id and print the block machine names or use the loaded blocks in your code:

$blocks = \Drupal::entityTypeManager()->getStorage('block')
  ->loadByProperties(['plugin' => $plugin_id]);
foreach ($blocks as $block) {
  echo $block->id();
}

Add a theme or region to loadByProperties() if needed:

['theme' => 'bartik', 'region' => 'header']

This is in accordance to the pointer by @4k4

$plugin_id = 'bookingsystem_block';
$block_id = $this->getCurrentBlockId($plugin_id);
protected function getCurrentBlockId($plugin_id)
{
    $block_id = NULL;

    $blocks = \Drupal::entityTypeManager()->getStorage('block')
        ->loadByProperties(['plugin' => $plugin_id]);

    $current_route_path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);

    foreach ($blocks as $block)
    {
        $visibility = $block->getVisibility();
        $request_path = $visibility['request_path'];
        $request_path_url_arr = explode("\r\n", $request_path['pages']);

        $node_url_arr = array();

        foreach ($request_path_url_arr as $path_alias)
        {
            $path = \Drupal::service('path.alias_manager')->getPathByAlias($path_alias);
            if(preg_match('/node\/(\d+)/', $path, $matches)) {
                $node_url_arr[] = $path;
            }
            else if($path_alias=='<front>') {
                $node_url_arr[] = '/';
            }
        }

        $request_path_url_arr = array_merge($request_path_url_arr,$node_url_arr);

        if(in_array($current_route_path,$request_path_url_arr))
        {
            $block_id = $block->id();
            break;
        }
    }

    return $block_id;
}


How to expose the user's email on the user's detail page? Currently in the manage display page there is no way to display the email field in the manage display page. How do you expose this in Drupal 8 contacts details page?

There can be a work around for this as in user template or views-block rendering on profile page.

By default the mail field is not configurable in view modes.

You can change this in a custom module. Place this hook in mymodule.module

function mymodule_entity_base_field_info_alter(&$fields, $entity_type) {
  if ($entity_type->id() == 'user') {
    if (isset($fields['mail'])) {
      $fields['mail']->setDisplayConfigurable('view', TRUE);
    }
  }
}

and you'll find the mail field in the Manage Display page.

I assume the reason this wasn't added was to encourage use of the Contact form instead (given email addresses are hidden, there's flood protection and you can allow users to enable/disable it). However, clearly there are reasons for it being convenient to see the actual address.

(Do take time to check your permissions for user profile pages though, so you're not exposing people to spam.)

Here's a modified user.html.twig, using classy as the base theme, with clickable address and a translatable string for the label:

  {% if content %}

{% trans %}Email{% endtrans %}

{{ user.mail.value }}

    {{- content -}}
  {% endif %}


Using wget to get the latest module version I was contemplating building a quick bash script to wget all of the modules I use on Drupal sites but every time the module version changes, the link changes.

Take for example the views module. At the time of writing it's at version 7.x-3.0-rc3 and therefore the link is as such http://ftp.drupal.org/files/projects/views-7.x-3.0-rc3.tar.gz

If I were to add this to my bash script it'd obviously stop working as soon as the next version is released.

Is there a URL which I can use with wget which will always give me the latest non dev version of a Drupal module.

[...]drupal.org/projects/views-7.x-stable.tar.gz for example

I don't want to use GIT or CVS etc as this will mean anyone using the script will need to install said program first. I would just like to be able to pass this script around to developers in my office to quickly download and deploy the latest Drupal version and modules we use constantly.

The latest stable is published on an XML file, so your script would need to query and parse it to get the proper URL. http://updates.drupal.org/release-history/project-list/all this returns ALL the projects release history, obviously very large. You can get a specific project with this URL http://updates.drupal.org/release-history/views/7.x where "views" is the project name and "7.x" is the version.

Or you could just use DRUSH. It's super easy to install and will make your life 100x easier and better. Drush is a command line PHP script that allows you to simply type things like drush dl views or drush up views. It can do a lot more too, it's truly amazing. http://drupal.org/project/drush

Dave Hall has a blog post on this very subject, with excellent example code, at http://davehall.com.au/blog/dave/2010/02/22/check-drupal-module-status-using-bash


Getting the image URL from a field_image on a node So I have this Node:

object(Drupal\node\Entity\Node)[1862]
  protected 'values' =>
    array (size=17)
      'vid' =>
        array (size=1)
          'x-default' => string '7' (length=1)
      'langcode' =>
        array (size=1)
          'x-default' =>
            array (size=1)
              0 =>
                array (size=1)
                  'value' => string 'en' (length=2)
      ... (more fields)
      'field_image' =>
        array (size=1)
          'x-default' =>
            array (size=1)
              0 =>
                array (size=5)
                  'target_id' => string '1' (length=1)
                  'alt' => string '' (length=0)
                  'title' => string '' (length=0)
                  'width' => string '150' (length=3)
                  'height' => string '120' (length=3)

Now the field_image has an array with x-default and some basic image data. How do I show the image, or create a link to the image inside the Twig template?

Here is an update version of for this answer after 8.0.x. This base on @joelpittet comment.

{{ file_url(node.field_image.entity.fileuri) }}

You can do it in two ways!

1) file_create_url(---------) // inside write the path of node

2) file_url(-------) // inside write the path of node


iframe in - rewrite results - Override the output of this field with custom text I'm trying to make a view for showing latest youtube videos in a block

I have a field called Youtube Video ID (Plain text) where I Drupal 8 stores the ID of the video...

I'm using the option of the field "Override the output of this field with custom text" in REWRITE RESULTS...

I'm doing something like this:

Like you can see.. I'm using that mark up to show a youtube video.. taking the value of the field....

the problem is that Drupal is cleaning the iframe mark up.. I think for security...

this is how Drupal render it in the website

When you configure the content type you can see a note:

Allowed HTML tags:   <big>
 <q>      <tt>

This field supports tokens.

how can I add more allowed tags?

How can I allow that HTML tag for this view?
¡Thanks!

I have been wrestling with this as well but my users want to embed google docs.  Same concept though.

I figured out the solution and it's not super complicated.  You you just need to create a 'Field Template' in the theme.

This video covers the concept with 'Node Template' but you can easily apply it to the field template.

Drupal 8 Theming - Part 11 - Displaying Fields
https://www.youtube.com/watch?v=fQ6Ypik_jsE

It's been a while since this question has been asked, but in case someone searches for a solution for this problem and ends up here (like I did):

You can add the iframe-Tag to the Xss whitelist:

Open the file core/lib/Drupal/Component/Utility/Xss.php
Add 'iframe' to the $adminTags array

After refreshing the cache, iframe-Tags will no longer be stripped from your override text.


Add custom validation on views exposed filter block form I have one content type called Address. It has title, body, etc.. fields.
Initially Created view for Address.

Later client wants to add search field for this view.
So created exposed filter block for body field.

Now search block with results working fine.

But challenge is, we need MINLENGTH validation to that search field.

Added $form['#validate'][] = _custom_validate; in form_alter.

if ($my_field_length < 4) {
  form_set_error('my_field', t('Please enter minimum 3 characters.'));
}

First Question: This validation is happening on each page load but it is not triggering when we submit form (This is ajax form).
Second question: Is that any possible to stop validation or auto submit on intial page load?

There are many issues reported for this behavior on Drupal.org and Drupal Answers.

As a work around, you can try HTML5 pattern attribute to add minimum length validation, check example here.

Or add a small JS snippet to validate input field on blur event.


Overwrite field description in an image widget I have an image field (multiple).

In the node form, the ImageWiget has a process method that adds previews and form fields for images that have already been uploaded.

The description for the title tag is hard-coded on line 278: '#description' => t('The title is used as a tool tip when the user hovers the mouse over the image.'). We are actually showing the title as a caption and not a tooltip.

How can I override the description?

Using hook_field_widget_form_alter You can do this:

function MYMODULE_field_widget_form_alter(&$element, \Drupal\Core\Form\FormStateInterface $form_state, $context) {
  if ($context['field']['field_name'] == 'field_image_top') {
    // Loop through the element children (there will always be at least one).
    foreach (element_children($element) as $key => $child) {
      // Add the new process function to the element

      $element[$key]['#process'][] = 'MYMODULE_image_field_widget_process';
    }
  }
}

function MYMODULE_image_field_widget_process($element, \Drupal\Core\Form\FormStateInterface $form_state, $form) {
  // Change the title field label and description

 $element['title']['#description'] = 'SOME NEW DESCRIPTION HERE.';
 return $element;
}

Using a hook_form_alter() you will be able to change that '#description' inside the structured $form array.


Create personality quiz i'm looking for solution on how to create personality quiz. The Quiz module doesn't have an option to label answers - I need to find the most popular label checked and not the total amount of points.

It could be like this: 2 questions, 3 answers each. Each answer for each question has labels: "label one", "label two" and "label three" and they are randomized. I answer both questions and get "label two=2", which is the most popular label and therefore I am forwarded to node2 with some description.

Is it possible to do this with forms?

The webform module would work for you. It gives you a nice interface to fetch the results so you can do some meaningful post analysis on your results too.

Someone wrote a great module for it
Personality Test

This module allows you to easily create a personality test that visitors can take.
After you installed it a new node type becomes available, when you create a node of this type you can add questions and their possible answers; you can also define a score for each answer.


Get term ID of a field vocabulary in for templating I have a node template with various taxonomy fields and I'm trying to get the term ID of a specific vocabulary field to pass it through an url.
I have tried many function but I can't seem to find the proper one.
Can anyone help me on this ?

It sounds like you need to inspect your node.
You can do this with the vital devel module.

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

Once installed it will give you a few new tabs on your node page to see how the node is constructed when it is loaded using node_load($nid) and rendered using node_view($node).

In the node template itself, you will have access to the rendered node as per node_view($node) so anything you see in the devel modules render page you can print out in your node.tpl.php

Devel uses the excellent Krumo library to display PHP objects and array nicely, this is also accessible using dpm($object); however it can not be used in templates, but you can call krumo directly using krumo($node);

So in your node template, call krumo($node); to find the field you want, then once found add it to a variables $tid = $node->taxonomy[LANGUAGE_NONE][0]['tid']; and pass it to you link print l("taxonomy", "view/$tid");


How do I show a basic search block on the front page that integrates with search api? I've been creating my search pages in Search API, but I want to offer a search block on the front page or other pages that can do what the core search block does. Is there a way to either integrate the search block, or a work around to have a search block on the front page while it pulls up search and displays everything on the main search page?

Search API module has the ability to integrate with views module. All you need to do is to install views module and then create Search view,expose search filter and in your views configuration choose Exposed form in block option to yes, now you will the see the search block from your search api and place it on front page, the block will take you automatically to the search page to show the search items.


How to create the slideshow as the background slideshow using drupal 7? We are currently developing a single page responsive site in drupal 7.In our home page we tried implementing slideshow through view slideshow module (drupal 7). The slideshow is working perfectly fine. I want to know how to create a background slideshow using views slideshow?

You can try using the Vegas Background jQuery Plugin module.

  Vegas is a jQuery plugin to add beautiful fullscreen backgrounds and slideshows to your webpages.

Try out the module demo.

The Photo module is great but still alpha stage. Details from its project page:

  Photo is a photography and multimedia theme with a full screen slideshow. Showcase your important work, imagination with full screen photo slider. Photo is Drupal theme for photographic professionals, photo artist, amateur photographers to create photo gallery, portfolio with photos, video blogs. It is also useful for architecture, travel sites, hotels, restaurants, sculpture artist and for any purpose who want to emphasis on photos for the website.

Otherwise Write your own JS or add JS plugin to get this effect. With Jquery, anything is possible.


Minutes in date value displayed never the same as value entered I have a weird bug.  On many content types, I have a Date field using the Pop-up calendar widget with the format "February 3 2014 - 2:35".

When that date is displayed, the minutes are never the same as the minutes that I entered when I saved my content. If my date field has the time value 4:15, the time displayed will be 4:12. If I change the minutes again for let's say, 4:52, the time displayed is still 4:12. And when I edit that content, the time I entered is still there, so I know it's saved correctly. If I change the hour, that change is displayed properly but the minutes stay the same.

Also, when I check recent log messages, for a given hour, the minutes displayed are always the same. Like every event that happened between 2PM and 3PM has the time 2h02.

Does anybody know what the problem might be ?

I'm on Drupal 7.34 and using Date 7.x-2.8.

Well, turns out the discrepancy was due to a bad date format ... I was using "m" for the minutes instead of "i".

My bad !


How do I redirect access denied to front page? I asked this a while back and got nowhere. Sorry for the repost but it needs to be resolved (somehow).

If a visitor types in a URL for which they are not authorized, I do -not- want them to see a 403 page. I just want them to be redirected to the site home page.

I entered...

<front>

...in the 403 field under admin/config/system/site-information but that apparently does nothing. We're using LoginToboggan which (I think) overrides this.

How can I do this?

TIA,

Instead of <front> try using node or 'home page path' if you have customized home page.

...in the 403 field under admin/config/system/site-information.

Ref: Redirect 404 errors to home page?


How to make a clone of a website without contents I need to create a clone of one of my website.
It will be the same (modules, views, content types, template etc...)
I've already done once by coping everything and then deleting the contents and the users.
Is there the right way? I will need to do 3-4 copies of the website.
Is there any module that can help me(a part from backup and migrate) to do these copies? Should I create an kind of "distribution" enabling modules and creating content type, similar to the master one, from the scratch and then export the database?

If I do as I always did (clone and delete contents and users), how can I reset the content id?

Thanks in advance

I guess what your looking for is the features module http://drupal.org/project/features. When creating clones of websites, obviously all the code/themes/modules is easy to copy but the only way to get all your node types, fields, views etc... is in the database.

Features exports all this information as a module as you can just copy this to a new site along with all your other modules, enable it, and voila all your views content types etc..
In the features you can list modules as dependencies so when enabling your feature all the contrib/core modules you need are enabled aswell (they will ofcourse need to exist on your new area).

It intergrates fully with most the big contrib modules and from what I understand is exactly what your after. It can be daunting at first but dont worry its really very easy to use. The following video is for drupal 6 but the features interface is identical (as far as I remember) http://mustardseedmedia.com/podcast/episode43

There are other more complex ways to do what your after aswell using drush and creating build scripts, you can ever combine drush, build scripts and features. However I believe just normal features will do you fine.

After copying files and the DB, you can clean up the node and the users Table.

Dont forget to keep the admin user in the table.


Upgrading from 7.22 to 7.28, htaccess file in /tmp I get this error :

My .htaccess file in that directory looks like this now (I copied it from the url):

# Turn off all options we don't need.
Deny All
Options None
Options +FollowSymLinks

# Set the catch-all handler to prevent scripts from being executed.
SetHandler Drupal_Security_Do_Not_Remove_See_SA_2006_006
<Files *>
  # Override the handler again if we're run later in the evaluation list.
  SetHandler Drupal_Security_Do_Not_Remove_See_SA_2013_003
</Files>

# If we know how to do it safely, disable the PHP engine entirely.
<IfModule mod_php5.c>
  php_flag engine off
</IfModule>

I still get said error. Why?

Make sure your file system settings are set to /tmp or tmp, then...

In the tmp folder, select the htaccess and delete it from your FTP, then refresh your site cache.

Drupal will replace the missing .htaccess automatically.

As far as https://drupal.org/SA-CORE-2013-003; It suggests,

  To fix the code execution prevention vulnerability on existing Apache
  installations also requires changes to your site's .htaccess files in
  the files directories. Until you do this, your site's status report
  page at admin/reports/status will display error messages about the
  problem. Please note that if you are using a different web server such
  as Nginx the .htaccess files have no effect and you need to configure
  PHP execution protection yourself in the respective server
  configuration files.

  To fix this issue, you must edit or replace the old .htaccess files
  manually. Copies of the .htaccess files are found in the site's files
  directory and temporary files directory, and (for Drupal 7 only) the
  separate private files directory if your site is configured to use
  one. To find the location of these directories, consult the error
  messages at admin/reports/status, or visit the file system
  configuration page at admin/settings/file-system (Drupal 6) or
  admin/config/media/file-system (Drupal 7). Note that you should only
  make changes to the .htaccess files that are found in the directories
  specified on that page. Do not change the top-level .htaccess file (at
  the root of your Drupal installation).

  Go onto your server, navigate to each directory, and replace or create
  the .htaccess file in this directory with the contents described
  below. Alternatively, you can remove the .htaccess file from each
  directory using SFTP or SSH and then visit the file system
  configuration page (admin/settings/file-system in Drupal 6 or
  admin/config/media/file-system in Drupal 7) and click the save button
  to have Drupal create the file automatically.

  The recommended .htaccess file contents are as follows.

  For Drupal 6:

  Turn off all options we don't need. Options None Options +FollowSymLinks

  Set the catch-all handler to prevent scripts from being executed. SetHandler Drupal_Security_Do_Not_Remove_See_SA_2006_006

  Override the handler again if we're run later in the evaluation list.
  SetHandler Drupal_Security_Do_Not_Remove_See_SA_2013_003

  If we know how to do it safely, disable the PHP engine entirely.    php_flag engine off

  PHP 4, Apache 1.    php_flag engine off

  PHP 4, Apache 2.    php_flag engine off  For Drupal 7:

  Turn off all options we don't need. Options None Options +FollowSymLinks

  Set the catch-all handler to prevent scripts from being executed. SetHandler Drupal_Security_Do_Not_Remove_See_SA_2006_006

  Override the handler again if we're run later in the evaluation list.
  SetHandler Drupal_Security_Do_Not_Remove_See_SA_2013_003

  If we know how to do it safely, disable the PHP engine entirely.    php_flag engine off  Additionally,

  the .htaccess of the temporary files directory and private files
  directory (if used) should include this command:

  Deny from all


Remove reply link in comments How can you remove the reply button under each comment in Drupal 8? I understand there is an option "Show reply form on the same page as comments", but I am not trying to remove this form. Only the reply button.

How can the reply button be removed?

You could use the hook_comment_links_alter()

use Drupal\comment\CommentInterface;

/**
 * Implements hook_comment_links_alter().
 *
 * Unsets the "Reply" link of a comment.
 *
 * @param array &$links
 *   A renderable array representing the comment links.
 * @param \Drupal\comment\CommentInterface $entity
 *   The comment being rendered.
 * @param array &$context
 *   Various aspects of the context in which the comment links are going to be
 *   displayed, with the following keys:
 *   - 'view_mode': the view mode in which the comment is being viewed
 *   - 'langcode': the language in which the comment is being viewed
 *   - 'commented_entity': the entity to which the comment is attached
 */
function mymodule_comment_links_alter(array &$links, CommentInterface $entity, array &$context) {
  // Unset the "Reply" link
  if(isset($links['comment']['#links']['comment-reply'])) {
    unset($links['comment']['#links']['comment-reply']);
  }
}

The forms in Drupal 8 are entities, through the administration of the form you can manipulate the fields and in the presentation of the type of content you can show it, the button can be deleted from the entity of the comments.


How to change the title and add a placeholder to password and confirm password field through hook_form_alter? How can i remove the label of the password and the confirm password field through hook_form_alter functionality ?
Tried the below:

$form['pass']['#title']= t('');   $form['pass']['#description']=
t('');
$form['account']['pass']['pass1']['#attributes']['placeholder']=
t('Password');
$form['account']['pass']['pass2']['#attributes']['placeholder']=
t('Confirm Password');

But no change in the behavior.
This is the exact code that i have written in my .theme file.
   function THEMENAME_form_user_pass_reset_alter(&$form, &$form_state, $form_id) {
  // Get default process function array:
  $element_info = element_info('password_confirm');
  $process = $element_info['#process'];
  // Add our process function to the array:
  $process[] = 'port_process_password_confirm';
  $form['account']['pass']['#process'] = $process;
}

function port_process_password_confirm($element) {
  $element['pass1']['#title'] = t('New password');
  $element['pass2']['#title'] = t('Confirm new password');
  return $element;
}

The output that  i am getting is as per the below image

In D8 You can try the code below:

use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Render\Element\PasswordConfirm;

function mymtheme_form_user_pass_reset_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  $form['account']['pass']['#process'][] = 'mytheme_form_user_register_form_process_pass';
}

function mytheme_form_user_register_form_process_pass(&$element, FormStateInterface $form_state, &$complete_form) {
  $element = PasswordConfirm::processPasswordConfirm($element, $form_state, $complete_form);
  $element['pass1']['#placeholder'] = t('Password here please');
  $element['pass2']['#placeholder'] = t('Password again here please');
  $element['pass1']['#title'] = t("New password");
  $element['pass2']['#title'] = t("New password confirm");
  return $element;
}

See more PasswordConfirm.php

In D7

function mymtheme_form_user_pass_reset_form_alter(&$form, &$form_state, $form_id) {
   // #process handler to modify the password element expanded by Field API.
   $form['pass']['#process'] = array('form_process_password_confirm', 'register_alter_password_confirm');
}

/**
 * Alter password and confirm password fields to remove title and insert placeholder.
 */
function register_alter_password_confirm($element) {
    $element['pass1']['#attributes']['placeholder'] = t("Password");
    $element['pass2']['#attributes']['placeholder'] = t("Confirm password");
    $element['pass1']['#title'] = t("New Password");
    $element['pass2']['#title'] = t("New password confirm");
    return $element;
}

See more https://www.drupal.org/project/drupal/issues/540340#comment-2782800

The above solution worked for me but the problem was wrong function name. The solution that worked for me :

function THEMENAME_form_user_pass_reset_alter(&$form, FormStateInterface $form_state, $form_id){
    $form['pass']['#title'] = t('');
    $form['pass']['#description'] = t('');
    $form['pass']['#process'][] = 'test_form_user_register_form_process_pass';
    $form['actions']['submit']['#attributes'] = ['class' => ['registerbtn']];
}

function test_form_user_register_form_process_pass(&$element, FormStateInterface $form_state, &$complete_form) {
  $element = PasswordConfirm::processPasswordConfirm($element, $form_state, $complete_form);
  $element['pass1']['#placeholder'] = t('Password here please');
  $element['pass2']['#placeholder'] = t('Password again here please');
  $element['pass1']['#title'] = t("");
  $element['pass2']['#title'] = t("");
  return $element;
}