How do you run custom functions after Migrate class finishes an import? I have migrate classes to import useres, taxonomy, content, etc.  Some of these are being imported from a CSV source and need to be organized a little better either before or after an import.

How can I run custom functions before and after an import with the Migrate module?

For what you're asking (running a function prior to or after a single Migration) see the documentation for Less Commonly Implemented Migration Methods. They include:

function preImport()
function postImport()
function preRollback()
function postRollback()

Note this caveat from the documentation:

  NOTE: If you are running your migrations through the web UI, which
  chunks the work into batches, if a given migration takes long enough
  to be broken into separate batches, these functions will be called for
  each batch. They are called each time the migration is invoked, not
  just the first (or last, in the complete case).

If you don't like that behavior, then in your preImport() or postImport() simply use a static variable to see if your custom logic has already run once. Lullabot Posted a good blog entry on using drupal_static back in 2011 on this subject.

With regards to per-record migration completion (like moving 1 song from legacy data store to drupal -- 1 "row" of a migration) take a look at the documentation for Commonly Implemented Migration Methods. They include:

function prepareRow($row)
function prepare($entity, stdClass $row)
function complete($entity, stdClass $row)
function createStub()


How can I force the user to register/login first before being redirected back to the current URL? I'm displaying a form using the Form API under a given URL. User gets this URL and accesses it. But before the user fills out the form, they need to be registered or logged in.

How can I send the user to the login page, or present the login form, then subsequently direct them back to the form under the given URL?

This is not a Webform -- I'm using the Form API.

Redirect to the login page and provide a destination query parameter to the current route to redirect back after login:

  public function buildForm(array $form, FormStateInterface $form_state) {
    if ($this->currentUser()->isAnonymous()) {
      return $this->redirect(
          'user.login',
          [],
          ['query' => ['destination' => Url::fromRoute('<current>')->toString()]]
      );
    }

    // build form

    return $form
  }

Don't forget to add a use Drupal\Core\Url; statement to the class.


Restrict node for anonymous user programmatically First of all I've seen lot's of threads about restriction, but didn't find what I'm looking for.

So, my goal is to restrict the access for a specific node to anonymous users and when they try to enter that node, it will redirect them to the user/login page.

I was using Content Access module till now. It works like it should, but the problem is when this module is enabled, block caching is not working. As I know the Context module has the same issue.

I have one big menu block and without caching, the website is 4 times slower. When the Content Access module is disabled, the block is cached and the performance is great.

Let's say the url of the page is 'apple'.

I'm looking for a way to restrict only this page programmatically, without breaking the block caching.

I'm using Drupal 7.

hook_init:

<?php
// Get the current active node object if present.
$node = menu_get_object();
// Redirect to login page if NID == 42 and user is anonymous.
// User will then go back to node page due to destination being set.
if (   user_is_anonymous()
    && !empty($node)
    && !empty($node->nid)
    && $node->nid == 42
    ) {
  drupal_goto('user/login', array('query' => array('destination' => 'node/' . $node->nid)), 307);
}
?>

hook_boot:

<?php
$args = arg();
if (   user_is_anonymous()
    && isset($args[0]) && $args[0] == 'node'
    && isset($args[1]) && is_numeric($args[1])
    ) {
  drupal_goto('user/login', array('query' => array('destination' => 'node/' . $node->nid)), 307);
}
?>


Retrieving customer information to use in drupal commerce payment module I'm new to drupal development and am programming a payment module for the new drupal commerce module.  It's will be a basic api module that allows the user to stay on the site and makes a separate curl call to send the data and use the response to indicate success or failure.

I copied the authorize.net aim payment module and have so far gotten to a point where I'm correctly posting the information that's being sent using the authorize module.  However the payment system I'm using requires the customer name and billing address and I'm not sure about how to go about gathering that information.  I know in the order there is a user/customer profile id but I don't know how to get any other information about the customer.  I do know that the billing address is gathered, it just isn't sent to authorize.

The customer profile is attached to the order, and it has an address field that holds the information. To get it you could do;

$order_wrapper = entity_metadata_wrapper('commerce_order', $order);
$address = $order_wrapper->commerce_customer_billing->commerce_customer_address->value();
$postal_code = $order_wrapper->commerce_customer_billing->commerce_customer_address->postal_code->value();
...

It's a lot simpler to use the entity metadata wrapper as shown above. What it does is that it loads the customer profile entity for you and let you access it's field.


EntityQuery not returning content based on language I'm trying to get a list of all of a specific content type, but my entityQuery is only returning the original language of the site (English). Here's my code:

  public function fetchDocumentReferenceOptions() {
$language = \Drupal::languageManager()->getCurrentLanguage()->getId();
$query = \Drupal::entityQuery('node')
  ->condition('status', 1)
  ->condition('type', 'document')
  ->condition('langcode', $language)
  ->sort('title', 'ASC');

$nids = $query->execute();

$nodes = node_load_multiple($nids);

$options = [];

foreach($nodes as $node)
{
  // check if the document (content type) has an uploaded file
  if ($node->field_document->entity) {
      $options[$node->id()] = $node->getTitle();
  }
}

return $options;

}

This is how I call the function:

'#options' => $DocumentReferenceCore->fetchDocumentReferenceOptions(),

What I am expecting, based on condition for langcode would be that, if, for example, I am editing a Chinese language node (translated from the original English node), I should see Chinese nodes, and the content being returned, but instead I am still seeing the original English content.

What am I doing wrong here?

Content entities have an active language concept. If load them, they by default return values for the default translation.

With your query, you know it has that translation, so you can do $node = $node->getTranslation($language);. If you're not sure it exists, you can use $custom_tag = \Drupal::service('entity.repository')->getTranslationFromContext($node, $desired_langcode);. That will return the node in the matching translation if it exists, or the best alternative. You can also leave out the langcode, then it defaults to the current content language.


How do I add the tertiary level from the main menu to my skin? Let's say I have the following menu:

Smartphones

Android

LG Nexus 4
Samsung Galaxy Note 2
HTC One
Motorola Droid RAZR MAXX HD

iOS

iPhone 4
iPhone 4S
iPhone 5

Windows Phone

HTC Windows Phone 8X
HTC Windows Phone 8S
Nokia Lumia 920
Nokia Lumia 820

I want a menu that will display all the third level items if I'm on the parent node.  So, if I'm on the Android page, I should see LG Nexus 4, Samsung Galaxy Note 2, HTC One, and Motorola Droid RAZR MAXX HD.

The only recommendation I keep seeing is to use the Menu block module, but I want to just create the menu myself in PHP.  How?

I figured it out.  In template.php, I added the following function:

function MYTHEME_preprocess_page(&$variables) {
    $active_tree = menu_get_active_trail();
    $parent = array_pop($active_tree);
    if($parent['depth'] == 3) {
        $parent = array_pop($active_tree);
    }

    $parameters = array(
        'active_trail' => array($parent['plid']),
        'only_active_trail' => FALSE,
        'min_depth' => 3,
        'max_depth' => 3,
        'conditions' => array('plid' => $parent['mlid']),
      );

    $tertiary_menu = menu_build_tree($parent['menu_name'], $parameters);

    $links = array();
    foreach($tertiary_menu as $branch=>$link) {
        array_push($links, $link['link']);
    }

    $tertiary_links_vars = array(
        'links' => $links,
        'attributes' => array('class' => array('sub-nav')),
        'heading' => array(
            'text' => t('Tertiary menu'),
            'level' => 'h2',
            'class' => array('element-invisible'),
        ),
    );

    $variables['tertiary_menu'] = theme_links($tertiary_links_vars);
}

In my page.tpl.php file, I added the following:

<?php print $tertiary_menu; ?>


How do I disable Commerce cart order refresh to preserve custom prices on line items? The goal is to allow the user to select the quantity they want, hit Add to Cart, then have the script separate the Line Item into individual Line Items with the Quantity of 1. I have accomplished this using Rule which works great but we also use Commerce Pricing Attributes which allows you to alter the price of a product before adding to cart. The altered price does not carry through to the split Line Items using this Rule. My script so far does keep that price.

This works for the first time the cart is loaded. The second time the cart is loaded, the original price is not applied to the added line items. Instead they remain in tack but get their default price applied.

Here is the shopping cart when it's first loaded after clicking the Cart link in the popup message. Everything appears OK with price across all items.

Here is what it looks like when I refresh the page, update cart, proceed to next step - pretty much anything that will trigger the commerce_cart_order_refresh().

As you can see the original item retains it's altered price, but the others that were added now default back to their original price.

Here is my code:

function ces_line_items_commerce_cart_line_item_refresh($line_item, $order_wrapper){
    // set the global user
    global $user;
    // load the entity wrapper of the line item
    $line_wrapper = entity_metadata_wrapper('commerce_line_item', $line_item);
    // get the quantity of the line item
    $quantity = (int)$line_wrapper->quantity->value();
    // get the product id to use later
    $product_id = $line_wrapper->commerce_product->product_id->value();
    // set the altered price or current price of line item
    $newPrice = $line_wrapper->commerce_unit_price->amount->value();
    // get the original line item
    $old_line_item = $line_wrapper->line_item_id->value();
    // load the original line item -- need to do this for rewriting later
    $original_line_item = commerce_line_item_load($old_line_item);
    // set our index
    $i = 1;
    // only do the following if the original line item has a quantity above 1
    if($quantity > 1){
        // loop until we are 1 below quantity
        while($i < $quantity) {
            // it the product can be loaded
            if ($product = commerce_product_load($product_id)) {
                // create new line item
                $new_line_item = commerce_product_line_item_new($product, 1, $order_wrapper->order_id, $original_line_item->data);
                // make sure to include any additional price calculations
                drupal_alter('commerce_product_calculate_sell_price_line_item', $new_line_item);
                rules_invoke_event('commerce_product_calculate_sell_price', $new_line_item);
                // reload the line item
                $new_line_item = commerce_cart_product_add($user->uid, $new_line_item, FALSE);
                // set unit price
                $new_line_item->commerce_unit_price['und'][0]['amount'] = $newPrice;
                // set base price
                $new_line_item->commerce_unit_price['und'][0]['data']['components'][0]['price']['amount'] = $newPrice;
                // set base total amount
                $new_line_item->commerce_total['und'][0]['data']['components'][0]['price']['amount'] = $newPrice;
                // save new line item
                commerce_line_item_save($new_line_item);
                // add line item to order wrapper
                $order_wrapper->commerce_line_items[] = $new_line_item;
            }
            // increment our index
            $i++;
        }
    }
    // alter line item quantity back to 1
    $original_line_item->quantity = "1.00";
    // save line item
    commerce_line_item_save($original_line_item);
}

