texts: What is the ideal way to restore a previous version of a site with Backup & Migrate files?

texts:
So I've been backing up my sites with backup and migrate and I always found weird that the backup&migrate .mysql files are smaller than the "drush sql-dump" sql files. Does anyone know why?

Also what is the quickest way to do a restore using backup&migrate? I usually unzip the gz files that gets saved to my server and just do a mysql drop database and then recreate it again and just fill it in with the sql files. I'm not sure if im doing it the long way or not.


texts:
Everytime that I type a backslash into a textbox on my drupal site (in content editors, administration pages, you name it; I mean any textbox), it gets filtered out before it reaches the module code.

So I end up typing something like this:

  This is just some content with an \n
  or a directory structure like
  C:\Program Files\whatever

And it gets converted to this on save:

  This is just some content with an n
  or a directory structure like
  C:Program Fileswhatever

This really makes it hard to edit content on my D6 site; anyone know a fix for this?

Related issues:

http://drupal.org/node/673748
http://drupal.org/node/564166

This is on admin pages; so filters aren't used.


texts:
Our hoster informed us, that he has switched to fcgi. Therefore he had to switch of this part of the .htaccess file and move it to a central part of the server configuration:

<IfModule mod_php5.c>
  php_flag magic_quotes_gpc                 off
  php_flag magic_quotes_sybase              off
  php_flag register_globals                 off
  php_flag session.auto_start               off
  php_value mbstring.http_input             pass
  php_value mbstring.http_output            pass
  php_flag mbstring.encoding_translation    off
</IfModule>

Is fcgi ok to host Drupal? Are there any objections against moving this part of .htaccess to an other part of the configuration?


texts: How to send notification email to individual users

texts:
I want to send notification email to some users when a node is created in my site. The author should select the individual users in the node creation form and then after save the node email will be sent to those users.
I use Entity Reference and Rules modules to do that but I don't know how set the right action.


texts: If I have a table containing, say, images, how can I be able to select an image from one view, one from another and have them added/marked for later use (i.e., some sort of "add to cart" feature). So then I could select an image from slideshow1, one image from slideshow10 etc and then be able to do whatever I want with them (perhaps create another view?)


texts: Making images go to external sites in Slick carousel

texts:
I have a custom content type which collects one image and one URL per node. I have the Slick module along with Views set up to cycle through these images on the home page. I haven't been able to make the carousel images link to the external URLs. In Views I have this:

In the Global: Custom text field, I have this:
{{ field_library_photo }}
It's not using that markup. What's most confusing is that the images are displaying in the carousel. I have the photo field hidden and Drupal isn't using the custom text so I don't know how those images are being accessed.
What step have I missed to make this work? Thanks!


texts: hook_mail is not sending rendered HTML email

texts:
I'm rendering HTML template for email

demo_test.module

use Drupal\Component\Utility\SafeMarkup;

function demo_test_theme() {   return [
    'contact_mail' => [
      'variables' => ['params' => NULL],
    ]
  ];
}

function demo_test_mail($key, &$message, $params) {

  $render_email = [
    '#theme' => 'contact_email',
    '#params' => $params,   ];

  $mail = drupal_render($render_email);

  $message['body'][] = $mail;
  break;
}

contact_mail.html.twig

    <meta name="viewport" content="width=device-width">
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Test</title>

test

Tried:

$message['headers']['Content-Type'] = 'text/html; charset=UTF-8; format=flowed; delsp=yes';

But still not working.


texts:
How can I best redirect the following in Drupal 7?

stuff/bookA.pdf
stuff/bookB.pdf
stuff/magA.pdf
stuff/magB.pdf
stuff/...
stuff/magn.pdf

to

books/booka.pdf
books/bookb.pdf
mags/maga.pdf
mags/magb.pdf
mags/...
mags/magn.pdf

There are only a few Books (which can be redirected individually). There are hundreds of Mags.

I cannot find a module which does this.
I could write a custom module which checks the URL and redirects along these lines.
I am lost writing redirects in .htaccess.

Is there a noticeable performance improvement using .htaccess over the module solution?

If using .htaccess what would the rules be?


texts: Adding button with Ajax callback in node using preprocess_node

texts:
I have my_theme and my_project. Also have a file called my_project.php. There I have two functions and in both of them I have ALMOST the same structure:

function my_theme_preprocess_node__foo(&$variables){
  $variables['bye'] = [
    '#type' => 'button',
    '#value' => 'Value',
    '#description' => 'Description',
    '#ajax' => [
      'callback' => 'Drupal\my_project\MyProjectAjax::queryTestVisual',
      'event' => 'click',
      'progress' => [
        'type' => 'throbber',
        'message' => t('Wait...'),
      ],
    ],
    '#attached' => [
      'library' => [
        'my_theme/my-project-visual',
      ]
    ]
  ];
}

function my_theme_form_node_foo_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state){
  $form['hi'] = [
    '#type' => 'button',
    '#value' => 'Value',
    '#description' => 'Description',
    '#ajax' => [
      'callback' => 'Drupal\my_project\MyProjectAjax::queryTestForm',
      'event' => 'click',
      'progress' => [
        'type' => 'throbber',
        'message' => t('Wait...'),
      ],
    ],
    '#attached' => [
      'library' => [
        'my_theme/my-project-form',
      ]
    ]
  ];
}

Then I call buttons like:

In myvisual.html.twig:
{{bye}}

In myform.html.twig:
{{form.hi}}

I can see both buttons but only the form one ({{form.hi}}) does the callback.

Any idea why? Do I have to do write some extra code to make it work on preprocess_node?


texts: How to allow users upload images to existing nodes?

texts: Let’s say I have created a content type called movies and I want all nodes in movies to have a gallery tab. Inside the gallery tab it should allow users to upload images. How can I do this?


texts: How to create a default value for an entity base field in Drupal 8

texts:
Both the Examples module and the Drupal Console generate:entity:content both have code like this:

$fields['first_name'] = BaseFieldDefinition::create('string')
  ->setLabel(t('First Name'))
  ->setDescription(t('The first name of the Contact entity.'))
  ->setSettings(array(
    'default_value' => '',
    'max_length' => 255,
    'text_processing' => 0,
  ))

I was thinking that if I provided 'default_value' => 'Fred' in place of 'default_value' => '' that I might affect the default value of the field. I would expect to have seen Fred when creating an entity of this type, and I might have expected to see Fred as the default value in the entity's table definition, but it's not there.

I'm learning D8 and so have two parts to this question really, the first is just how to provide a default value, the second is if this default_value key isn't it, what is it for?


texts: How do I create a tax calculation rule that runs by default before the customers address has been set?

texts:
With Drupal Commerce and the Australian GST calculation module, I have been trying to calculate taxes as early as possible.

Most of the customers to the site are Australian and will have to pay the taxes. Rather than give them a nasty surprise I'd like to add GST by default and then get rid of it if the person's shipping address isn't Australian.

I created a secondary OR condition in the GST rule as below:

If the country component of the order address is AU or if it is not set, then calculate GST.

The current effect is that GST never get calculated.


texts: Search page is not shown properly with D7 custom theme

texts:
I am currently building a D7 theme for a website. I experiment some problems with the search page. After entering a search term the page "domain.com/search/node/[searched term]" is opened. But it just show the base page with nothing in the main-content block.

With another theme it works : results are shown properly on the search page and I can see both node tab and user tab. I assume something is wrong in my theme. I try to override
"search-results.tpl.php" because I read that this template is used to build the search page, but in my case it seems that the template is not used because if I put this code on it :

<?php print "foo"; ?>

there is no changes on the search page.

Any ideas ?


texts: Is there an easy way to load a related entity from an entity?

texts:
I have a content entity that references another entity, ie:

public static function baseFieldDefinitions(EntityTypeInterface $entity_type) {
  $fields = parent::baseFieldDefinitions($entity_type);

  $fields['other_entity_id'] = BaseFieldDefinition::create('entity_reference')
      ->setLabel(t('Other Entity'))
      ->setSetting('target_type', 'other_entity')
      ->setDisplayOptions('form', array(
        'type' => 'options_select',
        'weight' => 0,
      ))
      ->setDisplayConfigurable('form', TRUE);

Is there an easy way for me to load the other entity from the entity that references it?


texts: When a link is clicked, a value is retrieved from the table and displayed on a Webform field

texts:
I have created a basic page with two buttons, "Yes" and "No". When the "Yes" button is clicked, it is directed to the webform.

Aim: When the webform appears, it displays a value from the table into a field.

Database

Table name: Room
Field: Room
Data: Training Room

The Basic Page

The Webform

I created a module for this functionality:

test_presave.info

name = "Test presave"

description = "Retrieving data from table"

core = 7.x

package = Test

test_presave.module

/*

*Implements hook_node_presave()

*/

function test_presave_node_presave($node)

{

    $accessnode=$node->nid;

    if($accessnode==20)//Lettable Room Booking webform

    {

        $result=$db_query("SELECT Room FROM {Room} WHERE Room =:ln",array(':ln'=>'Training Room'))->fetchCol();

        $node->webform['components'][1]['value']=$result;

    }

}

Am I using the correct hook?

Do I have to use the node api or the webform api?

Can you help me with this?


texts: How to use a drupal footer and header on an external page

texts:
Sorry if the title is not the best description, it is my first time working with Drupal. My client has a portal created on Drupal 6.22, I'm creating a concurrent website for him, and he wanted to use the same header and footer that is created on the Drupal portal on my area.

So basically I would like to know if there is a include, or reference I can add to my website that would use\compile\something that Drupal header\footer on my layout.


texts: How to get attached files outputted by views for given node id (programatically)

texts:
I am working with a module.
I have a node id. That node id is a page and it has 2 or more view blocks on it. The results of views are lists of nodes with file attachments.

I need to get all the files attached to the nodes outputted by the view on this particular page.

I work in a module file and I can supply the nid of type page where these views sit.

I could not find much help so I decided to ask for what would be the best way to approach this.

I am new to Drupal so I will appreciate a great explanation on how to approach this.


texts:
I need to export some data directly from a D7 DB. I'm not that familiar with the Drupal DB schema. Some additional profile fields have been added to users profiles and I would like to export that along with some columns from the users table.

In this case the job_title custom field data appears to be stored in the field_data_field_user_job_title table.

In that table I notice there are columns entity_type and entity_id. The value entity_type is set as user for all rows in this table.

Does this mean that the entity_id field for rows in this table where entity_type='user' can be joined to users.uid to associate the custom profile data with the correct user record?


texts: white screen after clicking home menu button in drupal

texts:
i am using splashify module (for customized front page) in drupal. after accessing the website content and then finally clicking the home menu button in drupal website going white screen display. then again pressing enter key only displaying the home page of the website. can any one suggested me how to rectify this problem. if i am not using splashify module, website working normally. please help

this is the website url : www.kodikunnilsuresh.in


texts: I hope this question is not very naive, the problem is that in Drupal 8 there are several unit tests written for modules and I want to test them. But since I am on windows os I am not able to figure out by myself how to run them.Any ideas?


texts: How to grant permissions for some role to execute custom Rules Components?

texts:
I created a view (table) and i asociated views bulk operations. I created 4 rules components. I have permissions only for user/1 (admin). Another user role (eg. editor) can't see these options. "editor" user can see only "DELETE ITEM" rule components.

In permissions I have only the default actions (components); I created 4 new Rules Components, and these aren't displayed in Admin > People > Permissions.

Is there another method (trick) to give permissions for another role for custom Rules Components? Am I missing something?


texts:
I have a Drupal 8.0.1 installation running under Apache 3.4 from /var/www. During installation, I cannot seem to pass the requirements for clean URLs. I've read through answers I've found on Drupal.org, but to no avail.

Does anyone have any suggestions?


texts:
I am trying to use the icon API to pass an icon to the menu - I would use the icon menu module, but I want the icon to switch based on programmatic logic.

Here's what I have so far:

/**
 * Implements hook_menu().
 */
function MYMODULE_menu() {
  global $user;
  $icon = theme('icon', array('bundle' => "fontawesome", 'icon' => "envelope"));
  $items = array();
  $items['user/' . $user->uid . '/messages'] = array(
    'access callback' => 'user_is_logged_in',
    'title callback' => FALSE,
    'type' => MENU_NORMAL_ITEM,
    'menu_name' => 'main-menu',
    'title' => $icon . t('Messages'),
    'page callback' => 'views_embed_view',
    'page arguments' => array('message_private', 'page_1'),
    'file path' => drupal_get_path('module', 'views'),
    'file' => 'views.module',
        'options' => array('attributes' => array(
       'html' => true
       )),
  );
  return $items;
}

However this just seems to get the escaped icon HTML in the menu.

How do I get the actual item from the icon API?

Is there some way to tell hook_menu to pass everything as it is?


texts: Views 3 doesn't recognize a declared handler. Why not?

texts:
In modules/addressfield/addressfield.module I have:

/**
 * Implements hook_views_api().
 */
function addressfield_views_api() {
  return array(
    'api' => 3,
    'path' => drupal_get_path('module', 'addressfield') . '/views',
  );
}

and

/**
*  Implements hook_field_views_data_alter
*
* @param mixed $result
* @param mixed $field
*/
function addressfield_field_views_data_alter (&$result, $field) {
  if (array_key_exists('field_data_field_address', $result)) {
    $result['field_data_field_address']['field_address_country'] += array(
      'title' => t('Country'),
      'help' => t('The Country name of the field'),
      'field' => array(
        'handler' => 'addressfield_views_handler_field_country',
        'click sortable' => TRUE,
      ),
    );
  }
}

In modules/addressfield/views/addressfield.views.inc:

/**
 * Implementation of hook_views_handlers().
 */
function addressfield_views_handlers() {
  return array(
    'info' => array(
      'path' => drupal_get_path('module', 'addressfield') . '/views',
    ),
    'handlers' => array(
      'addressfield_views_handler_field_country' => array(
        'parent' => 'views_handler_field',
      ),
    ),
  );
}

This file doesn't get triggered in the debugger when I clear the cache. I don't understand this.

The handler is in modules/addressfield/views/addressfield_views_handler_field_country.inc which I took from the location module:

/**
 * @file
 * Country field handler.
 */

class addressfield_views_handler_field_country extends views_handler_field {

  function option_definition() {
    $options = parent::option_definition();
    $options['style'] = array('default' => 'name');
    return $options;
  }

  function options_form(&$form, &$form_state) {
    parent::options_form($form, $form_state);
    $form['style'] = array(
      '#title' => t('Display style'),
      '#type' => 'select',
      '#options' => array('name' => t('Country name'), 'code' => t('Country code')),
      '#default_value' => $this->options['style'],
    );
  }

  function render($values) {
      return check_plain(strtoupper($values->{$this->field_alias}));
  }
}

Any advice on how to get this to work would be helpful. Thank you.


texts:
I have put an exposed filter on my page, which is an auto-submit textbox without any submit button. When I put the focus on this textbox and refresh the page with no value inside the textbox, the page gives me an error which is caused by emptiness of the textbox.

**Error:**
An AJAX HTTP request terminated abnormally.
Debugging information follows.
Path: /************/views/ajax
StatusText:
ResponseText:
ReadyState: 4

What is your solution for it?


texts: How to implement a notifications on my webpages while any data insertion or updation occured on my custom tables

texts:
How to implement a notifications on my web pages while any data insertion or updation occured on my custom tables.

My requirement is for an auction website where once an user places a bid, then all the  other logged in users in that region should get the notifications.


texts: Using field api to get key of select list option

texts:
I need the safe output of a key from a select list field within a field collection item.

I'm theming a field collection item and one of the fields is a select list like:

icon-map|Map
icon-info|Info
icon-pencil|Pencil

I'm using the following to create some easy to use variables;

$fields = array_keys($content);
foreach ($fields as $field) {
  $field_items = field_get_items('field_collection_item', $content[$field]['#object'], $field);
  $$field = render(field_view_value('field_collection_item', $content[$field]['#object'], $field, $field_items[0]));
}

This works fine for all fields except for the select list.  I need the key of that select list.  For this select list field, $field_items is an array which looks like:

array(1) { [0]=> &array(1) { ["value"]=> string(13) "icon-map" } }

However, $field_icon (result of $$field = render(..) ) is Map, which makes sense.

I can get the key by using $field_items[0]['value'] but I'm not sure that's the best way.


texts: Hide/unhide based on number of values in multifield

texts:
I want a dependent field to be hidden if a dependee has less than three values, and shown if the dependee has three or greater.

So far in my research, I've not seen a way to do this with states or Conditional Fields, it has "value" but not "number of values."

I would love some help or just to be pointed in the right direction. Thanks in advance.


texts:
I am getting the below fatal error when i click content type > content x > manage fields > click edit:

"Fatal error: Call to undefined function drupal_array_diff_assoc_recursive() in /home/content/65/11722765/html/sites/all/modules/token/token.pages.inc on line 23"

Please help.

D


texts: How to call default node validation functions

texts:
I have a custom node-creation form for which I have my own validation function. How can I make sure that after my validation function the form goes through the same validation that it would have done on the original node-creation form?
Some thing like node_validate looks like the kind of thing I need, but it works on $node objects rather than forms.
The order of operations I perceive to be the best is

On submit run custom validation
If custom validation passes run the normal node validation
If node validation succeeds insert values in the database

Is that a good and Drupal way?


texts: How to configure programmatically a unique constraint on several fields of a custom entity?

texts:
How could I configure a unique constraint on several  fields of a custom entity I have already created with drupalconsole.

The purpose is not allowing insert of two record of the same entity having for example same lastname and fisrtname.


texts: Installing Acquia BLT on an existing site

texts:
We have a working Drupal 9 installation (running within Docksal), which has pretty much the whole install living in docroot/ except for the config/ directory, which is a sibling of docroot/.  This application is fairly plain-vanilla--no custom modules, just some well-known contrib modules and normal config.  I will refer to it herein as the "working app."
In order to get this application onto Acquia Cloud and set up our CI/CD we hope to use their BLT utility.
We have tried several approaches to get BLT working with this application:

Create a Docksal Drupal 9 BLT boilerplate application and attempt to use
composer install to get the same set of modules as the working app, and
then import the working app's configuration with fin drush cim.
Create a Drupal 9 BLT
boilerplate application and hand-edit composer.lock with selections
from the working app's composer.lock file, run composer install, and
then import the working app's configuration using fin drush cim.
Install BLT within the
working app as described here:
https://docs.acquia.com/blt/install/adding-to-project/.

Approaches 1 & 2 did not work because of incompatibilities between the BLT boilerplate app's composer configuration requirements (minimum-stability dev and prefer-stable true) and those configurations in the composer.json file of the working app.  There were also version incompatibilities between the contrib modules in the working app and those which the BLT boilerplate app wanted to install.   Hand editing the composer.json file also proved equally fruitless.
Using approach 3 we got as far as installing BLT in that the blt/ directory and associated files are now present, but blt doctor complains of a missing docroot/docroot directory.  Looking at the differences in the filesystem layout between the BLT boilerplate app and the working app made it seem like it might be worth trying to move vendor/, sites/, composer.json and composer.lock up one level from within docroot/ such that those two directories and two files are now siblings of docroot/ and seeing if that satisfies blt doctor.  Doing this of course breaks the application and makes composer unhappy.  I have tried the following:

Deleting everything in vendor/ and running composer install
Running composer dump-autoload
Hand-editing docroot/autoload.php looking for and
attempting to edit incorrect filesystem locations within the
relocated vendor/ directory

As you can imagine, none of the above have worked and we are just about at the end of our patience with this endeavor.
I have a few general questions:

Are any of the three approaches above likely to result in a successful BLT install?
With regard to approach 3, is there a generally accepted method of moving either vendor/, composer.* and/or the sites/ directory as described above?

Thank you in advance for any general or specific help you can offer.


texts:
services version 7.x-3.1   drupal version 7.12

I upload file in Base64 encoding with rest services

  resource_path: file.json

how can i delete file with rest services?
i now how to delete node

  resource_path:node/nid.json,  resource_type:DELETE

i test

  resource_path:file/fid.json,  resource_type:DELETE

but receive 404!


texts:
I have setup a product which has multiple variations as the image shows:

My variations have a colour taxonomy which I'm trying to use for when a user wishes to switch between variations on the same product.

My problem is the product node is not presenting any option for selecting the list of available colour nor is there an add to cart form.

I'm sure I'm missing one or two things ... I could use a second opinion, please.

UPDATE:

I already had the "Enable this field to function as an attribute field on Add to Cart forms" selected but didn't work.

I noticed in step#2 of the answer you directed me to, the taxonomy field is created in a Variation entity type.
However, I don't see a Variation entity listed on my site.
I'm adding my colour taxonomy field into the product type entity as shown in the image below:


texts: best practice for email validation in form alter drupal 7

texts:
What is the best recommended drupal way to validate an email is input on a new field I added in drupal settings page? Here is the code I have now:

function MYMODULE_form_uc_order_settings_form_alter(&$form, &$form_state, $form_id) {   $form['MYMODULE_uc_order_template_email'] = array(
'#title' => t('Template Email'),
'#default_value' => variable_get('MYMODULE_uc_order_template_email', 'test@example.com'),
'#description' => t("Template Email"),
'#type' => 'textfield',
 );

}


texts: Why my stylesheet won´t load into my node/add forms? (D6)

texts:
I wanted to have a special template for all my node/add forms, in my Drupal 6 installation.

So, I´ve added this code to a little module:

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

My node-add.tpl.php template looks like this:

<?php print $title ?>

<?php print $content ?>

The thing is that all styling has gone.

The style sheets won´t load, and I don´t understand why. It looks as ugly as it can get when no style whatsoever is loaded.

I may add that I´ve cleared cache more than once, and as this is a testing site, all performance caching has been disabled.

Thanks for your help!!


texts: Drupal 7 form missing from $form object during Ajax callback function

texts:
I'm using this example code to create a 'add another field' to my custom Form. The form itself is quite big and showing a full example here isn't possible.

The problem I'm having is that when I hit my callback button to 'add another field' the $form variable is missing most of the form I wish to utilise. My form is an admin area only form, but using the above example works fine in my implementation as POC.

The form utilises vertical_tabs but I have also tried without. I have a lot of validation around this form and in essence it's being built of a yaml file but I can't work out why the form elements are missing during the ajax callback. $form_state contains all the values submitted by the form including the missing data from $form.

I had assumptions that #tree was the issue but, I have this set to TRUE from the start.


texts: Out of the several possible ways, what is the best practice for getting a field value for an entity?

texts:
There are many different ways to get a field value from an entity.  For example, a text field:

$entity->get('title')->value;
$entity->get('title')->get(0)->get('value')->getValue();
$entity->get('title')->get(0)->getValue()['value'];
$entity->get('title')->first()->get('value')->getValue();
$entity->get('title')->first()->getValue()['value'];

And so on.

And then, depending on the entity, for the entity title (or name or label), you can sometimes do...

$entity->getName();

What is the best practice?  The first expression above (using the "value" property) is most concise -- are there any drawbacks to using it?

Is there any reason to prefer the first() helper instead of get(0)?  Why does the first() helper exist?  Are there cases when the first value in a field list doesn't have a 0 index?


texts: How Do I improve the performance of my Drupal7 Site?

texts: For somebody who is new to Drupal,  I see that there are many resources available on Drupal Caching but I am not sure which of them to use.


texts:
I have a base, sub theme, and sub sub theme. I don't want the sub sub themes CSS to be grouped to CSS_THEME due to support for legacy IE browsers and the issues associated with large CSS files.

$value['group'] = 100 = CSS_THEME = (Theme-Layer CSS)
$value['group'] = 0 = CSS_DEFAULT = (Module-Layer CSS)
$value['group'] = -100 = CSS_SYSTEM = (System-Layer CSS)

Possible to add to this with a different weighting?

$value['group'] = 200 = CSS_SUB_THEME = (Sub Theme-Layer CSS)

Adding CSS to separate group.

  // Add sub sub theme css to separate group.
  drupal_add_css(PATH_TO_THEME/sub_sub_theme.css',
    array(
      'group' => CSS_SUB_THEME,
    )
  );

NOTE: not looking for related answers to legacy IE browser limitations as solutions such as css_splitter are already in place, simply can the above be done or is there a good reason you can't.


texts: Custom menu with drupal_get_form plus form_alter_hook

texts:
I'm working in Drupal 6 to create a custom module. I have a menu that creates some custom URLs and tabs for me, and each item runs a page callback function, which itself runs drupal_get_form.

What I'm observing is that this process does not run mymodule_form_name_alter. While this makes sense, I'd like to achieve both of these ends.

Here's some of what I currently have:

function module_accounts_menu() {

  $items['user/%user/preferences'] = array(
    'title'            => 'Preferences',
    'page callback'    => 'module_accounts_category_form',
    'page arguments' => array('preferences'),
    'access callback'  => 'module_accounts_edit_access',
    'access arguments' => array('access content'),
    'type'             => MENU_LOCAL_TASK,
    'file'             => 'user.pages.inc',
    'file path'        => 'modules/user',
    'weight' => 1
  );

  return $items;
}

function module_accounts_category_form($category = 'account') {
  global $user;
  $account = user_load($user->uid);
  return drupal_get_form('user_profile_form', $account, $category);
}

function module_accounts_edit_access(){
  global $user;
  return user_edit_access($user);
}

function module_form_formid_alter(&$form, &$form_state) {
drupal_set_message('tes');
$form['#attributes'] = array('class' => 'user');

// some more stuff that does not happen

}

So basically, it's really helpful for me to have the custom menu links, but not at the expense of my form hooks. Is it possible for me to have both of these?

Thanks.


texts: Send Email After User has confirmed email address using Rules

texts:
I my drupal site, I have checked Require Email Confirmation to enable email confirmation. In this case it is sending an email with link to confirm email to set password for account.

Now when user has confirmed email address and set password for account, I want to send email to the user informing of confirmed email.

I have looked Rules Module for this, but there is no any such even present.

Any suggestion how can I implement this using Rules module.

-- Many thanks for your time


texts: Drupal Commerce: Set Order as Paid in Full

texts:
I am trying to import records from a CSV file (from another non-drupal database) for a membership site I am porting to Drupal 7. I have Drupal Commerce, Commerce Recurring Framework set up. Everything works as it should when you go through the proper work flow. However, I have 2000+ records that need to be added to the site and going through that process doesn't make sense. In other words, I am writing a script to set up the order and then recurring entity for each user.

I have code that creates my order, the issue is that Commerce is looking for a payment to be made before it creates the recurring entity for the order. Again, that doesn't make sense from a time perspective, not to mention all of these members have already paid as these are being ported. So my question is how to I trigger the order paid in full event that will trigger the creation of the recurring entity being created? Or is there a way to just create the recurring entity?

Here is my code:

<?php
foreach ($records as $record) {
$product_sku = $record['sku'];

$order = commerce_order_new($user->uid, 'completed');

commerce_order_save($order);

$product = commerce_product_load_by_sku($product_sku);
$line_item = commerce_product_line_item_new($product, 1, $order->order_id);

commerce_line_item_save($line_item);

$order_wrapper = entity_metadata_wrapper('commerce_order', $order);
$order_wrapper->commerce_line_items[] = $line_item;

commerce_order_save($order);
}
?>

Thanks,
Aaron


texts: DeployAuthenticationException: Authentication error when try to push the content

texts:
I have two sites on my localhost registration and testing. I want to push the content (node having type article) from testing to registration.I am using Deploy module to do this, by following this procedure.
"https://www.drupal.org/node/1406134"

Everything is OK until I click "Deploy" on testing. When I do I get the following error:

my path to endpoint is "/services/rest. and I also visit here
Authentication error when deploying site's content

but my issue still open.


texts: How to force a field to allow unlimited number of values using Field API?

texts: How do I force an unlimited number of values using code for a field I created using the Field API in Drupal 7? In this case it doesn't make sense to have any other setting so every time I create an instance of this field I have to set the number of values from 1 to unlimited.


texts:
I use the Admin Menu module for my projects. In my Drupal 7 and Pressflow 7 instances, it randomly shows only some menu items.

At first, I thought I could correct this by clearing menu cache. When I went to the front page, I once again got the corrupted menu.

How do I solve this error, permanently?

I found out this issue is reported in detail, but there is only a workaround (disable menu caching).

I disabled menu caching with drush vset admin_menu_cache_client 0 as a workaround.
(I am still testing this issue with the menu cache enabled.)

I checked and eliminated JavaScript errors using Firebug browser extension.

I removed BOM from *.js files as suggested in this answer.


texts:
I have created a form in my custom module, and I want to show it in a popup. I used the Modal Forms module, but it has some issues.

How can I display a custom form in a popup?


texts: Can't generate stack trace for EntityMetadataWrapperException, even with Devel and ddebug_backtrace()

texts:
I have the following error on a product display page on Drupal 7 :
EntityMetadataWrapperException : Unknown data property field_attribute_name. dans EntityStructureWrapper->getPropertyInfo() (ligne 354 dans /***/sites/all/modules/contrib/entity/includes/entity.wrapper.inc).

The line given is useless as it's in the generic entity class, I need the stack trace to see what's actually causing the error.
I followed steps in another stackexchange question about this, including installing the Devel module, setting it to display Krumo backtrace, adding the ddebug_backtrace() function just before the line in the error, but none of them had any effect at all. No visible change at all on the error page or in dblog.
Any idea on how to debug this?


texts: Re-enable System theme file within a child theme

texts:
I have the bootstrap theme installed.

I have a custom theme installed.

The bootstrap.info.yml file has the lines:

libraries-override:

# Remove individual stylesheets.
  system/base:
    css:
      component:
        css/components/ajax-progress.module.css: false
        css/components/autocomplete-loading.module.css: false
        css/components/tabledrag.module.css: false

In my custom_theme.info.yml file, how can I re-enable the ajax-progress.module.css file?

I've tried adding the following, thinking it would override it, but it doesn't seem to work.

libraries-override:

# Re-enable individual stylesheets.
  system/base:
    css:
      component:
        css/components/ajax-progress.module.css: true


texts: How to properly use two contextual filter for taxonomy

texts:
this is my case:

I have a content type called "norm".
Each norm has two fields with taxonomy terms: "issuing institution" and "norm type".
Each taxonomy field has its own vocabulary.

I'm making a View that will:

Filter all the "norms" that are issued by "institution A" or "institution B".
Has two contextual filters. One for "insitution", second for "norm type".
If the first parameter is not given, just show a summary with the instituions (in this case, just two institutions). [This is working]
Then, if the second parameter is not given, just show a summary with the "norm type". I mean this will be a list of norm types that has been issued by institution %1 (first parameter).

But, the last is not working. It shows again the instituion.

How can I do this kind of thing?


texts: Aggregation and grouping with dates and integers

texts:
I am using Views along with Highcharts Module.

Here is my objective:

I have some integers that are contained in nodes 3 different integer fields to be exact.
These integers occur over a duration of time and are entered on various days.

What I am trying to do is sum all the integers that happen on the same day.

Example:

Day 1 - 5/24/12

node #1
integer field: 10

node #2
integer field: 10

node #3
integer field: 10

node #4
integer field: 10

node #5
integer field: 10

Day 2 - 5/30/12

node #1
integer field: 20

node #2
integer field: 20

node #3
integer field: 20

node #4
integer field: 20

node #5
integer field: 20

Desired output of data for highcharts would be:

Day 1 - 5/24/12
integer field: 50

Day 2 - 5/30/12
integer field: 100

I have tried to use grouping and aggregation but I could not get a desired display.
I could get all nodes to display but could reduced them down to the desired result.

Please let me know if I can clarify in any way or if this is even possible

thanks!


texts:
We have a View showing all nodes of type 'member'. We have set permissions to view this node only for authenticated users. If anonymous user tries to access this view then it displays blank page. We expected that it will be redirecting to the page set under 'admin/config/system/site-information' for the 403 page(Access denied), but it is not. It is redirecting if anonymous user tries to access any node instance of 'member' itself but not if the view. How to configure 'Access denied' page for a view? Thank You

Drupal 7.23

Thank You


texts:
As question states, i'm trying to make a custom menu ( hook_menu() ) to call the same pages as how commerce does it originally (will link everything below)

The idea is to let Authenticated users add products (of all product types)
I have changed the permissions for creating product entities
and can acces, as Authenticated users, the add form via the the admin url

But i'd like to change that so they have a custom link and don't see the whole admin/commerce/products/add/bag

but only
/products/add/bag

i have tried to do this by adding a custom menu with the hook_menu() but always get an 'You are not authorized to access this page.' message, even when i am connected as admin

Anyone any idea what i should change to be able to acces it outside de admin zone?

my hook_menu():

function TTK_product_form_menu() {

  //non admin form
  if (function_exists('commerce_product_types')) {
    $commerce_product_bp = drupal_get_path('module', 'commerce_product').'/';

    foreach (commerce_product_types() as $type => $product_type) {

      $items['products/add/' . strtr($type, array('_' => '-'))] = array(
        'title' => 'Create !name',
        'title arguments' => array('!name' => $product_type['name']),
        'description' => $product_type['description'],
        'page callback' => $commerce_product_bp.'commerce_product_ui_product_form_wrapper',
        'page arguments' => array(commerce_product_new($type)),
        'access callback' => $commerce_product_bp.'commerce_product_access',
        'access arguments' => array('create', $type),
        'file' => $commerce_product_bp.'includes/commerce_product_ui.products.inc',
      );
    }
  }

  return $items;
}


texts: How do you perform a Guzzle POST request with "Basic Auth" for the current user?

texts:
In my class, I have the following request:

    $rest_response = $client->post($endpoint, [
      'auth' => ['admin', 'admin'],
      'body' => $serialized_entity,
      'headers' => [
        'Content-Type' => 'application/hal+json',
        'X-CSRF-Token' => $token,
      ],
    ]);

It works because I have a user with the username/password as "admin"/"admin", but when that user's password is changed, it won't work anymore, as expected.

In the logs, I am getting an "access denied" error for the endpoint I am trying to POST to - and the user associated with that error says "Anonymous (not verified)". All other log messages printed out in my controller show the current user's username.

I am running Drupal core 8.1.9.

The question is - how do I use basic_auth to get the current logged-in user's credentials to be passed into the request?


texts: Group context on pages generated by views

texts:
I have two group page

node/%/posts and node/%/activity.

Inside these pages, I have a mini panel which requires group context to display. For some reason, the pages generated by views are not recognized as group context though its a menu tab inside the group. Did anyone had the same issue ?


texts: Undefined index: und on .tpl.php for content type

texts:
How can i fix the error message?

  the error message is Notice: Undefined index: und in include() (line
  9 of /var/www/html/sites/all/modules/custom/theme/icons.tpl.php).

my code is:

<?php
global $language ;
global $base_url , $base_path ;
$lang = $language->language;
$count = 0;
foreach ($data as $kay => $node_obj) {
    $node = node_load($node_obj->nid);
if (isset($node->field_description[$lang])) {
    $img_url = $node->field_icon['und'][0]['uri'] ;
$count++;

?>


texts: Create folders in custom installation profile fails when usind drush site-install

texts:
I am working on a custom installation profile, and am using $_SERVER['DOCUMENT_ROOT'] as part of creating custom folders inside <drupal-root>/sites/sitename.tld/.
It works as expected when using the UI installation process, but when I try to run it through drush site-install my_custom_install it fails. I expect this is because $_SERVER is never set in the CLI (at least that is what I could understand from search around for a solution).

In terms of the error I get when it fails, it is just a permission denied for creating the folder, since it tries to create it in /sites/sitename.tld in the root of the server, which it naturally does not have access to. It's this path that is correctly getting the document root in the UI, but not in CLI.

Code example that is creating the folder

copyTheme($from, $to, &$context) {
  $site_root = $_SERVER['DOCUMENT_ROOT'];

  $context['message'] = 'Copy theme';

  $source = $site_root . $from;
  $destination = $site_root . $to;

  try {
    // If the destination directory does not exist create it
    if (!is_dir($destination)) {
      if (!mkdir($destination, 0777, TRUE)) {
        // If the destination directory could not be created stop processing
        throw new Error('Could not create custom theme folder \'' . $destination . '\'');
      }
    }

    //if (chmod($destination, 0777)) {
    //  rcopy($source, $destination, $context);
    //}
  } catch (\Exception $e) {
    \Drupal::logger('custom_installer')->error($e->getMessage());
  }
}

Snippet of the actual error output during drush site-install
In the error, installtester.dev is the $project_domain and installtester is the $project_name.

Error: Could not create custom theme folder '/sites/installtester.dev/themes/custom/installtester' in /var/www/drupalvm/drupal/webroot/profiles/contrib/custom_installer/batch.inc on line 20 #0 /var/www/drupalvm/drupal/webroot/core/includes/batch.inc(252): copyTheme('/themes/contrib...','/sites/installt...', Array)
#1 /var/www/drupalvm/drupal/webroot/core/includes/form.inc(874): batch_process()
#2 /var/www/drupalvm/drupal/webroot/core/includes/install.core.inc(619): batch_process(Object(Drupal\Core\Url), Object(Drupal\Core\Url))
...

In case it is relevant, I am doing the development on drupal-vm via vagrant and virtualbox on a windows 10 machine.

Question
Is there a better way than using $_SERVER['DOCUMENT_ROOT'] to get the document root? one that will work both using UI install and drush site-install?.

Alternatively, is there a parameter I can check for if I use the --root option for drush site-install?


texts: pass view result from one view to another

texts:
I have a view that outputs field content, and outputs one result.  There are four additional views that I need to have this result passed to somehow so I can filter the nid of that result out of the possible results for the other four views.

It's the end of the day so I wrote this question in haste, if it is no clear, please ask for clarification.  I will review later and update if necessary.


texts:
How can I test for active MySQL connections? I am trying to move one site to windows platform, and MySQL connections are failing; db_query() returns FALSE.
I am not sure how to use drupal_test_mysqli().


texts: How to share only a particular link in a node using social media,instead of complete node?

texts:
Using user referral module i was able to generate referral link.
After this i enabled social media module in order to share the particular link to other people whom i would be referring.

While testing this,i came to know that instead of link,entire node is being shared.

Can anyone tell me  an idea as how to share only the link,apart from getting the entire node being shared


texts: A large amount of Tokens slows down everything - Placeholder Tokens

texts:
had anyone of you had a problem with too large amount of tokens? Because of having few content types (~8) with bunch of fields (~5-10 each) Token module generates too big table with replacement tokens. This is why I had to increase in settings.php available memory to avoid drupal from php error. I set 512M so it generates the output table now but it is so slow that it freezes Chrome.

It happens where I have this preview of available tokens. So it can be found in Pathauto or Custom Breadcrumbs.

This is how it looks like in Google Chrome HTML preview:


texts: Non-Members of Organic Group can still view Node links

texts:
I'm on Drupal 7 with Organic Groups installed.  I've created a Private Group for my IT Team, meaning that only members of that group can see the group content.

The problem I'm seeing is that when I publish group content, Non-Members can still see the node link from the homepage, and click on it, even though the content is not displayed.

How can I make group content only visible to group members?  (Meaning, the node itself is not visible to non-members.).


texts: Altering max-execution-time on a per module basis

texts:
I have some components (mass XML/CSV import) where we may need to set the PHP Max Execution Time beyond a 30 second cap. Is there a way I can lift this restriction on module-specific logic (with ini_set() for example) over having to force it inside a php.ini setting?

Before you ask -- yes, I know making this logic a Drush command would be better suited for this, but the nature of our host not providing SSH makes it difficult for us to install or use Drush.


texts:
Where does the value of entity come from in a field of a content type?

I am trying to understand how the property (if it is a property) entity is related to the field.

This question is more informative, I describe my case below.

I have a type of content News, in this I added field of type image called "field_image" with a limit of a single value.

Type of content: News
Field: field_image

Debuggin:

I programmatically load the node:

// Return Drupal\node\Entity\Node;
$node = $this->entityTypeManager->getStorage("node")->load(1);

// {\Drupal\file\Plugin\Field\FieldType\FileFieldItemList}
kint($node->field_image);

// {Drupal\file\Entity\File}
kint($node->field_image->entity); // from where comes from entity?

From the last example I show above ($node->field_image->entity), where does the property entity appear, how can field_image access it and know that it is a file type field?

I'm just trying to understand these internal Drupal relationships.
Thank you very much for helping me understand this.
regards


texts: Google Analytics to sort by amount of traffic in the last 24 hours only

texts:
I am using Google Analytics Counter at the moment to sort the content by traffic (in Views). However, at the moment Google Analytics Counter only supports Pageview Total which is the total views (all time). What I am looking for is to sort the content by amount of traffic in the last 24 hours only.

Created an issue in the project page as well: https://www.drupal.org/node/2507213

I am also reading the Google Analytics doc now (first acquaintance). Thinking that I might need to do some settings on Google Analytics panel in order to achieved what I want.


texts: EntityQuery condition "is not equal to..."

texts:
Problem :

I need filtering entities based on the value of a multiple-choice field.
I want my query returns all entities except those who have a given value ('doe' for this example).

Actual :

multiple-choice values

foo|Choice 1
bar|Choice 2
doe|Choice 3

MyController.php

$query = \Drupal::entityQuery('node')
       ->condition('type', 'order');
$nids = $query->execute();
$entities = \Drupal::entityManager()->getStorage('node')->loadMultiple($nids);

Need :

So I need something like below :

$query = \Drupal::entityQuery('node')
       ->condition('type', 'order')
       ->condition('field_multiple_choice', '!=', 'doe');
$nids = $query->execute();
$entities = \Drupal::entityManager()->getStorage('node')->loadMultiple($nids);

How can I do ?
Thank you in advance.


texts:
I have a couple of forms where I need to attach metadata fields to files (a description, and a category).

The file_entity module alone lets me specify fields, but doesn't change the form fields.

When enabling the Media module, it sort of works, but the Media module

does its work in an overlay, which is unacceptable - I need something that looks like if you enable the "description" option in the core File element
breaks the look of the site as soon as I click on the "edit" button that opens the overlay - it loads the entire Bartik CSS even if the current theme is not related or using Bartik!
is way too overcrowded - I don't need support for youtube
is a security hole because people can browse all uploaded files!

So, basically, I need some way to attach a dropdown box to the standard file upload widget, nothing more - how do I achieve this? If possible, I'd prefer something that integrates at least with file_entity, so I don't have to define the field in code.


texts: How to configure the CONTEXTUAL FILTER in a View for Rules?

texts:
I want to make a component that receives a user as parameter, and will then do something with some of that user’s content.

That something is: delete nodes of contenttype FICHE that have a due date in the past and copy the content of that node to a variable_mailbody. Send the variable_mailbody when all records of that user are processed. (After testing the component, it will be called in a viewloop of all active users, so it will be executed for all members, one after another, periodically.)

I know how to make a view that selects all nodes with a due date in the past. This will give me all the nodes to delete, but I want only those for this respective user, because I do not want to send a mail for each deleted item.

So how to configure contextual filter to limit the result to only the nodes of the user for which the component is being executed? Or should I tackle this in a different way?


texts: Views filter based on value in referenced entity

texts:
I'm attempting to use a view to display the body of a content type that is referenced based on a field referencing another content type as long as that content type is referenced by another field. Confusing I know. Here's a diagram of what I'm trying to accomplish.

I need to display the body and title of all 'news' that reference a 'horse' that an 'owner' references as long as that 'owner' is referencing the current user.

I understand that there would be much better ways to structure my content type fields to get them to play more nicely, and I understand that I could easily accomplish this by not using views and making a custom module but that isn't an option available to me. I am required to use views. I wouldn't mind creating a custom views filter plugin, or use a hook though. I understand how to perform entity queries that can accomplish this task. However I'm not sure how view filter plugins work.

Is there a way to accomplish this specifically with views?


texts: Taxonomy term listing of nodes with the term in a paragraph

texts:
I found similar questions but not an actual answer...
This is my setup In Drupal 8:

  Node

    Paragraph

      Taxonomy term reference

I would like to use the default taxonomy term view (taxonomy/term/%) to display a list of node teasers in which the paragraph contains the term. I'm probably passing the wrong contextual filter but I couldn't figure how to fix it.


texts: Copy whole field from one entity to another

texts:
i want to copy a field from one entity to another while processing a rule.
my current code looks like this:

<?php
    $entity_created->field_ort = $entity_fetched->field_ort;
?>

but instead i get an error message:

Notice: Trying to get property of non-object in eval() (Zeile 3 von /www/www/sites/all/modules/rules/modules/php.eval.inc(125) : eval()'d code).

so i found this site http://drupal.org/node/1000200 which tells me that i need to do this more like this:

<?php
    $entity_created->field_ort['und'][0]['value'] = $entity_fetched->field_ort['und'][0]['value'];
?>

but what about lists and other fields? is there a more generic approach? i need to copy about 5 or more fields.


texts: How to parse a URL's content into a Drupal node

texts:
I'd like to create a node type in which I'd have an URL field, title and some description. Once I create a new node using this content type, Drupal would parse the contents of the URL I've added in the URL field. It'd work almost like one of these read it later services.

Is this possible, if its how? I've been looking into feeds, but its not exactly what I'm looking for (as it deals with rss/atom rather than url).

Background: Basically I'm creating a personal wiki using Drupal and wanted the ability to parse content directly to a node type. This way I can categorize the way I want as well as being able to create views, aggregate different content, etc. This is for a personal project and the site wouldn't be public.


texts: Granular role access on a per Entity basis

texts:
I have a config entity that I would like to grant access to on a role based level. There is going to be one role to access the entities, but how can I assign access on a per entity basis?

My naive thinking is to add a $roles array instance variable, and add each individual role to that, then create a custom EntityAccessControlHandler class, implementing EntityAccessControlHandlerInterface that checks the array for all of the users roles, but that doesn't seem like a very good solution.


texts: How to resave all user accounts on a schedule?

texts:
I want to re-save all user accounts on my site weekly because I wrote some code in hook_user_presave() that I want to update every week.
Specifically, my hook_user_presave() code updates the values of some fields like Total number of comments posted and Total number of articles posted, and it sends an email if the user hasn't logged in for more than a month. (This info is only available to the site admin, which is me, so it doesn't need to be perfectly in sync.)
Right now, I have a View with VBO that I can use to re-save all the user accounts manually. I want to automate this process by saving all the users automatically at 3 am on Sunday.
How do I schedule all user accounts to be saved?  Is this a task for Queue API or does core/contrib provide something more appropriate for this use case?


texts: In which file to add the cache_clear_all function

texts:
In my situation I would like a certain block on my page with real time information to not be cached for anonymous users. Literature listed below:

https://www.drupal.org/node/42055

https://www.lullabot.com/blog/article/beginners-guide-caching-data-drupal-7
suggests using the

cache_clear_all('modulename', 'cache')

I added this on my module inside the hook_block_view() function. This does not work though. Any directions on where I can use this function.
Here is the function information:
Clearing specific entries in cache tables
The Drupal cache API can be used to clear specific items. Caching back ends can be switched (to memcache, to flat files, etc.) without having to rewrite any code.
cache_clear_all('content:' . $MYNID, 'cache_content', TRUE);

The example above clears all items from cache that start with 'content:$MYNID*'. To ONLY remove one specific row, drop the $wildcard parameter (the "TRUE" statement in the function call) and change the format of the first parameter to omit the asterisk, which functions as a wildcard.
cache_clear_all('content:' . $MYNID . ':' . $MYNID, 'cache_content');


texts:
I am working on a new module that will store stock levels in multiple inventory locations. What is the "best" way to store the data? I am slow to just attach and array of key/values to the product object and think I should use an entity instance for each warehouse. A few things that might effect what "best" is:

need to be conflict free with existing commerce simple stock module
need to be able to show individual stock locations via Field UI using conditional fields or Rules.
need to be able to iterate through all of the stock location
Each stock will have name, stock value, and a few other properties such as geo location
List item would like to use field group to displace the multiple values with existing formatters and widgets.
Commerce uses inline entity fields that might be good pattern to use
I intend to be a Commerce Stock submodule and would like to leverage as much Commerce Stock functionality as possible.


texts: Rules: Copying field from user's account to field in content type

texts:
D7.
Using the File Field Rules module, I am trying to copy the content of the image field of the user's account ("picture") to another image field ("field_node_image") in the same user's image gallery (each user has his own photo gallery.)

The purpose of this is for when a user uploads a picture to his account profile, a copy of it is also posted in his image gallery along with all the other pictures he may post there (displayed via Views.)

The module requires the selection of a source entity and a destination entity. Then a field is chosen from each entity.

I am making the event react upon updating the user's account, so that gives me access to the "account" selector for the source entity where the module finds the "picture" field.

But I need help in finding the destination selector. This, evidently, should be a node since the gallery is a content type. It also has to be a node that belongs to the user. But all base selectors I have begin by "site" or "account."

Can anyone help me find this second selector?

Thanks. :)


texts: How to test a code where the config is involved as parameter?

texts:
I'm new to OOP concepts, also PHPUnit Testing is new for me. I want to get the configuration in my testcase.

XYZFormResult.php

namespace Drupal\xyz\XYZFormResult;

use Drupal\Core\Config\ConfigFactory;
use Drupal\webform\Entity\WebformSubmission;

/**
* Class XYZFormResult.
*
* @package Drupal\xyz\formgroup
*/
class XYZFormResult {

    /**
    * Defines the immutable configuration object.
    *
    * @var \Drupal\Core\Config\Config|\Drupal\Core\Config\ImmutableConfig
    */
    private $config;

    /**
    * XYZFormResult constructor.
    *
    * @param \Drupal\Core\Config\ConfigFactory $config
    *   Inject ConfigFactory.
    */
    public function __construct(ConfigFactory $config) {
        $this->config = $config->getEditable('xyz.settings');
    }
}

XYZFormTest.php

namespace Drupal\Tests\xyz\Unit\XYZFormTest;

//use Drupal\Core\Config\ConfigFactory;
use Drupal\Tests\UnitTestCase;
use Drupal\xyz\formgroup\FormsGroupResult;
use Drupal\xyz\formgroup\XYZFormResult;
use Drupal\webform\Entity\WebformSubmission;

/**
* @coversDefaultClass \Drupal\xyz\formgroup\FormsGroupResult
* @group xyz
*/
class XYZFormTest extends UnitTestCase {
    /**
    *
    * @var \Drupal\Core\Config\ConfigFactory|\PHPUnit_Framework_MockObject_MockBuilder
    */
    protected $config;

    public function testxyz() {
        $this->XYZresult = new XYZFormResult($config);
    }
}

When I execute this XYZFormTest testcase, I need to pass a parameter for XYZFormResult(), how to pass config parameter?

If I pass any string in XYZFormResult(), I'm getting error this error:

__construct() must be an instance of Drupal\Core\Config\ConfigFactory, string given error


texts: Language information in Session for anonymous users

texts:
I selected the language preference to be detected with user sessions, the problem is that for anonymous user this preference does not seem to be stored. As this site is not user driven (Meaning that site users don t need to create account in order to browse the site), it s very problematic.

Is there anyway to have this language preference stocked in anonymous sessions ?


texts: Why is my update query OK for the database but the page shows the wrong value?

texts:
I have 2 custom content entities created with Drupal Console (drupal generate:entity:content): 'person' and 'member'.
They are linked (1 member <-> n persons) by a field named 'member_id' in 'person'.
If a person is set with 'iscontact' = true, the other persons related to the same member should have 'iscontact' = false.

In the PersonForm.php, I have this code.

public function save(array $form, FormStateInterface $form_state) {
  $entity = $this->entity;

  if ($entity->get('iscontact')) {

    $member_id = $entity->get('member_id')->getString();
    $iId = $entity->get('id')->getString();
    $database = \Drupal::database();
    $query = $database->select('person', 'ap');
    $query->fields('ap', ['id', 'member_id'])
      ->condition('id', $iId, '<>')
      ->condition('member_id', $member_id, '=');
    $results = $query->execute();

    foreach ($results as $key=>$result) {
      $numberofrowsaffected = $database->update('person')
        ->fields(['iscontact' => 0,])
        ->condition('id', $result->id)
        ->execute();
    }
  }

  $status = parent::save($form, $form_state);

  switch ($status) {
    case SAVED_NEW:
      drupal_set_message($this->t('La personne « %label » a été ajoutée.', [
        '%label' => $entity->label(),
      ]));
      break;
    default:
      drupal_set_message($this->t('La personne « %label » a été modifiée.', [
        '%label' => $entity->label(),
      ]));
  }
  $form_state->setRedirect('entity.person.canonical', ['person' => $entity->id()]);
}

When I execute this, the table 'person' in the database is correctly updated, but in the page the previous person is still seen as having 'iscontact' = 1.
It's incorrect until I clear the cache.
What am I doing wrong?


texts: I am using hybridauth module for LinkedIn and twitter login. I have installed twitter module and twitter post module for posting node on twitter. After enabling twitter module Linkedin login via hybridauth not working, it shows a blank page. If I disable twitter module it works fine. Kindly guide me to resolve this.


texts:
I would like to generate an entity that contains image generated by another module file in drupal 7. This is my code :

//appel de la variable user
global $user;

//recuperation de lapercu
$apercu = $_SESSION['image_generate'];
//creation de lobject file
$file_apercu = new StdClass();
$file_apercu->uid = $user->uid;
$file_apercu->uri = $apercu;
$file_apercu->filemime = file_get_mimetype($file_apercu->uri);
$file_apercu->status = 1;
//sauvegarde en base
$file_apercu = file_save($file_apercu);
$file_apercu = (array) $file_apercu;
$file_apercu = array($file_apercu);

//recuperation du pdf
$pdf = $_SESSION['pdf']->uri;
//creation de lobject file
$file_pdf = new StdClass();
$file_pdf->uid = $user->uid;
$file_pdf->uri = $pdf;
$file_pdf->filemime = file_get_mimetype($file_pdf->uri);
$file_pdf->status = 1;
//sauvegarde en base
$file_pdf = file_save($file_pdf);
$file_pdf = (array) $file_pdf;
$file_pdf = array($file_pdf);

//recuperation du numero de commande
$form_panier = $_SESSION['form_state_panier'];
$sql = db_query('SELECT MAX("order_id")
                FROM commerce_order
                WHERE uid = '.$user->uid.'')->fetchAssoc();

//creation de lentity
$values = array(
            'type' => 'commandeflyer',
            'uid' => intval($user->uid),
            'status' => 1,
            'comment' => 0,
            'promote' => 0,
        );

$entity = entity_create('node', $values);
$ewrapper = entity_metadata_wrapper('node', $entity);
$ewrapper->title->set('commandeflyer'.$sql['MAX("order_id")']);
$ewrapper->field_flyer_image_commande->set($file_apercu);
$ewrapper->field_pdf->set($file_pdf);
$ewrapper->field_numcommande->set(intval($sql['MAX("order_id")']));
$ewrapper->save(true);
entity_save('node', $entity);

When I run this code I get this error :

EntityMetadataWrapperException : Invalid data value given. Be sure it matches the required data type and format. dans EntityMetadataWrapper->set() (ligne 122 dans /var/www/commerce_kickstart-7.x-2.9/profiles/commerce_kickstart/modules/contrib/entity/includes/entity.wrapper.inc).

But my type correspond : pdf for pdf and jpg for image. Thank you for help.


texts: How can I change the redirect that happens after a node is edited?

texts: Normally, after a node is edited, the user is sent to the node's display page.  I would like to change this so that the user is sent to a different page.  Is there a module for this or is there a native setting that I can use?


texts:
I want something like SELECT nid FROM node WHERE type = "blablabla".

How do I do this in Drupal 8 PHP code?


texts: Views math expression or Computed field to find date difference in views

texts:
I have two content type, Bill (Type1) and Cash Receipts (Type2), Type2 referencing Type1 when cash is received.

In Type1 I have date field called (Bill Issue date), and Type2 I have date field cash receipt date.

So I want to calculate, different between those two dates. I was trying by creating views with two date (by entity reference relationship), then subtract two filed with math expression field, but it return zero.

Actually, I have no idea whether I was wrong or Its not possible to calculate different between dates with views math expression field?

I think, it can be done with Computed Field, I did one within same content type, but I don’t know how to access a field from different content type, please help.

Code that I was used to calculate date for same content type, but how I can access a field from other content type?

If the Machine name of your date-field is 'field_example_date', then the Computed Code (PHP) would be

$startdate = $entity->field_example_date['und'][0]['value']; // Value of start-date
$enddate = $entity->field_example_date['und'][0]['value2']; // Value of end-date

$datediff = strtotime($enddate) - strtotime($startdate);
/* The PHP Function STRTOTIME parses the english textual datetime description
 * into a Unix timestamp
 */

$num_leaves = $datediff/(60*60*24);
/* Since we need the number of days IN-BETWEEN,
 * we divide the resultant difference by 60*60*24 .
 *
 * Incase of counting no.of days "FROM" to "TO" days, add 1 to the above result.
 * $num_leaves = $datediff/(60*60*24) + 1;
 */

 $entity_field[0]['value'] = $num_leaves;

The Display Code (PHP) will have

$display_output = $entity_field_item['value'];


texts: Why does the same Rule Calculating The Sell Price Of A Product fire multiple times?

texts:
I'm having dreadful performance with Commerce Kickstart 2. Trying to troubleshoot.

I noticed that when viewing any Product in the catalog, the Rules Evaluation log looks like the log below.

Questions:
1. Why is the event Calculating the sell price of a product firing multiple times?

Why is the rule "Apply a discount to a given order" firing? The product I'm viewing has nothing to do with the reaction rule or the cart?

This adding a lot of unneeded overhead, right? How do I stop it?

    0 ms Reacting on event Calculating the sell price of a product.
    7.329 ms Evaluating conditions of rule Unset the price of disabled products in the cart. [edit]
    7.698 ms The condition data_is_empty evaluated to FALSE [edit]
    7.903 ms The condition entity_has_field evaluated to TRUE [edit]
    8.669 ms The condition data_is evaluated to FALSE [edit]
    8.676 ms AND evaluated to FALSE.
    8.694 ms Finished reacting on event Calculating the sell price of a product.

0 ms Reacting on event Apply a discount to a given order.
0.256 ms Evaluating conditions of rule 10% Of AH-10. [edit]
0.854 ms The condition commerce_order_contains_products evaluated to FALSE [edit]
0.862 ms AND evaluated to FALSE.
0.876 ms Finished reacting on event Apply a discount to a given order.
0 ms Reacting on event Calculating the sell price of a product.
0.164 ms Evaluating conditions of rule Unset the price of disabled products in the cart. [edit]
0.317 ms The condition data_is_empty evaluated to TRUE [edit]
0.324 ms AND evaluated to FALSE.
0.336 ms Finished reacting on event Calculating the sell price of a product.
0 ms Reacting on event Calculating the sell price of a product.
0.376 ms Evaluating conditions of rule Unset the price of disabled products in the cart. [edit]
0.656 ms The condition data_is_empty evaluated to TRUE [edit]
0.673 ms AND evaluated to FALSE.
0.7 ms Finished reacting on event Calculating the sell price of a product.
0 ms Reacting on event Calculating the sell price of a product.
0.223 ms Evaluating conditions of rule Unset the price of disabled products in the cart. [edit]
0.407 ms The condition data_is_empty evaluated to TRUE [edit]
0.42 ms AND evaluated to FALSE.
0.439 ms Finished reacting on event Calculating the sell price of a product.
0 ms Reacting on event Calculating the sell price of a product.
0.221 ms Evaluating conditions of rule Unset the price of disabled products in the cart. [edit]
0.384 ms The condition data_is_empty evaluated to TRUE [edit]
0.393 ms AND evaluated to FALSE.
0.418 ms Finished reacting on event Calculating the sell price of a product.

0 ms Reacting on event Calculating the sell price of a product.
0.398 ms Evaluating conditions of rule Unset the price of disabled products in the cart. [edit]
0.67 ms The condition data_is_empty evaluated to TRUE [edit]
0.687 ms AND evaluated to FALSE.
0.714 ms Finished reacting on event Calculating the sell price of a product.


texts: How to apply a distinct css class to each value of a field with multiple values?

texts:
In a similar manner to views-row classes, is it possible to add a distinct css class to each value of a field where cardinality is greater than one?

Ideally I am looking for a module that does this.


texts: CSS is automatically created in the sites/default/files/css directory

texts:
I unchecked the Aggregate and compress CSS files option from admin/config/development/performance. Still, when I am inspecting the element CSS styles, the location is the same (sites/default/files/css).

How do I change CSS styles in this case?


texts: Filter by content type and shared taxonomy terms

texts:
I want to classify my content within the following categories:

Technology
International Politics
Education
Religion
Sports

They are shared among my content types (e.g. news, page).
I want to create listing pages filtering by category, something like "news/international-politics" (notice the clean URL).

What is the best way to achieve this?

I've kind of done it with a shared taxonomy and a view per content type with an argument, but then I can't use the taxonomy links and have to build them by hand (cleaning the taxonomy name), but it's not a very clean solution.


texts: I am using D6. I want to add another argument to a view, but it only needs to be a word ie: 'practice'. Which type of argument do I chose in the list of possible argument types ie:node, content, global...


texts: Will forcing validation on a node save result in security issues or data integrity loss?

texts:
I have a content type containing lots of required and conditional fields. Because it can take a bit of time to properly create these nodes, and not all information will always be available to the end-user, I've implemented the ability for the user to "Save as Draft" while on this node's edit form.

Here's my form alter:

function mymodule_form_node_form_alter(&$form, &$form_state) {
  if ($form['#bundle'] == 'content_type') {
    // If node already exists and is not published, show "Draft" markup.
    if (isset($form['#node']->nid) && $form['#node']->status == 0) {
      $form['draft_markup']['#markup'] = '
Draft
';
    }

    // Add a new validate function to disable error checking on required fields.
    if (empty($form['#validate'])) {
      $form['#validate'] = array();
    }
    array_unshift($form['#validate'], 'mymodule_save_draft_validate');

    // Add 'Save as Draft' button
    $form['actions']['draft'] = array(
      '#type' => 'submit',
      '#class' => 'form-submit',
      '#value' => t('Save as Draft'),
      '#weight' => '0',
      '#submit' => array('mymodule_save_draft_submit'),
    );

    // Change submit button's text.
    $form['actions']['submit']['#value'] = t('Save & Publish');
  }
}

Custom validate function – the magic lies in &drupal_static('form_set_error', NULL, TRUE), where TRUE resets the static form_set_error variable:

function mymodule_save_draft_validate($form, &$form_state) {
  if ($form_state['triggering_element']['#value'] == $form['actions']['draft']['#value']) {
    // Set as unpublished.
    $form_state['values']['status'] = 0;

    // Force validation.
    $errors = &drupal_static('form_set_error', NULL, TRUE);
  } else {
    // Set as published.
    $form_state['values']['status'] = 1;
  }
}

Custom submit function – drupal_get_messages() stops "required" field errors from displaying when a user saves as draft, while a user doing the normal 'submit' will see the errors:

function mymodule_save_draft_submit($form, &$form_state) {
  drupal_get_messages();
  node_form_submit($form, $form_state);
}

Outside of obviously missing field data (which I'm not worried about since status = 0 and I can filter to never display unpublished nodes to the public) does anything stand out as dangerous here for a long-term, production site? Maybe the answer is simply "no", but forcing validation via &drupal_static('form_set_error', NULL, TRUE) makes me wonder if I'm opening the door to bigger security vulnerabilities. Because fields still run their validation, I am unable to get data to save that shouldn't be saved (i.e. if I try and put PHP code in a number input, the integer "0" is saved into the database - cool). Looking for a bit of peer review here...


texts:
I've created a Content Type that will have >50 fields. I've noticed that each field has a corresponding table. Is Drupal joining 50 tables in order to load the page with all of the designated content?

Would a high amount (but not an unnecessary) amount of fields cause a noticeable decrease in performance?

Thanks in advance for your answers.


texts: Why does nothing change when I attempt to restore a backup?

texts:
I have a drupal 7.43 installation and it has been doing regular backups using the Backup and Restore module.  I wanted to do a restore but I'm blocked at every turn it seems.  I go to Configuration >> System >> Backup and Migrate >> Saved Backups and click on "restore" next to the one I want to restore from.  I get a new page where I choose "Entire Site" to restore to, as that is what I'm backing up, and then click "Restore." That takes me to a white page.  When I reload my site, nothing has changed, so I assume this means failure, although I have no way of knowing what failed or why that I can tell.

So I tried drush:

drush bam-restore archive scheduled drupal.xxxxx.net-2016-03-21T09-44-17.sitearchive.tar.gz

This gave me a mysterious error:

  Restoring will delete some or all of your data and cannot be undone. ALWAYS TEST YOUR BACKUPS ON A NON-PRODUCTION SERVER!
  Are you sure you want to perform the restore? (y/n): y
  PHP Fatal error:  Call to undefined function file_directory_path() in /var/www/drupal.wealthychef.net/public_html/sites/all/modules/backup_migrate/includes/sources.archivesource.inc on line 211
  Drush command terminated abnormally due to an unrecoverable error.
  Error: Call to undefined function file_directory_path() in
      /var/www/drupal.wealthychef.net/public_html/sites/all/modules/backup_migrate/includes/sources.archivesource.inc,
      line 211

Can someone help me understand how to restore my site?


texts: Drupal module to make html pages of all nodes automatically

texts:
I am looking for a solution / module which can create the whole site in HTML .

So every time the user does content changes, he can click on a button, it will create the html for that node only or the whole site and syncs it to an FTP or same hosting.

I do not want to use caching or any other technique to speed up the site.

is it possible with drupal ?
thanks


texts: Duplicate part of the main menu to a sidebar

texts:
I am building a website like the one in the picture (here is the photoshop mockup :P) My question is the blue arrow!

I want to relate the main menu with the node as follows: When the visitor clicks on a parent item of the main menu (or a child of that parent menu) (let's say he clicks on "services" or on "Web dev" or "Web design" or "SEO") I want a submenu to be displayed, on the left sidebar, with "services" as the parent element highlighted and the sub elements also present (as shown in the photo).

If i use menu block and choose to display from a certain level and on, then I will have that level from the whole main menu depicted, and not just the active one, right? (for my example, in the left sidebar i only want to show the items shown, not "Home" or "About us" or "Contact us")

Which modules should I use? Can I do it with hook_page_alter, and if yes, how will I choose to only show the submenu of services and not the whole main menu? (Any directions are appreciated)

P.S. for what's worth, the main menu is a drop down Superfish menu with a depth of 2 levels.


texts: My server has been on MySQL 5.6 for quite awhile and now I need to upgrade to MySQL 5.7. Is it safe to upgrade to 5.7 for all of my Drupal 7.x sites? Just doing a quick google for drupal 7 mysql 5.7, I get a few people reporting issues when updating with Drupal 7.x.


texts: Is it possible to have multiple instances of the same field in one content type?

texts:
I understand that it is best reuse fields where possible and to avoid unnecessary duplication.

So is it possible to duplicate or reuse a field (or field instance) on the same content type?

For Example: A news article with both a cover image and an image gallery. Is it possible for both to use field_image or must there be two distinct fields, such as field_cover_image and field_gallery_image ???


texts:
I recently installed a theme that called for Panels Everywhere, Mini Panels, and Page Manager modules to be installed.  The theme looks great but I don't understand where all my custom pages went?

I had created a bunch of pages in my custom module using hook_menu().  Now my site is completely driven by Panels and Page Manager.  I assume all my MENU_NORMAL_ITEMS were being stored in a block that is now being suppressed by panels everywhere.

How do I get all my old menu items to work with my new theme?  How do I link up the elements of my theme with my existing pages?


texts:
There is a string which gets displayed in the mobile menu.

var arrowimages = {
down: 'downarrowclass',
right: 'rightarrowclass'
}, $mainNav = $('#navigation'), $mainList  = $mainNav.find('ul').eq(0), optionsList = '<option value="" selected>Navigate...</option>', $submenu = $mainList.find("ul").parent();

I want to make this string translatable using t() function. So edited the JS file like this:

var arrowimages = {
down: 'downarrowclass',
right: 'rightarrowclass'
}, $mainNav = $('#navigation'), $mainList  = $mainNav.find('ul').eq(0), optionsList = '<option value="" selected>'.t('Navigate...').'</option>', $submenu = $mainList.find("ul").parent();

After that the string was available for translation but the menu option was missing from the mobile view. Is there any solution for this? Or am I doing any mistake?


texts:
Afternoon Everyone,

I am having a few problems with a site we are having developed; although it is nothing significant it is quite annoying.

At the moment I am editing a fair amount of content ready for site-live but when I go to edit a page that I have names the node with a custom alias (ie /events/event1 ) I have to remember to go back into the node alias, uncheck the Automatic Alias box and put in the custom alias again.

If I don't do this, it becomes a second level page (ie /full-title-of-event-1 ) which obviously is not great.


texts: What does #optional mean for a "details" form element?

texts:
The node edit form contains the following form element.

  $form['revision_information'] = array(
    '#type' => 'details',
    '#group' => 'advanced',
    '#title' => t('Revision information'),
    // Open by default when "Create new revision" is checked.
    '#open' => $node->isNewRevision(),
    '#attributes' => array(
      'class' => array('node-form-revision-information'),
    ),
    '#attached' => array(
      'library' => array('node/drupal.node'),
    ),
    '#weight' => 20,
    '#optional' => TRUE,
  );

What does the #optional property mean for it?

I looked at both the Details and the VerticalTabs classes, but neither of them seems to handle that property.

What does setting #optional to TRUE do?


texts: Webform Select Element Optgroup / hierarchy

texts:
Hello fellow Drupal users, I have created an advanced HTML element in my webform. When the form is submitted the advanced html element reverts back to the default setting, which in this case is option A1. The users selection and data for this element is not in the submission.

This is the YAML an example form:

processed_text:
  '#type': processed_text
  '#display_on': both
  '#text': |
    <select  name="processed_textone" id="processed_textone" style="width: 570px;">
    <optgroup label="A">
        <option value="A1">A1</option>
        <option value="A2"> A2</option>
        <option value="A3"> A3</option>
    </optgroup>

    <optgroup label="B">
        <option value="B1">B1</option>
    </optgroup>

    <optgroup label="C">
        <option value="C1">C1</option>
        <option value="C2">C2</option>
    </optgroup>

  '#format': full_html

I would like to get the data of the selection upon submission. I tried using a computed twig and Ajax, but that doesn't seem to work either. I think I might be able to add a javascript file to get this data into the submission, but I'm not sure. I'm pretty new at subtheming and js in general.


texts: Have a profile field item from user registration show on a users page

texts:
I have created a new checkbox field through the core module 'profiles' called Billing Terms. It is visible on the user registration form.

I'd simply like an asterisk * next to the users name on their profile page if the Billing Terms checkbox is ticked. Actually it doesn't have to be an * but rather anyway to signify that the Billing Terms checkbox was ticked.

Any help or helpful links would be greatly appreciated.


texts: How do I distribute/share a project/product?

texts:
I have a site that I've built with Drupal 8, using composer and git to manage the code base. It's a fairly simple site that includes a handful of third-party modules, a few custom views, and a custom theme.
I am thinking about the best way to share this site as an open solution for others that may want to use it for themselves.
Should I consider an installation profile, a distribution, or just a git repository?
Is there any reason I couldn't share my Drupal 8 project simply by sharing the composer.json file and configuration exported data?


texts:
I have a content type available in FR and in EN.

In hook_node_presave(), I would like to concatenate the French title and the English title in another field. (This is an "helper field" which contains concatenate strings to be used by a filter in a view.)

This is my code.

function mymodule_node_presave(Drupal\Core\Entity\EntityInterface $entity) {
  $entity_title1=$entity->getTitle(); //It is the French title if the saved node is the french node.
  $entity_title2= '?'; //HERE IS MY PROBLEM: how to get the title in the other language?
  $entity->my_helper_field->setValue("$entity_title1 $entity_title1");
}

How do I get the translated title of a node?


texts: How to override the display of a field in a view: is preprocessing possible?

texts:
I want to override the display of a field in a particular view, so that rather than printing:

Content here

I just want:

Content here

Is this something which is best done in a template (I assume):

views-view-field--view-name--field-tagline.tpl.php

Edit: I've solved this using the above template, and then removing the wrapping elements from the view in via the Views UI. If using preprocessing is more performant, I'd still be interested to know, so please drop a line below if so. Otherwise, this question is solved.


texts:
I have created a "partners" block in the rightmenu of my theme .. it works perfect and all, but it shows only 6 partners (set from views settings) with newest first .. now my problem is i want to have a "view all" button, also i want to have a pager with jquery transition to view next 6 partners etc.

how can i do this? also, what modules do i need for this?

Thank you in advance


texts: Is there any implication/consideration for using the boost module on many different websites running on the same VPS?


texts: Drupal hash salt / private key is changing?

texts:
I've created a token that I store in database, here is how I create my token :

$token = drupal_hmac_base64($pid . " " . $order_id . " " . $solde, drupal_get_private_key() . drupal_get_hash_salt());

And then when a user go to my url that looks like that :

https://mycustomwebsite.com/order_id/token

With the token and another value : order_id, I get the line in my database with the order_id and then I create a new token :

$new_token = drupal_hmac_base64($pid . " " . $order->order_id . " " . $solde, drupal_get_private_key() . drupal_get_hash_salt());

I compare these two tokens just for a verification to grant the access or not.

This works fine but couple days after when I try to go on a link the access doesn't work anymore. When I look at the new_token generated for verification it's not the same !
But the value used to make this token (pid, order_id and solde) are the same, so here is why I ask my question.

Does the drupal_get_hash_salt() or drupal_get_private_key() can return different values in the time ?


texts: How to check when a user last updated password

texts:
I would like to display a message to any user who has not changed their password since yesterday (4/21/14).

Does Drupal keep track of when the password was last updated? If so, how can I access that information?


texts: Add multichoice question to quiz node programmatically

texts:
I'm using the latest version of drupal and quiz module. In my custom module, I have created a quiz by using below code

 $quiz = new stdClass();
  $quiz->title = 'Testing Quiz';
  $quiz->type = 'quiz';
  $quiz->language = LANGUAGE_NONE;
  $quiz->uid = 1;
  $quiz->status = 1;
  node_object_prepare($quiz);
  $quiz = node_submit($quiz);
  node_save($quiz);

However, the quiz is created successfully. I have a list of multichoice question, which is imported using feeds module. Now what I want is assign those multichoice question to this custom quiz node.

How can I do this?


texts:
I have installed the Advanced Forum module for Drupal 7.10.

How can I set permissions for each forum I make? I want only administrators to have the "admin forum" permission, and not authenticated users.

Is that possible?


texts:
I'd like to make a Drupal 7 view which displays nodes using the following behavior:

1) Show the body summary if it is populated.
2) Never show a trimmed version of anything.
3) If the body summary is empty, show the actual body.
4) If the body summary is not empty, display a "read more" link.
5) If the full body was displayed, don't display a "read more" link.