So what I need is the ability to disable commerce_cart_order_refresh from trying to default everything back.

You're approaching the problem incorrectly here. You shouldn't be trying to disable the cart order refresh. That includes things like discounts, taxes, etc. that may actually need to be applied to line items on the order in the future.

Instead, you should find a strategy to enrich the line item with the information it needs to reset the price to the proper custom price during the pricing process. This is the approach utilized in our old donation examples where customers can enter custom prices to donate:

https://drupalcommerce.org/videos/tutorials/donations-custom-line-item-types

I have no experience with the module you're using, so I can't say how to keep working within the framework it provides. Generally speaking, though, you could make this work by adding a price field to the line item called "Custom price" or something and then creating a pricing rule that sets the unit price of line items to the custom price at the appropriate point in time.

Alternately, you could store the necessary information in the data array of the line item, but then you'd still need a product pricing rule with a custom action that knows how to inspect the data array and reset the unit price to the appropriate amount.


"Add an item to a list" using rule just works for plain text I created a rule with an action which "Add an item to a list".
The value of the item to add is this (also see my picture bellow)

Voucher: [node:title].
The code for this voucher is [codigo-otorgado:value].
View the voucher: [node:url]

This item will be added to a field of the user which I created at admin/config/people/accounts/fields The details of this field are:

Name: My voucher codes
Type: Long text
Widget: Text area (multiple rows)
Text processing: Plain Text
Number of values: Unlimited

So far so good. When the rule is fired all is working right, but The problem is that the text is shown as plain text. As you can see there is a url and breaks lines that I need to print out.

I guess the first suggestion will be to change the Text processing of the field  to Filtered Html or Full Html, and so I did.

But then the tokens ([node:url], [node:title]..) inside the value doesn't work. The tokens are printed as it, instead of their values.

I know that Rules is very mature module and I'm sure there must be a way to do this. What am I missing here?

You have saved your textarea field as Plain text, change it to Filtered Text (in Text formats admin settings you should check allowed tags):


Clean URLS work with http, but not with https When I visit ?q=admin/config/search/clean-urls via HTTP I am able to enable clean URLs and they work fine.

However, when I visit the same path via HTTPS I am not able to enable clean URLs and get this error:

Here is my apache conf file for http:

NameVirtualHost *:80

<VirtualHost *:80>

    UseCanonicalName Off
    ServerAdmin webmaster@localhost
    DocumentRoot /media/www_drive/drupal7

  <Directory /media/www_drive/drupal7>
    Require all granted
    AllowOverride All
  </Directory>

</VirtualHost>

Here is my apache conf file for https

NameVirtualHost *:443
<VirtualHost *:443>

    SSLEngine on
    SSLCertificateFile /etc/ssl/cgps/star.cgps.org.crt
    SSLCertificateKeyFile /etc/ssl/cgps/np_cgps.key
    ServerAdmin webmaster@cgps.org
    DocumentRoot /media/www_drive/drupal7
    SSLCACertificateFile /etc/ssl/cgps/RapidSSL.crt

    <Directory /media/www_drive/drupal7>
      Require all granted
      AllowOverride All
    </Directory>

</VirtualHost>

Shouldn't this config use the same .htacess file in the drupal root for both HTTP and HTTPS? What could cause clean URLs to fail to pass the check via HTTPS?

You can try below with changing in .htaccess file:

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}


How to add phone number field to simplereservation/add page I have installed the simplereservation module. I can add a reservation by visiting xxx.com/simplereservation/add page. I do not see phone number field on that page. How to add phone number field to the add page?

I think comment field is needed. I copied the comment form and pasted there. Then I edited the form for phone number as below:

  $form['phone'] = array(
    '#type' => 'textfield',
    '#size' => 50,
    '#title' => t('phone'),
    '#default_value' => $reservation["rcomment"],
    '#description' => t('You can add a phone for your reservation.'),
  );

When I go to simplereservation/add page, I do see the comment, phone number field plus other fields. However, after I enter the reservation info plus the phone number, I click Save this reservation. On the reservation page, I see other info except the 'phone number' + 'this reservation is for'. How can I see the phone number on the reservation page?

I have not learned how to use hook yet.

I did look at the simplereservation.install file and i saw how comment filed is defined in simplereservation_schema(). I simply copied the comment code and modified for phone field as below:

 'rcomment' => array(
    'description' => 'Text comment that accompanies the reservation',
    'type' => 'varchar',
    'length' => 255,
    'not null' => TRUE,
    'default' => '',
  ),
    'phone' => array(
    'description' => 'phone no of customer',
    'type' => 'varchar',
    'length' => 25,
    'not null' => TRUE,
    'default' => '',
  ),

I still see the phone field add page not on the reservation page.

In sr.module > i have added

$form['phone'] = array(
'#type' => 'textfield',
'#size' => 50,
'#title' => t('phone'),
'#default_value' => $reservation["myphone"],
'#description' => t('You can add a phone for your reservation.'),

);
In sr.install

'phone' => array(
'description' => 'phone no of customer',
'type' => 'varchar',
'length' => 25,
'not null' => TRUE,
'default' => '',

),
Disabled the module > Uninstalled the module > Cleared the cachse > Enabled the module > Created 2 items bc items were gone.
xxx.com/sr/add

Error:
Notice: Undefined index: myphone in
simplereservation_add_edit_form() (line 545 of ..../sites/all/modules/simple_reservation/simplereservation.module).

line 545:

   '#default_value' => $reservation["myphone"],

Please advise.

I think if you don't want to edit module, you may use comment field for telephone number. It's much easier to customize comment label and change it to phone number, than to edit module's code for additional field to store in database and display in form. Anyway it will be your preference.

UPD: tried to do something. If you don't need user comment, you can change Comment label, make it required field, and change description. (better solution is to try alter form)

Result:

Where to replace code in sites/all/modules/simple_reservation/simplereservation.module:

You just can compare lines from original and my example.


Get the user location during registeration process I am developing a drupal site along with the mobile application.
I want to store the latitude , longitude of the user who registers in my site...
I can see there are many location based modules available but i want to use the one which affers the map ui on the registeration form and the user types
in its address and through reverse geocoding i could fetch the latitude and longitude of that place.

Basically i need location module during registeration form
Thanks

In Drupal 6, the obvious answer would be use the Location and Gmaps or OpenLayers module. I've used it on many many sites and it generally works well. Another very good alternative in Drupal 6 that I just found now is HTML5 user geolocation, that looks awesome and its what drupal.org uses!

However if I was using Drupal 7, I would definitely use the Geolocation Field module. I've tried it out and its really awesome and easy for users.


Get the list of all content types How do I get a list of all the content types defined in a Drupal 8 site?

In Drupal 7 it used to be node_type_get_types(), but it has been deprecated.

I tried Entity::loadMultiple() but it doesn't seem to work. I was thinking about making a custom query, but I don't know how it's stored in the database.

loadMultiple() should be fine for this:

$types = \Drupal::entityTypeManager()
  ->getStorage('node_type')
  ->loadMultiple();


How to reorganize drupal sites/all/modules structure without symbolic links? Context:

As the number of modules used increases, I try to reorganize modules in /***/sites/all
into

sites/all/modules/contrib
sites/all/modules/custom
sites/all/modules/dev

subfolders as it is described here (1) and now I use a solution similar to what was answered here (2)

Question:
Is possible to use path variable or another solution instead of creating symlinks for each contrib module?

I don't want to create so many symbolic links for each of contrib modules separately.

How to explain to Drupal the sites/all/modules structure the way I don't get bootstrap.inc errors such as:

Error: require_once(): Failed opening required
'/***/sites/all/modules/entity/includes/entity.inc'
(include_path='.:/usr/local/php5/lib/php') in
/***/includes/bootstrap.inc, line 2935

The Registry Rebuild module really is the answer. I struggled to solve this problem for hours, then this module fixed it completely, and with elegance!


Where can I set cardinality for a custom field? I have a custom field defined in a module I am writing, which works correctly. The default cardinality is unlimited and I want to limit it to 1.
I am sure I need to call setCardinality(FieldStorageDefinitionInterface::1) somewhere, but I can't understand where exactly I should add that call.

Yes, you can limit a custom field to single value by defining a cardinality in the annotations of the field type.

I don't know if you can find this in the docs, but you can use the core comment field as example:

/**
 * Plugin implementation of the 'comment' field type.
 *
 * @FieldType(
 *   id = "comment",
 *   label = @Translation("Comments"),
 *   description = @Translation("This field manages configuration and presentation of comments on an entity."),
 *   list_class = "\Drupal\comment\CommentFieldItemList",
 *   default_widget = "comment_default",
 *   default_formatter = "comment_default",
 *   cardinality = 1,
 * )
 */
class CommentItem extends FieldItemBase implements CommentItemInterface {

When you add a comment field to a content type the cardinality form element is hidden and instead this message is displayed:

  Allowed number of values

  This field cardinality is set to 1 and cannot be configured.


Is there a way to update custom packages with composer? The project is using Drupal 8 composer template to manage dependencies. Some of the packages are defined locally to look like Drupal modules and be installed in a specific location.

An example could be found here

The issue is that Composer does not store the data about these packages and their version within the .lock file. This means that there does not seem to be a meaningful way to update those custom defined modules with composer itself.

Is there a better way than just writing some custom script, probably relates to some post install procedure that would just visit all of the subdirectories that could possibly be these custom modules and would issue the git pull? Or is there a way to just force composer to reinstall these packages on each composer install run?

We fully control the codebase for these packages/modules and master branches should be safe to use.

You do this with requiring the Composer Merge Plugin in your Drupal project's composer.json and then define in which additional locations it should look for composer.json files to be merged.