I've got this entirely working using a separate field for the summary (which may be what I end up with) but I'd hoped to use the body summary instead.  As far as I can tell the only way to access the body summary in a view is to use the "summary or trimmed" formatter in the field display, which violates #2.

I looked for modules, and all I found was "Smart Trim" which appears to do the opposite of what I want.

Suggestions?


texts: How do you make Varnish cache update when Drupal content changes?

texts:
I just started playing with Varnish cache. Looks like an awesome thing to have for speeding up page load times!

How does one force the cached copy of a node/page/content to be updated when the content changes in Drupal? Would it be something in the VCL file? I am using the VCL from Four Kitchens.


texts: Updating a Node image field from an external URL

texts:
I need to retrieve an image from an external URL and then save the image on Drupal's file system, and then set the image as the image for a node. In D7, this was a pretty simple task, but it's causing me issues in D8. In D7, here is what we have:
$file_info = system_retrieve_file($url, 'public://course_images/', TRUE);
if(!empty($file_info) && $file_info->fid) {
    $entity->field_image[0] = array('fid' => $file_info->fid);
}

I am trying the same thing in D8 but just receive this error Value is not valid entity which provides ZERO actual information about exactly what is wrong.
In D8, here is what I currently have:
$file = system_retrieve_file($image_url, 'public://course_images/', TRUE, FileSystemInterface::EXISTS_REPLACE);