  Composer Merge Plugin is intended to allow easier dependency management for applications which ship a composer.json file and expect some deployments to install additional Composer managed libraries. It does this by allowing the application's top level composer.json file to provide a list of optional additional configuration files. When Composer is run it will parse these files and merge their configuration settings into the base configuration. This combined configuration will then be used when downloading additional libraries and generating the autoloader.


How to let the admin select multiple users Probably something like that table with checkbox in people menu. Is there something like that in drupal, some API for creating this type of table? It needs to have pager, because i can't load all users. Is there any way, how to achieve this, or i need to do it by my self?

You can use Views and Views Bulk Operations modules.

You create a new view of users and you specify which bulk actions you allow to be performed.


Add/remove roles after submitting a certain webform I know that we can achieve this via Rules but unfortunately, there are some known issues that prevent Rules in Drupal 8 to add a role properly.

So I was wondering if it would be possible to programmatically add and remove some roles to an authenticated user after submitting a webform.

For now, I'm simply trying to add a role called styled to the logged-in user, So I created a 'Webform Handler' called webform_handler_role and added that to the webform through UI, but I still can't get it to add the role using the following code (Also note that I have Ajax enabled for the webform):

<?php
namespace Drupal\webform_handler_role\Plugin\WebformHandler;

use Drupal\Core\Form\FormStateInterface;
use Drupal\webform\Plugin\WebformHandlerBase;
use Drupal\webform\WebformSubmissionInterface;

/**
 * Webform submission action handler.
 *
 * @WebformHandler(
 *   id = "userrole",
 *   label = @Translation("User Role"),
 *   category = @Translation("User Role"),
 *   description = @Translation("Adds a user role after submission"),
 *   cardinality = \Drupal\webform\Plugin\WebformHandlerInterface::CARDINALITY_UNLIMITED,
 *   results = \Drupal\webform\Plugin\WebformHandlerInterface::RESULTS_PROCESSED,
 *   submission = \Drupal\webform\Plugin\WebformHandlerInterface::SUBMISSION_OPTIONAL,
 * )
 */
class UserRoleHandler extends WebformHandlerBase {

  /**
   * {@inheritdoc}
   */
  public function postSave(WebformSubmissionInterface $webform_submission, $update = TRUE) {
    $user = \Drupal::currentUser();
    $user->addRole('styled');
    $user->save();
  }
}

And after the form submission I end up with the following error:

  "Error: Call to undefined method Drupal\Core\Session\AccountProxy::addRole() in Drupal\webform_handler_role\Plugin\WebformHandler\UserRoleHandler->postSave() (line 28 of /modules/custom/webform_handler_role/src/Plugin/WebformHandler/UserRoleHandler.php).")."

\Drupal::currentUser() loads only an Account, but you need a fully loaded entity to modify and save the user:

$account = \Drupal::currentUser();
$user = \Drupal\user\Entity\User::load($account->id());
$user->addRole('styled');
$user->save();


How to show form elements within PDF by print module? I'm using the print module to convert a node to a PDF. I see that there is the print.tpl.php for theming, but where can I say that I want to show form elements (eg. input fields, radiobuttons, ..) within the PDF?

Not sure if this is exactly what you mean but you can show / hide elements via the ui.

go to admin/structure/types/manage/your-content-type/display
Under Custom Display Settings enable Print
admin/structure/types/manage/page/your-content-type/print

This will show or hide form elements for the pdf version as well as the print version.


Handling uploaded resources for local development With our Drupal site we develop locally, commit to svn and deploy to the live site. Some content gets uploaded on the live site (some images, videos etc). I am trying to sort out the best way to handle those uploaded resources.

Currently, we do daily database dumps, and use those for local development, but if someone has edited a page and added an image, it will 404 on the local since the image doesn't exist.

I rsync content down, but not all the team has ssh access (security). Should I tar up the uploaded assets at the same time as the database dumps? Or, is there a better way to handle this?

Basically; Whats the best way of getting uploaded content, for local development?

Yes your database and files need to be kept in sync to avoid 404s as you describe.
With our setup all developers have access to a backed up copy of the database and files. The backups of both database and files are synchronised so together they're essentially a snapshot of the production site. I personally use a collection of Drush commands wrapped up in a shell script in order to restore this snapshot to my local machine.


How can I render HTML tags in a variable in a twig template? I have a variable in my twig template called description.
The variable is a string with an html em tag in it. When I go to the webpage to view the field, the html em tags are stripped out of the string.
I am on a Drupal 8 site and my variable was rendered through
\Drupal::service('renderer')->render() The twig autoescape parameter is set to false.

Using the twig debugger, I can see that my markup object includes the html em tags so I know that the problem is how twig is processing the string.
I've read in other posts to use the |raw tag but this has no effect.
What can I do to make the HTML in my twig variable render properly?

Update: I've included a screenshot of my output from {{ dump(description) }}

my variable was rendered through
  \Drupal::service('renderer')->render()

Don't do that - Drupal sets Twig up to understand render arrays. Just use:

{{ original_description_render_array }}


How do I access $_SESSION in a view? Let's say I want to use $_SESSION['user_variable'] with a view as a filter value. I read that in Drupal 7 I could add such a value with custom PHP code. How should I do in Drupal 8? I didn't find an easy solution so far.

Would it be better to temporarily save a user's choice that is valid for the whole session in the database and tell the view to get the value from there?

In case this might be helpful for other (beginners): Using the session object in a custom controller class with dependency injection.

Drupal\user\PrivateTempStoreFactory;

class mymodule_Controller extends ControllerBase {

  /**
  * The user's private $tempStore object.
  *
  * @var \Drupal\user\PrivateTempStoreFactory
  */
  protected $tempStore;

  public function __construct(PrivateTempStoreFactory $temp_store_factory) {
    $this->tempStore = $temp_store_factory->get('mymodule_name');
  }

 /**
 * {@inheritdoc}
 */
 public static function create(ContainerInterface $container) {
   return new static(
     $container->get('user.private_tempstore')
   );
 }

 // Now get and set values in tempstore
 public function foo() {
  $foo = "xyz";
  // Set a session object "bar" and give it value $foo
  $this->tempStore->set('bar', $foo);

  // Get the 'bar' object from the session object.
  $value = $this->tempStore->get('bar');
 }

}


Created variations for products (error) Good evening, I created variations for products and when I add references to the display product, I get the following error "error message The Data 1 uses tokens (tokens) following invalid: [node : field-product: commerce_price] ".
Look at the setting in the screenshot below

Since you're using a field with multiple options, you need to use a delta. So if your token looks like this:

node:field_product:commerce_price

It should include a delta after the field name:

node:field_product:0:commerce_price


How do I create a page using Views and Drupal Commerce, where every listed term is a search term? I am setting up a site using Drupal Commerce, for an online medicine store. I need to create a Views display page that displays around 30 product titles, (maybe chosen randomly and) arranged alphabetically. The challenge, however is that each of the displayed titles, when clicked, leads to a search results page, which then displays all products that have the title as part of their name. The display page is similar to the following link:

http://www.progressiverx.com/store/prescription-otc.php

If you will click on any of the displayed medicine names, you will see the search results page that I am talking about.

I am not sure if there is a specific module or some configuration/logic that I can use to achieve the same using Views. Any help will be deeply appreciated. Thanks in advance.

Assign taxonomy terms (e.g. Flomax) to products, then display those terms in your view. Clicking on a term displays the term's page, with all its associated products.


How do I get the requirements in a module's composer.json merged into the consolidated composer.json? I am trying to use composer correctly to install a library named nikic/php-parser.

Thanks to helpful comments by Clive, I now understand that when a Drupal 7 module comes with a composer.json file, that file is supposed to be merged into a consolidated composer.json-file, and from then on things will be taken care of more or less automatically.

That things are supposed to work that way also follows from this note on the Composer Manager project page:

  Composer Manager allows each contributed module to ship with its own
  composer.json file, listing the module-specific requirements. It then
  merges the requirements of all found modules into the consolidated
  composer.json file. This results in a single vendor/ directory shared
  across all modules which prevents code duplication and version
  mismatches. [My emphasis.]

The Drupal site where I use for testing is a fresh install of Drupal 7, organized as Drupal 7 is normally organized when you install it using drush (drush si standard).

The Composer Manager package contains a composer.json with the following requirement:

"require": {
    "php": ">=5.3.0",
    "nikic/php-parser": "^4.2"
}

I have the Drupal variable composer_manager_vendor_dir set to sites/all/vendor and the composer directory for the consolidated composer.json is set to  /sites/default/files/composer.

The consolidated composer.json currently contains:

{
  "require": {
    "symfony/yaml": ">=3.1",
    "php": ">=5.3.0"
  },
  "config": {
    "autoloader-suffix": "ComposerManager",
    "vendor-dir": "../../../all/vendor"
  },
  "prefer-stable": true
}

I.e., it does not include a requirement for nikic/php-parser. The note from the project cited above seems to imply that it would somehow be merged in automatically.  This is yet to happen on my test site.

Following up another hint by Clive, I ran:

drush composer-manager install

This resulted in:

Loading composer repositories with package information
Installing dependencies (including require-dev) from lock file
  - Installing symfony/yaml (v3.1.0)
    Downloading: 100%
Generating autoload files

I.e. it did the updates that was required per the consolidated composer.json. But it did not pay attention to the composer.json in the module's directory.

Trying:

drush composer-manager update

... did not resolve the issue.

There must be something fairly obvious I am missing.

How do I get the requirements in a module's composer.json merged into the consolidated composer.json (apart from splicing it in "by hand")?

I think I've figured it out.

This is supposed to happen automatically. If the module is enabled with drush under Drupal 7, it does.  If you use other means to enable, the module, this might not happen.

In case the root composer.json for some reason is missing
the requirements for a specific module, using drush to disable and then again re-enable the module fixes the problem.  E.g.:

drush dis composer_manager -y
drush en composer_manager -y

This seems to be all that is required.

It should be emphasised that this is only valid for Drupal 7. Drupal 8 is a completely different beast.


How to make a list of all nodes of content type ABC on a site (not a sitemap)? I have a D8 website with about 100 landing pages for a Google Ads campaign.  All of my landing pages are of content type landing page.

I want to make sure that the cache is primed for these pages because Google penalizes the site ("below average landing page experience") if it takes too long to load.

It seems like the standard approach to doing this is to run wget over your sitemap: https://swsblog.stanford.edu/blog/xml-sitemap-and-cache-priming

But, the landing pages aren't in my sitemap because they are too similar to each other.  So, what should I do to get a list of the URLs of all of my landing pages?