if ($file && $file->id) {
  $course_node->set('field_image', [
    'target_id' => $file->id,
    'alt' => 'alt text',
    'title' => 'title'
  ]);
}

I've also tried using $file->id() and $file->fid with no luck. I just don't know how to access the file entity id!
I have tried to debug the $file object to figure this out using the logger
Drupal::logger('my_module')->notice('
' . print_r($file, TRUE) . '
');

but this code is in a cron job and adding that logger just makes the cron job fail with no error other than 'Cron cannot get lock' (again, another error with little to no information).
I can see that my file is being saved properly, but how can I access it's node ID after saving to be able to set as the target_id of the image field?
EDIT:
I moved all this code into an endpoint instead of a cron for debugging purposes. Here is my endpoint:
  function edxServiceTest(Request $request) {
    $course_node = Node::create([
      'type' => 'courses',
      'uid' => 1
    ]);
    $course_node->set('title', 'Test');
    $course_node->set('langcode', 'en');
    $course_node->set('status', NODE_PUBLISHED);

    $image_url = 'https://external-content.duckduckgo.com/iu/?u=http%3A%2F%2Fthewowstyle.com%2Fwp-content%2Fuploads%2F2015%2F01%2Fnature-images.jpg&f=1&nofb=1';

    $file = system_retrieve_file($image_url, 'public://course_images/', TRUE, FileSystemInterface::EXISTS_REPLACE);

    if ($file && $file->fid) {
      $course_node->set('field_image', [
        'target_id' => $file->fid,
        'alt' => 'Alt Text',
        'title' => 'Title',
      ]);
    } else {
      return new JsonResponse('error', 400);
    }

    $course_node->save();

    return new JsonResponse('success', 201);
  }

Here's what's occurring:

If I try to use $file->id() as the target, the endpoint runs successfully but the node is not added and there is no errors that occur.

If I try to use $file->fid as the target, the endpoint runs into an unexpected error Value is not a valid entity.


texts: Error: Private files directory not fully protected

texts:
I received the following error in my Drupal 8 status report:

PRIVATE FILES DIRECTORY Not fully protected See
https://www.drupal.org/SA-CORE-2013-003 for information about the
recommended .htaccess file which should be added to the private://
directory to help protect against arbitrary code execution.

The obsolete link provided shows no guidance for Drupal 8 or 9, only 7 and prior. I already have what I believe is a strict .htaccess file I'd found elsewhere in Drupal's documentation. How can I fix this error in Drupal 8?


texts:
I'm using hook_preprocess_node to get node field and make some processes, then pass a variable to the node to use it in the node twig template. The problem with me that when I edit this node, it doesn't affect on the view, I have to clear cache to see this change on the node view.

function THEME_preprocess_node(&$variables) {

    if (isset($variables['elements']['#node'])) {
        $node = $variables['elements']['#node'];
        $bundle = $node->bundle();
    }
    if (isset($bundle) && $bundle == 'crse') {
        $course_schedules = array();
        foreach ($node->get('crse_sched') as $schedule_item) {
            $schedule_entity = \Drupal\node\Entity\Node::load($schedule_item->target_id);
            $schedule = new stdClass();
            $schedule->title = $schedule_entity->get('title')->getValue()[0]['value'];
            $schedule->seats = $schedule_entity->get('seats')->getValue()[0]['value'];
            $schedule->state = $schedule_entity->get('moderation_state')->getValue()[0]['value'];
            $course_schedules[] = $schedule;
        }
        $variables['schedules'] = $course_schedules;
    }
}


texts: why does internationalization menu i18n_menu translate but never localizes?

texts:
I have a menu set to :

Translate and Localize. Menu items with language will allow translations. Menu items without language will be localized.

And I have include menu items that are "language neutral" and provided translations for said items.

Nothing but the original 'language neutral' language ever shows regardless of what the users profile language is set to (user's profile language is the primary way I have translation determining what language to use)

What do I have to do to get the Menu items to localize to the current users current profile language ?


texts: Unable to set Singularity grid total to 16

texts:
I’m having a problem using the Singularity grid framework. I set the total number of columns to 16 but it seems not to be reading this setting. instead the total seems to be 12.

the details are as follows.
I’m using the Omega theme and have correctly implemented a sub-theme
i’m using SASS and in the grid partial, _grid.scss have this code

@import "singularitygs";
$tab: 44em; /*704 pixels */
$desk: 70em; /* 1120 pixels */
$grids:16;
$gutters:1/4;

for test purposes i set a div to be 16 columns with this code.

.someDiv {@include grid-span(16, 1); }

this div then breaks out of the main page div, in this case .l-page and in the inspector it reads as

width:133%;

to trouble shoot i’ve searched via grep ‘grids:12’ and cleared the .sass-cache file. but so far nothing is working. has anyone had this same problem?


texts:
I want to add my custom action to defined rule('commerce_checkout_new_account'), I have found here. How can create my action, but I don't know how can I add it to defined rule by another module ('commerce_checkout_new_account').

Anybody know how can I add my custom rule action  to exists rule programmatically?

update

for more details: I want create my custom rule action, then add my actions to exists rule (the rule that created before by another version on in UI, I just want add my custom action to it porgrammatically )