Of course you can use Views (d'oh!) to do this.

Just make a view of content type landing page showing fields and then add a link to content and check the box for show URL as text.


How to access image style url from jQuery code? image_style_url() generates proper links, but sadly it's only a PHP function.

Let's assume I want to substitute file icon with preview image on hover:

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

      $('.form-managed-file', context).on('hover', function(){
        $(this).find('img').attr('src', $(this).find('a').attr('href'));
      });

    }
  };
})(jQuery);

Not the smartest code in the world, but simple, works and illustrates my example. Now, it will show image in the resolution user uploaded. But I need a thumbnail. It's a built in style so I don't need to test if it exists, but I do need valid security token and I need to respect all the Drupal file system settings, just like image_style_url() does. How can I achieve this with jQuery?

Note: In my case both input and output need to happen on jQuery side, as the image may not even be on the server when page is rendered.

For a single image style, I tack it on as a data attribute to the image.  Then in my JS, I use that.

This is how I handle retina images, using src switching (edited to just show the relevant portions):

function MYTHEME_image_style($variables) {
  // ...

  if (in_array($variables['style_name'] . '_2x', array_keys(image_styles())) {
    $variables['data-retina'] = image_style_url($variables['style_name'] . '_2x', $path);
  }

  return theme('image', $variables);
}

/**
 * Implements theme_image().
 */
function MYTHEME_image($variables) {
  // ...

  if (isset($variables['data-retina'])) {
    $attributes['data-retina'] = file_create_url($variables['data-retina']);
  }

  return '<img' . drupal_attributes($attributes) . ' />';
}

This in the JS (again, lifted and edited):

$('img').each(function (i, img) {
  var $img = $(img);

  if ($img.data('retina')) {
    $img.data('src', img.src);
    img.src = $img.data('retina');
  }
});

The key is to generate the style URL on the server side, so that the URL includes the itok and that all hooks get fired to allow modules like CDN to work.  You just need to figure out the proper place to do it from.  In your case, I suspect you may need to do it from a theme_field.


Save boolean data types in serialized array I'm writing a CRUD front end application that talks to a hand-written Drupal endpoint. The data I'm pulling from the database is serialized in one field, or cell. It comes out as a keyed array.

One of the actions a user can do is to set a value true/false. The problem I'm running into is that when I send that data to the database from Javascript, it's coming in as a string:

 request.post('/my-api/save/' + id )
  .set('Content-Type', 'application/json')
  .send('{"' + prop + '":"' + val + '"}')

And when it's serialized and saved the the database val is written as a string. The problem is when val it is equal to "false." I'm using drupal_write_record to save the array. When this comes back to the front end, it's still a string, which in Javascript gets coerced to true.

What I'm struggling with is how/where to turn that string into a boolean. I'm guessing I should be doing this on the save action, but maybe there's a Drupal specific way to do this.

I'm doing this to the incoming json at the moment, I don't like it but it works for now.

$received_json = file_get_contents("php://input",  TRUE);
$json = drupal_json_decode($received_json);
foreach($json as $key => $val) {
  // Typecast the "false" string
  $json[$key] = $val === 'false' ? (bool) FALSE : $val;
}

This would be much easier to do on the client side. Assuming val is your boolean value, you can just add a single line to handle this:

val = +val;

That will coerce your boolean to an integer (1 or 0). No need to check all of the json data on the server side.


Views expose filter with ajax showing validation message after reloading page? I added a date filter that showing select list for year and month. I created the block type view. When I select the month and submit the form it makes the red border outside the year. But when I reload the page or go to another page it gives me the error :

Please choose a year.

How to show error message at the time of form submit?

Any Solution???

Disable the Ajax for exposed filter, It will show only the message on form submit.


Stop Youtube when changing between tabs (Quicktabs) I am trying to stop a Youtube video when I change between tabs using QuickTabs but the video is still running, even in the iPad, I can even play the both videos, in this case Trailer and Full Movie at same time.

By the way, I am using the vanilla Youtube iFrame.

I think this post should help you: https://stackoverflow.com/questions/1094397/how-can-i-stop-a-video-with-javascript-in-youtube.

As @Pan Chrono said, it's not a drupal related question, more a youtube one.

What you basically need is:

change the way the youtube video is embed. It's actually using an iframe, you need a "embed" tag.
add "enable_js=1" to your URL so you can use Youtube Api
add a custom JS file to your page, and do some little jQuery code so that the video is stopped (with var myPlayer = document.getElementById('playerid'); myPlayer.stopVideo();) when you click on one of your tab


Customised user registration / sign-up forms in Drupal 7 I want to have 2 customised registration/sign-up form for different users with different fields for their account and profile (like buyer and supplier). How to make different form or multi step form for each kind of user based on role.

How can it be accomplish? Please help in this regard. As after lot of search, i could not figure it out. Is there better approach which is being used then please let me know.

When you need different set of fields for different users you should have a look at the profiles 2 module. There's a good chance that you can acomplish your requirements without any coding.

BTW: This kind of question has been asked many times here. The search functionality will give you a lot of information about this topic.


How can I check if an image style for an image has been created already? Is there a function I can use to check if a particular image style for a given image has been created already?

I couldn't find one in the core files but fortunately it's pretty straightforward to implement:

function image_style_path_exists($style_name, $path) {
  $uri = image_style_path($style_name, $path);
  return file_exists($uri);
}

Assuming you have a file object you would call it like this:

$image_exists = image_style_path_exists('thumbnail', $file->uri);

If you only need to use it once in the site you could boil it down to:

$image_exists = file_exists(image_style_path('thumbnail', $file->uri));

but it's usually better to separate this sort of thing out into a function


Add column to custom field schema I have created a D8 custom field that extends FieldBaseItem. It is already in use storing data.

How do I get the schema updated in the database, for an existing field?

What I've done:

I have added a new column by adding to propertyDefinitions and schema() accordingly.

Here's an example schema. Let's say I just added the admin column.

  /**
   * {@inheritdoc}
   */
  public static function schema(FieldStorageDefinitionInterface $field_definition) {
    $schema = [
      'columns' => [
        'state' => [
          'type' => 'varchar',
          'length' => 2
        ],
        'admin' => [
          'type' => 'int',
          'size' => 'tiny'
        ],
        ...

I've found posts on how to do this in hook_update_N in D7, but it's unclear how to do this in D8.

In fact, like it's a custom field type, your change in the schema can be detected and applied if you launch the drush command drush entity-updates (or drush entup).

All tables which implement this field (like node__field_my_field_type or paragraph__field_my_field_type) will be updated. So you don't need to use an hook_update to update the schema of all these tables.

The big problem with this command is many errors are silent and sometimes, the command don't return errors but the schema hasn't been updated and still proposed by the command to be updated.


Can I filter entityFieldQuery results by Workbench moderation state? I have the Workbench module and I want to look up nodes which have a specific workbench state with EntityFieldQuery.

I can get articles assigned to a user as follows:

$articles = new EntityFieldQuery();
$articles->entityCondition('entity_type', 'node')
         ->fieldCondition('field_moderating_user', 'uid', $user_id, '=');

Now I want to add a condition that only gets articles that have the state 'assigned'.

Any ideas?

An EntityFieldQuery can only filter based on fields associated with the entity by default, and since workbench moderation records are held in a custom table outside of the field system the standard query can't include a reference to them.

However, you can extend the query using tags and hook_query_alter, e.g.:

function MYMODULE_query_alter(QueryAlterableInterface $query) {
  // Only change the query if we have the required tag
  if ($query->hasTag('WorkbenchModerationAssigned')) {
    // Join the workbench moderation node history table
    $query->join('workbench_moderation_node_history', 'wmnh', 'wmnh.nid = n.nid');

    // Add the state and current conditions
    $query->condition('wmnh.state', 'assigned');
    $query->condition('wmnh.current', 1);
  }
}

You would then build up your EntityFieldQuery like this:

$articles = new EntityFieldQuery();
$articles->entityCondition('entity_type', 'node')
  ->fieldCondition('field_moderating_user', 'uid', $user_id, '=')
  ->addTag('WorkbenchModerationAssigned');

That's a very basic example which may need some changing, you might also want to join in the workbench_moderation_states table but it depends on your exact requirements.

EDIT

Just for a bit more info you can also use hook_query_TAG_alter() to do this in a more targeted manner:

function MYMODULE_query_WorkbenchModerationAssigned_alter(QueryAlterableInterface $query) {
  $query->join('workbench_moderation_node_history', 'wmnh', 'wmnh.nid = n.nid');
  // ...


Receiving Access Denied with altered CRUD paths in ECK I have altered the CRUD paths for entity types and bundles created with Entity Construction Kit.  The change propogates correctly, all views which use the ECK provided views fields (Link, Edit, Delete) are now using the correct URL.

The issue is when trying to hit those URL's, the page is always access denied.  What I have found in my troubleshooting:

The menu is built within eck.entity.inc.  I have used the following test code, inserted at line #93

if ($bundle->name == 'inventory_item' && $action_label == 'Edit') {
  print_r($access_args);
  die();
}
// result = Array ( [0] => edit [1] => inventory_item [2] => inventory_item [3] => 5 )

Note that the $access_args does contain the correct entity id (index 3 in the result array).
The menu access callback is eck__entity_menu_access() which is found in eck.module and I have included the following there, inserted at line 762:

if ($action == 'edit' && $bundle_name == 'inventory_item') {
  print_r(func_get_args());die();
}
// result = Array ( [0] => edit [1] => inventory_item [2] => inventory_item [3] => )

Note that index 3 ($entity_id) is null now.

I can't figure out where the entity id is lost.  I don't think it matters, but I did check the loader, eckentity_load() and it is loading the correct entity.

Any ideas why the entity id is not making it to the access callback?

It would be helpful to see an example of an original ECK path (for a single entity), and then your updated one. If you re-arranged the arguments, or changed their quantity, the access arguments passed to the access callback will not be correct.

You will almost certainly need to implement hook_menu_alter to update the access arguments property of ECK paths.


what are the css files with question marks - like modules/system/system.theme.css?pywps6u? I am new here, starting to find my way around a Drupal site I inherited. I am trying to work out if I can safely ignore all the @import css files with question marks like system.theme.css?pywps6u . I notice that the appended string of letters changes every so often, and I assume this is resulting from the caching.

What's going on here and can I safely ignore these files and just edit the normal files with standard filenames like MyStyleSheet.css?

I assume this is resulting from the caching

You are correct. It is for caching; especially to prevent browsers from thinking they have already downloaded a certain file.

If the file was named system.theme.css, and your browser already downloaded that file several days ago, it won't download it again. This results in an outdated site. The suffix changes every time the CSS files change and forces your browser to download the file again.

You can safely edit the 'regular' CSS files on the filesystem. Take care though that is discouraged to edit system and module files, as they will be overridden during updates. Instead create a custom module or theme to implement the changes you need.


How to alter file upload description text I'm trying to customize text for a file upload widget in Drupal 8.

Here is a screenshot of the widget:

I just want to display the first 15 MB which I added as file field description text in the content type.

The trouble is the last 3 lines of text have no HTML tags so I can't selectively hide it with display:none;. Here is what I mean:

I tried this CSS but it doesn't work:

#edit-field-dataset-file-0--description * {
    display:none;
}

#edit-field-dataset-file-0--description p {
    display:inline !important;
}

Does anyone have any suggestions?

I used hook_field_widget_form_alter as suggested by DannyEnglander and leymannx.

8.8.x hook_field_widget_form_alter

Replace MYMODULE with your custom module's name and alter the element array to suit your needs.

/**
 * Implements hook_field_widget_form_alter().
 */
function MYMODULE_field_widget_form_alter(&$element, \Drupal\Core\Form\FormStateInterface $form_state, $context) {
  if (get_class($context['widget']) === 'Drupal\file\Plugin\Field\FieldWidget\FileWidget' && !empty($context['form']['#attributes'])) {
    $element['#description'] = '
File must be less than 15 MB.
Allowed types: txt csv tsv xls xlsx sav sas7bdat
';
  }
}


How do I print a custom menu? There are lot of tutorials on Internet about how to display menu, but no one works for me.
I have tried:

$menu_array = menu_navigation_links('menu_menu-login-menu');
print theme('links__menu_login_menu', array('links' => $menu_array));

print drupal_render(menu_tree_output(menu_tree_all_data('menu-login-menu')));

Both don't work.

My menu looks like this.

Have you tried using the Menu Block module (D7)?

Disable the main menu in the theme settings and create one or multiple menu blocks with a lot of options for the menus. The module can render submenu items with the main navigation and/or in a separate menu-block. The Menu block module can render a custom menu as well.

You can also add an extra region to your theme that renders a menu-block-menu inside a nav-tag:

yourtheme.info file add:

regions[nav_custom] = Nav Custom

In page.tpl.php add:

<?php if ($page['nav_custom']): ?>
    <nav id="nav-custom" role="navigation" class="navigation">
      <?php print render($page['nav_custom']); ?>
    </nav> <!-- /.section, /#nav-custom -->
<?php endif; ?>


How do I import taxonomy terms This is almost 6000 rows of taxonomy terms ranging over 8 columns that i'd like to import from csv. I would like to use it for facet search.

The CSV is located here (google_product_category).

The format is like:

# Google_Product_Taxonomy_Version: 2015-02-19
1 - Animals & Pet Supplies
3237 - Animals & Pet Supplies > Live Animals
2 - Animals & Pet Supplies > Pet Supplies
3 - Animals & Pet Supplies > Pet Supplies > Bird Supplies
7385 - Animals & Pet Supplies > Pet Supplies > Bird Supplies > Bird Cage Accessories

As popular Drupal 7 modules like Taxonomy CSV import/export and Taxonomy Manager are not ported to Drupal 8, I recommend a very simple but functional module called term_csv_tree_import.

After installing, go to /csv-tree-import and paste your taxonomies into the form. It assigns parent values from right to left, empty intermediate elements are allowed. You have to convert your CSV into the following format:

"element","subelement","subsubelement"


Rendering a 'google_map_field' when referenced via entity reference field I have a content type with an entity reference field to another content type. We'll call the first content type A, and the other B.

In my node level template for A, I need to output a google_map_field (https://www.drupal.org/project/google_map_field) from referenced entity (B).

I'm outputting other fields from B by using:

node.field_entity_reference.entity.field_example.value

However, this does not work for the google_map_field. Lots of errors spit out, regarding parts of the google_map_field, such as lat, lng etc. I'm guessing this is because the module usually does some processing of this field, which isn't being done due to the nature of how I'm outputting it?

I need to work out how to tell Drupal to render it as a GoogleMapFieldType (I beleive).

Any guidance on this would be highly appreciated!

Thanks in advance.

I would recommend using a view mode to render out the referenced entity.

For instance, A's display settings is set to display B using the 'teaser' view mode. Then, you can configure B's teaser display to show what you want.

I know this doesn't answer your direct referenced entity value question, but this is how I would tackle this problem.

I hope that helps!


Ideas on collecting payment before form submission? I have a use case in which I wish to collect payments before users are allowed to fill a form; basically the form is an assessment form for which the provider (offering analysis) would like to charge money.
Currently I have the form setup using webforms, but I couldn't find a decent or well established way of collecting payment with webform submission. I already have Ubercart on the site so, if there is a Ubercart to webform bridge, I would definitely like to know about it as well (I couldn't find any). Lastly I am also open for any other approaches.

My use case is the following.
Users pay for the assessment (service) using Paypal, and then they are given a link to submit a form; the submitted data need to go to the provider.
Do you have any ideas on how this could be implemented? I assume it should be a relatively common use case.

Have you tried the Ubercart Webform Checkout Pane module?
You could define a simple product and use the webform as part of the checkout process.
Some more details about this module (from its project page):

This module allows you to define Webform nodes as checkout/order panes in Ubercart.
This is useful if you want to collect additional information during the checkout process. For example, you may want a quick survey or require additional fields that apply to the entire order.
Using the Webform module allows for many advantages: the forms/fields can easily be modified by an end-user; less development time is required to create database tables and code to store/retrieve the data; and the form will remember the user's previous answers.
Furthermore, this module now provides tokens for every field in each of your enabled webforms, making it easy for you to insert the submitted values into confirmation emails, invoices, etc.


How to get the node status? I have a function that returns sets of variables. Now, I want to control the return value by using node status. Basically I dont want the value to be returned when the node is unpublished. Any idea? Here is the function by the way. I just need to add a condition in the return value like this if($node->status == 1){ return $omniture_variables; }
function my_module_omniture_variables() {
  $current_day = date('D');
  $current_hour = date('G');
  .....

  $omniture_variables['variables'] = array(
    ....
  );

  //Sets omniture variables
  if(module_exists('omniture')) {
  ....
  }

  if(count($extra_variables) > 0) {
    $omniture_variables['variables'] = array_merge($omniture_variables['variables'], $extra_variables);
  }

  return $omniture_variables;
}

Getting a node's status is quite simple:

// Get the node with node ID 123.
$node = node_load(123);
// Get its status.
$status = $node->status;

That said... I don't know what your function looks like or in which context it's running, so depending on your situation, there may be an even better way to get what you want.


Theme "seven" – how to allow regular users edit content with this theme? please instruct me how to allow regular users (non-admins) to use Seven theme to edit content. Now users are forced to edit content using the default drupal theme which wasn't designed for this purpose (looks ugly).
Is it matter of some permission? Admins are editing with Seven theme without problem.

I've found some topics about more complex cases with module recommendations like this:
http://drupal.org/project/themekey . As my case is pretty simple, I decided to ask!

Cheers!

Checking the permissions "View the administration theme" fixed my problem.


Migration of content with an UI My goal is to import data of customers from a csv file to my custom entity. For that I wrote a migration with the migrate_source_csv module as source plugin. This works fine, but the problem is, that the import is just possible with drush. But it should work with an UI where a user can upload a file and run the import.

Is there any way to execute the import without drush?

The Wordpress Migrate module is a great example of how to implement a UI to upload a file and create a migration for it. Once you have that, it shouldn't be too difficult to run the actual migration via code.

Create Migration configuration from information and file provided to your Wizard Form. Then the following should work.

$migration = Migration::create($configuration);
$executable = new MigrateExecutable($migration, new MigrateMessage());
$executable->import();


Execute a Backup and Migrate backup via PHP I'm trying to create a custom module that will overwrite my testing site with a copy of my live site (I can't use SSH and I can't install my own PEAR modules, so Drush is a no-go).

I've been using PHP execute() commands to manipulate the file system and dump the database, but I'm getting errors on the testing site when importing the SQL dump, and I usually have to resort instead to the Backup and Migrate module, using a profile that copies my main database over to my testing database.

Now I'm wondering, is there any way I can hook into this and execute it as part of the chain of commands in my custom module? The goal is to turn the process of migrating to the testing site into a one-click (followed by a lot of grinding) process. But since Backup and Migrate doesn't apparently expose any API or hooks, or even the machine names of its profiles and destinations, how could I execute a backup command with a specific preset from a different module?

Say, for instance, I want a PHP command that will tell Backup and Migrate to backup database live_db to destination test_db, both of which are already recorded as mysql://[db_name] in the B&M settings.

Ok, as it happens, I figured this one out. Below is a sample function meant to be used as an admin form submission handler.

function _my_backup_handler() {
  $destination_hash = 'yourhash'; // See below.

  backup_migrate_include('profiles');
  $settings = _backup_migrate_profile_saved_default_profile();
  $settings->destination_id = $destination_hash;
  $settings->source_id = 'db'; // Your primary Drupal database. This is probably redundant.
  backup_migrate_perform_backup($settings);
}

As for what $destination_hash is, it turns out the "machine name" of a custom BM destination is a random hash. It can be found in the URL if you go to http://www.yoursite.com/admin/config/system/backup_migrate/destination and click the "edit" button for your destination; you'll end up at http://www.yoursite.com/admin/config/system/backup_migrate/destination/list/edit/[hash]. Just copy [hash] and plug it in as a string for the value of $settings->destination_id.


Image shows on home page, but not on article page I am using Open Outreach. When I create an article the image I uploaded appears on the home page, but does not appear when I click the link for that article.

From what I've read, it looks like it has something to do with Configuration/Media/File System. My public file system path is set as sites/openoutreach-7-x-1-19.dd/files. Do I need to change this? If so, what do I change it to?

Log message:

Type    page not found
Date    Thursday, June 4, 2015 - 9:43am
User    admin
Location    http://openoutreach-7-x-1-19.dd:8083/sites/openoutreach-7-x-1-19.dd/files/styles/medium_large/public/Portulaca%20grandiflora.jpg?itok=OP-6w24x
Referrer    http://openoutreach-7-x-1-19.dd:8083/article/june-3-2015-newsletter
Message sites/openoutreach-7-x-1-19.dd/files/styles/medium_large/public/Portulaca grandiflora.jpg
Severity    warning
Hostname    127.0.0.1

There is no medium_large folder in my styles folder. Do I need to create one?

Thanks!

When contrib images are missing in drupal the cause more often than not is that you have permissions problems with regards to your filesystem.

Make sure that your webserver can write to your files and files/styles directories.

If permissions are ok then drupal will create your medium_large directory and subdirectories.

Check the drupal setup documentation here (see the paragraph "Create the files directory").
As mentioned there make sure that you have write permissions on your sites/default/files directory.


Loading a jQuery plugin from the Libraries 2.X module in Drupal 7? I am using the jQuery Easing plugin (http://gsgd.co.uk/sandbox/jquery/easing/) for one of my Drupal 7 themes. I see that there is a Libraries module that loads this plugin in a way that allows other modules and themes to use it: http://drupal.org/project/jqeasing.

Is this the correct way to load the library?

After loading the library, Do I need to explicitly call drupal add js from the template.php theme file? The documentation for the Libraries module for theme development is terrible. I may contribute to it, once I get this sorted out.

Yea using a module that exposes it as a library is totally the way to go.

And you certainly don't want to use drupal_add_js because drupal_add_library  [link] will do it the proper way.

And for your case:

drupal_add_library('jqeasing', 'easing');


problem using ajax callback in form I have a very simple form that has a select box of the terms in a vocabulary, and renders the selected term below it.  It seems that the first time I change the value in the select it renders the appropriate term, however every subsequent "change" event it uses what ever term I selected the first time.

The code is as follows

function jms_industry_lens_form($form, &$form_state) {
    $values = array();

    // Load the vocabulary and collapse into an array that form api understands
    $vocabulary = taxonomy_vocabulary_machine_name_load('industry_lens');
    $terms = taxonomy_get_tree($vocabulary->vid);

    foreach($terms as $term) {
        $values[$term->tid] = $term->name;
    }

    $form['industry_lens'] = array(
        '#type'             => 'select',
        '#options'          => $values,
        '#default_value'    => 0,
        '#required'         => TRUE,
        '#ajax'             => array(
            'callback'  => 'jms_industry_lens_form_ajax',
            'wrapper'   => 'edit-industry-lens-term',
        ),
    );

    $form['industry_lens_term'] = array(
        '#type'     => 'item',
        '#markup'   => _jms_render_term($terms[0]->tid),
    );

    return $form;
}

/**
 * Ajax callback to change the rendered industry lens taxonomy term
 */
function jms_industry_lens_form_ajax(&$form, &$form_state) {
    $form['industry_lens_term']['#markup'] = _jms_render_term($form_state['values']['industry_lens']);
    $form_state['rebuild'] = TRUE;

    return $form['industry_lens_term'];
}

So try to use

function jms_industry_lens_form($form, &$form_state) {
    $values = array();

    // Load the vocabulary and collapse into an array that form api understands
    $vocabulary = taxonomy_vocabulary_machine_name_load('industry_lens');
    $terms = taxonomy_get_tree($vocabulary->vid);

    foreach($terms as $term) {
        $values[$term->tid] = $term->name;
    }

    $form['industry_lens'] = array(
        '#type'             => 'select',
        '#options'          => $values,
        '#default_value'    => 0,
        '#required'         => TRUE,
        '#ajax'             => array(
            'callback'  => 'jms_industry_lens_form_ajax',
            'wrapper'   => 'edit-industry-lens-term',
        ),
    );

    $form['industry_lens_term'] = array(
        '#type'     => 'item',
        '#markup'   => _jms_render_term($terms[0]->tid),
        '#prefix'   => '
',
        '#suffix'=> '
'
    );

    return $form;
}

/**
 * Ajax callback to change the rendered industry lens taxonomy term
 */
function jms_industry_lens_form_ajax($form, &$form_state) {
    $form['industry_lens_term']['#markup'] = _jms_render_term($form_state['values']['industry_lens']);

    return $form['industry_lens_term'];
}


Using a select form field for the field that selects the groups where a node is posted The form for creating a node for the content type that has been set as content type for the Organic Groups module has checkboxes for choosing the groups where a node is posted; I want to use a select form field instead of the checkboxes.

How should I alter the form field?

I have tried some patches from drupal.org, but they do not works correctly.

I have used the following code.

/**
 * Helper function; Make the groups audience accept only a single group.
 */
function og_single_group_form_alter(&$form, $form_state, $form_id) {
  if (module_exists('og_access')) {
    $path = drupal_get_path('module', 'og_single_group');
    drupal_add_js($path . '/og_single_group_hideoption.js');
  }

  if (!empty($form['og_nodeapi']['visible']['og_groups']) && ($form['og_nodeapi']['visible']['og_groups']['#type'] != 'value')) {
    $options = array();
    $options = array(t('Personal blog')) + $form['og_nodeapi']['visible']['og_groups']['#options'];
    $form['og_nodeapi']['visible']['og_groups']['#type'] = 'select';
    $form['og_nodeapi']['visible']['og_groups']['#multiple'] = FALSE;
    $form['og_nodeapi']['visible']['og_groups']['#options'] = $options;
    // Add own submit handler so we can cast the groups back to an array.
    $form['#submit'][] = 'og_single_group_submit';
  }
}

 /**
  * Submit handler; Since we permit only a single group per content, we need to
  * case to groups into an array
  */
function og_single_group_submit($form, &$form_state) {
   if (!empty($form_state['values']['og_groups']) && !is_array($form_state['values']['og_groups'])) {
     $form_state['values']['og_groups'] = drupal_map_assoc((array)$form_state['values']['og_groups']);
   }
  else if (empty($form_state['values']['og_groups'])) {
    $form_state['values']['og_groups'] = array();
  }
}

The code causes the following error:

  Warning: array_filter() [function.array-filter]: The first argument should be an array in /var/www/mysite/sites/all/modules/contrib/og/og.module on line 1303.

I am replying basing on what you wrote in the comment to your question.

Organic Groups shows checkboxes or a select field basing on the number of groups that are listed in the "Audience" form field. If the number of groups is less than 20, the module will use checkboxes; otherwise, it will use a select box.

There is no way to change which form field is used, except using a module that alters the form fields added by Organic Groups. The following code, contained in og.module, is the code that adds the audience form field to the node edit form.

// show multi-select. if less than 20 choices, use checkboxes.
$type = $cnt >= 20 || $is_optgroup ? 'select' : 'checkboxes';
$max_groups = variable_get('og_max_groups_'.$node->type,'');
$description_max_groups = ($max_groups && !user_access('administer nodes')) ? format_plural($max_groups," Limited to !max_groups choice."," Limited to !max_groups choices.", array('!max_groups' => $max_groups)):'';
$form['og_nodeapi']['visible']['og_groups'] = array(
  '#type' => $type,
  '#title' => t('Audience'),
  '#attributes' => array('class' => 'og-audience'),
  '#options' => $type == 'checkboxes' ? array_map('filter_xss', $options) : $options,
  '#required' => $required,
  '#description' =>  format_plural(count($options), 'Show this post in this group.', 'Show this post in these groups.') . $description_max_groups,
  '#default_value' => $groups ? $groups : array(),
  '#required' => $required,
  '#multiple' => TRUE);

It is enough to have a module that executes the following line, and the form field will always use a select box to show the list of groups to which associate a post.

$form['og_nodeapi']['visible']['og_groups']['#type'] = 'select';

The code needs to be executed inside the implementation of hook_form_alter(), or hook_form_FORM_ID_alter().


Drupal files folder owner/group for CentOS? This is my first time installing Drupal on CentOS. I know for Ubuntu it needs to be www-data as the /files folder owner, but what is it for CentOS?

I faced with this issue before, it was because of SELinux on CentOS, So you should try to Disable SELinux on Centos

  From the command line, you can edit the /etc/sysconfig/selinux file.
  This file is a symlink to /etc/selinux/config. The configuration file
  is self-explanatory. Changing the value of SELINUX or SELINUXTYPE
  changes the state of SELinux and the name of the policy to be used the
  next time the system boots.

[root@host2a ~]# cat /etc/sysconfig/selinux
# This file controls the state of SELinux on the system.
# SELINUX= can take one of these three values:
#       enforcing - SELinux security policy is enforced.
#       permissive - SELinux prints warnings instead of enforcing.
#       disabled - SELinux is fully disabled.
SELINUX=permissive
# SELINUXTYPE= type of policy in use. Possible values are:
#       targeted - Only targeted network daemons are protected.
#       strict - Full SELinux protection.
SELINUXTYPE=targeted

# SETLOCALDEFS= Check local definition changes
SETLOCALDEFS=0

Change it from SELINUX=permissive to SELINUX=disabled

Once you have saved the changes sudo shutdown -r now to restart now.

Also you can disable it temporary ( until next restarting ) with

sudo setenforce 0

How to Disable SELinux


Debug arrays from hook_cron? Does anybody know of the proper way to debug objects from within hook_cron? I'm trying to set up a task that periodically deletes backups from my private folder, but I can't properly debug arrays that I define in my module. I've tried both the object log and devel debug log modules, but neither of them are properly working for me at the moment, so I feel completely stuck on how to access the information I need.

I've tried running kint() directly, but I'm assuming that doesn't work because it's not running on a page load but in the middle of the cron task.

EDIT: Ended up solving this particular piece of the issue, but am having errors doing some of the deletion as addressed in another issue.

You might want to try a module like Ultimate Cron that allows you to run individual cron jobs, outside of cron.php. This will allow you to use kint() and see the output.


twig if Term ID is something, then do something I have a taxonomy called Fish and 2 terms in it. Bass and Gold. I have a term reference field on a Page node, and its a select list. The editor can select either Bass or Gold. And I want display something depending on what the user selects. I cannot get it to work. This is what I have tried. Below the Bass tid is '1'.

{% if node.field_term_reference.value == '1' %}

The value is Bass

{% else %}

The value is Gold

{% endif %}

Below I am outputting the string value bass.

{% if node.field_term_reference[0]['#title'] == "bass" %}

The value is Bass

{% else %}

The value is Gold

{% endif %}

Both of these return "The value is Gold"
I tried this also

{% if node.field_term_reference.label == "bass" %}

The value is Bass

{% else %}

The value is Gold

{% endif %}

What if you want to add multiple terms and use AND OR "bass" and "finch".

{% if node.field_term_reference.entity.label == "bass" and or "finch" %}

How would it be written?

The original question is how to use the term id in a twig condition. You find the term id in the property target_id of the reference field:

{% if node.field_term_reference.target_id == '1' %}

The value is Bass

{% else %}

The value is Gold

{% endif %}


How can I hide the "day" in a date field? I have a date field, but I only want to collect the year and month, not the day.  How can I hide the day part?

There are instructions for Drupal 7, but I am using Drupal 8.

Note that the day is required.

This means there are some difficulties:

You need to set the value for the day field (otherwise the form will fail validation).  In this example, we will set it to the 15th of the month.
You can't use unset() or #access: FALSE because this will cause the form to have no value and fail validation.

You can do this in an #after_build callback.

function MYMODULE_form_MYFORM_alter(&$form, FormStateInterface $form_state, $form_id) {
  $form['#after_build'][] = 'MYMODULE_date_remove_day_after_build';
}

function MYMODULE_date_remove_day_after_build($form, &$form_state) {
  $form['field_MYFIELD']['widget'][0]['value']['day']['#value'] = '15';
  $form['field_MYFIELD']['widget'][0]['value']['day']['#attributes']['class'][] = 'element-hidden';
  return $form;
}

And then in your theme .css, add this class:

.element-hidden {
  display: none !important;
}


How to alter the result of my view using filters? I have a view with 2 exposed filter.. I only want to change the result of my view when filters are used, ie if they have any value and press the button to run the filters.

I try to used the hook_views_pre_render, but doesn't work...

function node_db_views_pre_render(&$view) {
   if($view->name=="demo" && $view->current_display == 'page_1' &&  $view->exposed_input['date_filter'] != NULL) {
       $get_date = $view->exposed_input['date_filter'];
       $min = $get_date['min']['value'];
       $max = $get_date['max']['value'];

         $query_power = "SELECT h.id, h.name, count(c.room_id) as busy
                         FROM table_1 c JOIN table_2 h ON c.id = h.id
                         WHERE '%s' < c.in_date OR '%s' > c.in_date
                         AND '%s' < c.out_date OR '%s' > c.out_date";

         $result = db_query($query_power, $min, $min, $max, $max);

       $items = get_rows($result); // this is a function gets the data from the sentence and makes a array.

       $view->result = $items;
   }
}

Exist other hook that can help me?..Thanks :D

you should use hook_views_query_alter, because hook_views_pre_render is called after the query is done, so you cannot influence your database request anymore.

The views documentation has been added to the Drupal api docs recently, so for more info look at:
http://api.drupal.org/api/views/docs%21views.api.php/group/views_hooks/7

or

http://views.doc.logrus.com/


Rewrite results output creates 2 links for one for one rewritten custom text field I am using replacement patterns to rewrite the results of my content title field with the manufacturers name in front of the title. I am using the following custom text within the title field to accomplish this:

{{ field_tool_manufacturer }}
{{ title }}

I am then outputting this field as a custom link, with the path Node/{{ nid }}

Both the manufacturer and title fields render linked to the node correctly, but the problem is that they should be a single rewritten text link, but it's being output as 2 separate links. One link for the manufacturer, and a separate one for the title. This of course isn't optimal for UX as it communicates 2 separate links especially with css hover styling, etc.

The results are the same when removing the
 line break. The manufacturer field is excluded from the display, and it is not set to be output as a link in the original field. I have tried multiple style settings with no better luck.

I did this with very little trouble in Drupal 7, so I am wondering if this is a bug that I should create an issue for, or if there is a structural change that is causing the 2 links. I'm new to Drupal 8, so I might be missing something simple. Any help would be appreciated, and let me know if I left out any useful info.

Thanks!

When rewriting a field into a custom link you have to make sure that the tokens used for the link text aren't formatted as links, because links can't be nested one into the other.

Edit the field settings for the fields corresponding to {{ field_tool_manufacturer }} and {{ title }} and make sure their Formatter option is set to Plain text, or that the option to "link this field to content" is not checked.

Most field settings will be applied to the token in the Rewrite field option, so you have to control the output yourself.

You can test what the field output is by simply viewing the field without any Rewrite options, and if you see the field output as plain text, and not a link, you can proceed to set up the Rewrite options.


How to test the existence of a file in a webform email twig template I have a webform with a Document File field. In my twig email template, I want to test if that field is empty. For text area fields for example, this syntax works :

{% if webform_token('[webform_submission:values:question_text_area:value]', webform_submission) %}

  Questions

   {{ webform_token('[webform_submission:values:question_text_area:value]', webform_submission) }}

 {% endif %}

But for a Document File field, the same syntax does not work, meaning that if no file is uploaded, that part of my template is still printed.

I tried

{% if webform_token('[webform_submission:values:join_a_file:value]', webform_submission) %}

or

{% if webform_token('[webform_submission:values:join_a_file:value]', webform_submission) is not null %}

or

{% if webform_token('[webform_submission:values:join_a_file]', webform_submission) is not null %}

and none of them work.

Does anybody know the proper syntax for what I'm trying to do? Thanks!

The solution is to do this

{% if webform_token('[webform_submission:values:file:clear]', webform_submission) %}
  FILE UPLOADED
{% else %}
  NO FILE UPLOADED
{% endif %}

Solution given first here : https://www.drupal.org/project/webform/issues/2969437


Move XML once they're processed in Feeds Currently, I'm using Feeds & Feeds XPath Parser for importing XMLs into my Drupal 7.x site. As per the requirement, it's working perfectly fine expect the moving feature.

What I need to do is to move the XML files once they are processed, is there any hook or something which can be helpful for me on this? Suggestions are welcome.

You can use hook_feeds_after_import to move xml after successful import.

/**
 * Invoked after a feed source has been imported.
 *
 * @param FeedsSource $source
 *  FeedsSource object that describes the source that has been imported.
 */
function hook_feeds_after_import(FeedsSource $source) {
  // See geotaxonomy module's implementation for an example.

  // We can also check for an exception in this hook. The exception should not
  // be thrown here, Feeds will handle it.
  if (isset($source->exception)) {
    watchdog('mymodule', 'An exception occurred during importing!', array(), WATCHDOG_ERROR);
    mymodule_panic_reaction($source);
  }else {

        // You can write here you own code to move xml.

   }
 }


Form API #states with #default_value? I have a form which has a select with a #default_value which get's set when the user has errors/has filled out the form. Then I have two fields with a #states that show them when the select has a value.

So basically

$checkout_form['wrap'] = array(
  '#type' => 'select',
  '#title' => t('How many item(s) do you wish to have wrapped?'),
  '#default_value' => $default_giftwrap_amount,
);

Then I have a fieldset and a textarea with

  '#states' => array(
    'visible' => array(
      ':input[name="wrapping[wrap]"]' => array('!value' => ''),
    ),
  ),

which make those two fields show when ever something is selected.

But my problem is when the #default_value is say 400 (ie something is selected) it doesn't show the fieldset and textarea, only when you select something.

Is there anyway for it to check on page load as well as onchange?

Your default value in the select element must be the array key of your values not the value it self.So i set an empty "value" and check for that.

That said i got this working like:

$form['wrap'] = array(
  '#type' => 'select',
  '#title' => t('How many item(s) do you wish to have wrapped?'),
  '#options' => array('--', '1', '2', '300', '400'),
  '#default_value' => 2,
);
$form['textarea'] = array(
  '#type' => 'textarea',
  '#title' => t('How many item(s) do you wish to have wrapped?'),
  '#states' => array(
    'visible' => array(
      ':input[name="wrap"]' => array('!value' => 0 ),
      ),
    ),
  );

In the example above my default value is 300.
The state visibility will work onload and onchange and will show the textarea only when the value is the empty value (0 => '--')


Switch theme based on screen size I need to switch my theme based on the users screen size instead of their user agent. Currently I'm using the Browscap & Mobile Switch modules and they work perfectly. My problem is that for tablets, I want users to use the desktop site. For mobile phones or anything under a 7 inch tablet, I want users to use my mobile site. What modules can help me with this OR how can I create the switch based off screen size?

UPDATE: I've just found ThemeKey. Anyone know if using this in conjunction with Browscap/Mobile Switch will cause issues?

The ThemeKey module is definitely the way to go for this. Here is a quote about it (from the module's project page):

... allows you to define simple or sophisticated theme-switching rules which allow automatic selection of a theme depending on current path, taxonomy terms, language, node-type, and many, many other properties. It can also be easily extended to support additional properties exposed by other modules. In combination with Drupal's theme inheritance you can easily achieve features like:

individually-styled channels
a front-page / "splash" screen
a date/time-selected Christmas theme
mobile themes for different auto-detected mobile devices
special themes for "limited" or "old" browsers
content, user, or role -specific themes
indicating your environment (production, staging, testing, sandbox, … )
testing your redesign safely on a live server


Create an EventSubscriber for a specific module I'm attempting to make something occur at a specific event in the GatherContent module found here https://www.drupal.org/project/gathercontent

Based on the information here http://help.gathercontent.com/importing-and-exporting-content/drupal-integration/drupal-integration-extending-the-module-using-the-api and several tutorials and documentation

I created a module with the code entered like so

my_gathercontent.services.yml

services:
  my_gathercontent:
    class: '\Drupal\my_gathercontent\EventSubscriber\MyGatherContentSubscriber'
    tags:
      - { name: 'event_subscriber' }

src/EventSubscriber/MyGatherContentSubscriber.php

namespace Drupal\my_gathercontent\EventSubscriber;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

/**
 * Event Subscriber MyGatherContentSubscriber.
 */

class MyGatherContentSubscriber implements EventSubscriberInterface {
    public function onGatherContentPostImport(DrupalgathercontentEventPostImportEvent $event) {
        \Drupal::logger('my_gathercontent')->notice('This is a test');
        drupal_set_message("Debug: This is a test.");
        var_dump($event);
    }
    public static function getSubscribedEvents() {
        $events['gathercontent.post_import'] = ['onGatherContentPostImport'];
        return $events;
    }
}

And none of those messages get logged. I do now receive a page not found message after performing an action that should trigger that event. I'm not sure what I'm doing wrong.

Is there something wrong with the way I'm attempting to subscribe to the event?

Each event in the $events array should itself be an array; try:

$events['gathercontent.post_import'][] = ['onGatherContentPostImport'];


Can I create a view of watchdog log entries? We want to view a more detailed view of watchdog log entries, filtered by module and level and showing the details section in a table. When creating a new view, watchdog logs is not in the list. Is there a way to do this like a Views3 plugin or something what would integrate this?

You're probably looking for Views Watchdog

  The Views Watchdog module extends the Views module and allows to create customized lists (pages, blocks, feeds) of watchdog entries.


Saving multipage webforms after each page? You can create a multipage webform by inserting a pagebreak element. Can you have these webforms save after each page, so that if someone doesn't complete the final page you still get what they entered on previous pages?

The webform module does this by default if you enable Draft mode per webform and create multi-page forms.


Show block menu links only on certain pages I've built a menu with 20 links aprox. Then I put the block drupal creates for my menu on a region. Thing is I want some of the links to show for some pages, while others are hidden, like the option called "visibility options" on admin/structure/block/manage/block/nodenumber/

i.e.:
links 1,2 and 3 should be visible on page node/1
links 1,3 and 5 should be visible on page node/2
links 3,5 and 6 should be visible on page node/3

Any advice on how can I make it possible?

NOTE: Sorry for my english but it's not my native tongue.

Without any additional information about the links inside your menu, it seems the easiest way to structure this is to create 3 separate menus, even if some of the links inside them are repeated.

What sort of links are those? Maybe you can use Views to create a Block that reacts to the page it's on to filter out the relevant links.


How to access an entity loaded out of the cache I am working on a Drupal 8 modules which should push a http response header based on a value stored in an entity or a list of entities.

The module was originally done for D7 and now is in porting up to D8.

The main problem is that by using the Entity Cache in D8 any hooks are bypassed, which had been working in still in D7. So nor hook_entity_load or hook_entity_view are fired but only a single time before the entity is placed into the cache.

We might need to create an extra entity/node to a list and this should then eventually change the pages html-head section and the http response header.

So is there any chance to get informed (by a hook or event) for ALL entities be shown on a page (details or list/teaser)? Or can we store some information to a "cached" page (so a page that was assembled only out of cached entities) ?

Although the questions is not so clear I will try to give you some directions. I think it is time to dive into the new Cache API (I haven't done it so far!)

First of all, to get the "information" for a cached page you need to deal with the contexts and the cache tags.

To invalidate the tags you may need to use function invalidateTags(array $tags) (here is an example of using this class).

On the other hand if you want to invalidate cache of each node while loading the node you can set this option to the node_load($nid = NULL, $reset = FALSE) function by using $reset = TRUE.


Fatal error: Class 'DrupalDefaultEntityController' not found in comment.module I'm trying to update the Drupal Core of a website, specifically from 7.65 to 7.67.
I've followed the instructions from here. After the process, I've try to access the website without luck, because I'm getting the following error: Fatal error: Class 'DrupalDefaultEntityController' not found in /var/www/html/modules/comment/comment.module on line 1698

I've tried to run the update.php file and clearing the cache from the db several times, without fixing the error. I've also tried to update from 7.65 to 7.66, but the problem persists.

What am I doing wrong?

UPDATE 1

I've tried to follow the instructions written here suggested by the user sivani. Here is the message I am getting:

DRUPAL_ROOT is /Users/DamianFox/tests/drupal-website/website.

Bootstrapping to DRUPAL_BOOTSTRAP_SESSION

Additional uncaught exception thrown while handling exception.

Original

PDOException: SQLSTATE[HY000] [2002] php_network_getaddresses: getaddrinfo failed: nodename nor servname provided, or not known in lock_may_be_available() (line 167 of /Users/DamianFox/tests/drupal-website/website/includes/lock.inc).

Additional

PDOException: SQLSTATE[HY000] [2002] php_network_getaddresses: getaddrinfo failed: nodename nor servname provided, or not known in system_list() (line 165 of /Users/DamianFox/tests/drupal-website/website/includes/module.inc).

%

After a bit of research, I found out that the problem might be generated from entity.inc inside the includes folder.
Therefore, I tried to put back the previous entity.inc (from the 7.65 installation); subsequently, I run the update.php script, and after another refresh, the website is finally accessible.
I done few more tests to check if there are warnings or errors, but everything seems to work fine, so somehow I got it sorted.


How do I create a configuration menu with the selected section name? I want to create a menu in the admin section that is in the sitename/admin/config path.

As of now, I am doing this.

Routing file

custom_menu.adminmenu_section:
    path: '/admin/config/custommenu'
    defaults:
        _controller: 'Drupal\custom_menu\Controller\CustomMenuController::content'
        _title: 'Custom Menu Configuration'
    requirements:
        _permission: 'administer site configuration'

custom_menu.admin_menu:
    path: '/admin/config/custommenu/customconf'
    defaults:
        _form: 'Drupal\custom_menu\Form\CustomMenuForm'
        _title: Custom Menu creation
    requirements:
        _permission: 'administer site configuration'

links.menu file

custom_menu.adminmenu_section:
    title: 'Configuration'
    description: 'Custom Menus Configuration section'
    parent: system.admin
    route_name: custom_menu.adminmenu_section

custom_menu.admin_menu:
    title: 'Custom Menus Conf'
    description: 'Custom Menus Configuration section'
    parent: custom_menu.adminmenu_section
    route_name: custom_menu.admin_menu

This code is not creating a section in the admin/config path. But when I used  parent: system.admin_config that time I will get menu in the admin section but the section name will be CONFIGURATION. Because its title given in the system.admin_config route, but I don't want that name.

I want to create a section with separate name. How can I achieve that?

I tested it with your code and you just have to change two little things in your custom_menu.adminmenu_section. The rest is ok. See below:

module.links.menu.yml

custom_menu.adminmenu_section:
  title: 'Configuration' <= change this to your section name
  description: 'Custom Menus Configuration section'
  parent: system.admin_config  <= change this to system.admin_config
  route_name: custom_menu.adminmenu_section


How to test if honeypot is working on a form? I have applied the Honeypot module to my site and set it to protect all forms on the site.

The problem is I am unsure of how to test it to know that it is working as expected.

Can anyone tell me how to do this?

Open up firefox or chrome, and inspect the form (using firebug or any equivalent). If you see any element with the class 'honeypot-*' and a label 'Leave this field blank'. Then its a honeypot field and its enabled.

To check if it works. Make the element visible by changing display: none to display: block, enter a value into the input box and hit submit. The validation should fail.


Using NOT LIKE in db condition? I don't see an example when looking at the api.  I'm setting up a query and would like to use NOT LIKE as opposed to STARTS since START does not seem to be supported.

Is this possible?

Add this snippet to your query item:

$query->condition(X, Y, 'NOT LIKE');

where X and Y are two variables. You can also replace each of them with constants.


Is there a way to show the content of a field taken from the user profile in the comment.tpl.php file? How does one display a custom field from a user's profile in comment.tpl.php?

The comment.tpl.php template file receive a $comment value, which contains the comment object. Between its properties, there is $comment->uid, which can be used to get the user object for the author of the comment, with user_load($comment->uid). If you are instead interested in the author of the node containing the comment, then you can use the following code.

$node = node_load($comment->nid);
$uid = $node->uid;
if ($uid) {
  $user = user_load($uid);
}

In both the cases, the code should be used in the preprocess function, not in the template file used for the comments. In this case, $variables['comment']->uid, and $variables['comment']->nid are instead used.


Is it possible to find which user created an account? I currently have a Drupal 7 site set up to allow users with the Doctor role to create users with the Patient role, via admin/people/create.
Does Drupal store data about which user created a specific account? If the answer is yes, how can I display this information in a view?

You have to create a custom module for this.

First you have to add a user field here admin/config/people/accounts/fields. Add a field that will check whether the user has been created by user with role "doctor". A boolean field would suffice. Mark the field as non-mandatory
Create a custom module. This module will provide an interface that only the users with role "doctor" can access. In the interface provide a button, clicking that button will create user with role "patient", also flag the field you created above.
Now in views create a page or block that will display the users, in the filter criteria of the view check whether the boolean field is flagged for that user.


How a anonymous user can view profile of authenticated user How to see a profile of registered user by a anonymous user.

exampel : someuser2

when an administrator clicks any username or someuser2
it displays in this format in url on browser

http://mydomain/users/someuser1

When an anonymous user paste this link on browser,
the profile doesn't appear.

Is there any permissions to be ruled out ?, to display user profile.

In Drupal 7

/admin/people/permissions
Users - Section --> View user profiles!

Drupal 7 user Permission

In Drupal 6

/admin/user/permissions
user module --> access user profiles


How do I map attachments submitted via mailhandler? In Drupal-7 I'm reading an imap mailbox with mailhandler. I have the mapping setup via feeds. This processes text messages creating a node but messages with attachments don't have the attachments stored.

How do I store the attachments?

I created a file field and mapped the attachment.

Create the file field under structure/types. Set number of values to 'unlimited'.
Under the feeds mapping map attachments to File:URI


How to Compute fields on the fly I have content type having fields as follows.

first

second

third

Sum1 (first + second +third) - computed filed

xxxx

yyyy

zzzz

Sum2 (xxxx+yyyy+zzzz) - computed field

Grand Total (sum1 + sum2) - computed field

I could achieve this by using computed field module. When I save node, I could able to find sums and Grand Total.

My problem is client wants to see  sum1 filed in edit/create form and also wants to update sum1/sum2/Grand Total fields on the fly (dynamically).
There are couple of content types having the same requirement.

Before start to write a custom module, I would like to know alternates for this.Any suggestions?

This sounds like cashier functionality. There has been some effort for D6, see Drupal POS (Point of Sales) System. I haven't used this.

Ideally, this would be done with JavaScript (I have once done it for a non-Drupal system).

A cheap workaround would be the Save & Edit module, where you just save the node and continue editing it, effectively updating the calculations. On demand, not automatically.

A smoother workaround would be updating (on demand) the form with ajax. Ajax module  has no D7 version, but in the issue queue is mentioned this sandbox project which supposedly can ajaxify the node edit form:
Asaf (ajax submit for any form).

You need one extra module for actually displaying Computed field on node edit form: Field extra widgets. Select the widget "read only".