texts: Firing custom submit on ajax form works with #ajax_processed set, but reloads the page

texts:
I'm placing a subform within the node edit form using a form_alter where I build the subform and add it to the form array. My subform has a custom submit handler and '#ajax' is set:
    $form['decision_select']['update'] = [
      '#type' => 'submit',
      '#value' => $this->t('Select Segment Set'),
      '#submit' => [[$this, 'updateSegmentSet']],
      '#limit_validation_errors' => [],
      '#ajax' => [
        'callback' => [$this, 'updateSegmentSetAjax'],
        'wrapper' => $wrapper_id,
        'effect' => 'fade',
        'event' => 'mousedown',
        'keypress' => true,
        'prevent' => 'click'
      ],
      '#executes_submit_callback' => true,
      '#ajax_processed' => false
    ];

I've tried a huge variety of render array combinations in this array and its parents to try get this submit button to fire its custom submit handler. The only thing that has worked is adding the #ajax_processed key. Whether its set to true or false does not matter, when it's added, clicking the submit button will reload the page (i.e. the button no longer functions like an #ajax button). Clicked a second time after reloading, it reloads the page again and the custom submit handler runs.
Without #ajax_processed added, the submit button correctly works like an #ajax button, but my custom submit handler never gets called.
Does anyone know why the addition of #ajax_processed causes this? Even better, I want this submit button to work like an #ajax button and fire the custom submit handler. Does anyone know what render array combination will allow this?


texts: Is Contact module the right choice for multiple ask a question pages?

texts:
I have a set of pages already developed. For each page I need to add a new page with an "Ask a Question" form to let end users contact via email the corresponding page owner.

I tried the Contact module but it doesn't seem the right choice.

One of the requirements is to hide the recipient email address from the user.

How can I create such a customized form and be able to set a different recipient on each page? Do I have to create a new Feature?


texts: How to edit the content page fields column in the admin section?

texts:
In the admin section --> Content menu displays all the contents of the site.

I want to have options (or atleast to know where I have to change) for adding and removing the columns in the content section.


texts: How can a field definiton be imported, either via the admin or in code?

texts:
In my admin one of the modules I have installed (I am not sure which) has the ability to export a field definition in code, but I can't see any place where I can import the field. I thought that the field creation dialog has abilty to import a field definition from the export code just as the bundle creation tool give the ability to import a bundle.

There is no such thing in the menu and I wonder if I am missing something in the interface or I have to resort to code.

Is there something missing in the admin interface, or do I have to import it in code?


texts: Parameter upcasting in Drupal 8 with Form Controller

texts:
I have created a custom module with mymodule.routing.yml in which I am using own parameter {my_menu}. I have created a mymodule.services.yml file too in which I have used class for param conversion. Parameter conversion class is calling properly but I am not able to get the parameter in Form Controller class.

Code that I have written :

mymoudle.routing.yml :

entity.my_menu.mymodule:
  path: '/node/{my_menu}/mytab'
  defaults:
    _title: 'My Title'
    _form: '\Drupal\mymodule\Form\MyModuleformControllerForm'
  requirements:
    _permission: 'edit my page'
    _entity_access: 'my_menu.update'
  options:
    _node_operation_route: TRUE
    parameters:
      my_menu:
        type: my_menu

mymoudle.services.yml :

services:
  my_menu:
    class: Drupal\mymodule\ParamConverter\MyModuleParamConverter
    tags:
      - { name: paramconverter }

src/ParamConverter/MyModuleParamConverter.php :

/**
 * {@inheritdoc}
 */
public function convert($value, $definition, $name, array $defaults) {
  dsm($value); // Node id that exists.
  return Node::load($value);
}

/**
 * {@inheritdoc}
 */
public function applies($definition, $name, Route $route) {
  return (!empty($definition['type']) && $definition['type'] == 'my_menu');
}

src/Controller/MyModuleformControllerForm :

public function buildForm(array $form, FormStateInterface $form_state, NodeInterface $node = NULL) {
  dsm($node); // It is null here
}


texts: Rules sends email to mailto link instead of email address

texts: I've created a content type with an email field. Anonymous users are allowed to create these nodes. I've created a Rule that sends an email message to the value submitted in the node's email field, using a replacement pattern. Rules tries to send the email to a mailto: link, not to the email address. The outgoing mail fails with the sendmail error: "Cannot mail directly to files", because it is addressing the email to the link, not the address.


texts: Drupal login using other subdomain user account with certain role

texts:
I'm having a main site and few subdomain sites for different countries:

www.mydomain.com (for U.S users)
newzealand.mydomain.com
singapore.mydomain.com
australia.mydomain.com

For each site, there are roles of anonymous user, authenticated user, member.
Rules module is used to add "member" role if this is an active user, and remove "member" role if this is not an active user.

I'm going to have another subdomain, members.mydomain.com.

Only those users with "member" role in those subdomains are able to access to members.mydomain.com.

In members.mydomain.com, how am I going to retrieve the user login info and user role from different subdomain?


texts:
I am trying to display a form in a table, but it is showing an empty result, while the header is displayed. I can't understand what I am doing wrong.

/*
 * cart form and page display
 */
function cart_page_form() {
  $form=array();
  $form['#tree'] = TRUE;

  $checkboxes=array();

  foreach($_SESSION['cart'] as $key => $qty) {
    $checkboxes[$key] = '';

    $form['checkboxes'][$key] = array(
      '#type' => 'checkbox',
      '#default_value' =>check_plain($key),
    );

    $form['quantinty'][$key] = array(
      '#type' => 'textfield',
      '#size' => 4,
      '#maxlength' => 4,
      '#id' => 'prod_qty',
      '#default_value' => check_plain($qty),
    );

    $form['price'][$key]['#value'] = t('244p');
  }

  $form['remove'] = array(
      '#type'           => 'button',
      '#name'           => 'remove_selected',
      '#value'          => t('Remove selected'),
  );

  $form['submit'] = array(
    '#type'           => 'button',
    '#name'           => 'update_quantity',
    '#value'          => t('Update'),
  );

  $form['checkout'] = array(
    '#type'           => 'submit',
    '#name'           => 'checkout',
    '#value'          => t('Зделать заказы'),
  );

   return $form;
}

/**
 *Implementation of hook_theme().
 *
 */
function yalublurudn_theme() {
  return array(
    'cart_page_form' => array('variables' => array('form' => NULL)),
  );
}

/**
 * display cart page
 */
function theme_cart_page_form($form) {
  $rows = array();

  foreach(element_children($form) as $key) {
    if (isset($form['checkboxes'][$key])) { //// make sure this is one of our table rows
      $row = array();
      $row[] = array('data' => drupal_render($form['checkboxes'][$key]));
      $row[] = array('data' =>drupal_render($form['quantinty'][$key]));
      $row[] = array('data' =>drupal_render($form['price'][$key]));
      $rows[] = $row;
    }
  }

  $header = array(
    'Checkboxes',
    'Title',
    'Quantity',
  );

  $output = theme('table', array('header' => $header, 'rows' => $rows));
  $output .= drupal_render($form); // Render rest of form components.

  return $output;
}


texts: Get last accessed timestamp value of a user in Drupal 8

texts:
Im trying to display the last accessed field when a user logs in.
For this I tried using User::getLastLoginTime() .
But this returns a fatal error saying

PHP Fatal error:  Call to undefined method Drupal\customize_block\Plugin\Block\ContractDetails::get() in /var/www/html/core/modules/user/src/Entity/User.php on line 265

Here is my block ,in my custom module:

/**
 * Provides a 'Customized contract' Block
 *
 * @Block(
 *   id = "customer_info",
 *   label = @Translation("Customer and contract info"),
 *   module = "user",
 *   context = {
 *     "current_user" = @ContextDefinition("entity:user", label = @Translation("Current User"))
 *   }
 * )
namespace Drupal\customize_block\Plugin\Block;

use Drupal\Core\Block\BlockBase;

class ContractInfo extends BlockBase {
 public function build() {
 $output='';
 global $base_url;
 $current_user = $this->getContext('current_user');
 $output.='<div>' . $current_user -> contextData . '</div>';

     return array(
      '#markup' => $output,
      '#cache' => array(
     'contexts' => array('url'),
      ),
    );
  }
}

Am I calling this method correct way?


texts: May I use width and height CSS properties on images?

texts:
CSS architecture (for Drupal 8) says:

  Never apply widths or heights except to elements that natively have these properties (e.g. images).

I use CSS properties like width:100% often with images. It seems much easier to get to than the markup most of the time. Does this guideline mean I should not being doing this? If so, is the only solution overriding a template file to get at the HTML element properties?


texts:
Since upgrading a module the other day, I am no longer able to upload files to my site.
Has anyone experienced this? If so, how did you fix it?

Actually, I am able to upload a image but not insert it.


texts:
Shortly, here is my situation:

I have installed both Metatag and Page Title modules.
The Page Title module page shows all my nodes and correspondent meta title I inserted.
The issue is that on certain pages (say Product page), meta title is
not generated and it generates something like [node:field_zone_geo]
instead of generating directly the Zone, say New York.

P.S. All other tokens are well generated within the meta titles, but this won't. Made lot of research and couldn't find any solution. I even de-installed the two modules (Metatag and Page Title) in order to avoid conflicts between them, but no solution.


texts: About the template for poll recent block in drupal 7

texts: I need a template for the poll recent block in drupal 7.  I have tried with block--poll.tpl.php and block--poll--recent.tpl.php and poll--recent--block.tpl.php and I can't see any changes.  What's my wrong?


texts: Attachments are included only on manual resend, but not on initial form submission

texts:
Using Webform and Mimemail to send HTML emails and uploaded files attached to emails.
When submitting the form, the file is not attached to the email. The box is ticked.

If you edit the submitted submission and click 'resend email', it attaches the PDF file to the email.

There are no errors on dblog.
How do I attach the files to the emails when the user submits the form with uploaded files?


texts: Accessing content variables through the page variable

texts:
I have a template that extends the page.html.twig base template. I wish to render a field variable from the node as a heading in other parts of the page template.

I've tried {{dump(page.content)}} but the variable does not seem to be there, it is already rendered into HTML.

What's the syntax - if it exists - for accessing a node variable from the page.content variable?

For example, at the node level, I can access {{ content.field_heading }}.

At the page level, what can I use? ({{ page.content.??? }})


texts: How can I a revert an overridden template to its default in a sub theme?

texts:
If a base theme overrides a certain template, how can I tell a sub theme to revert to the default template instead of using the overridden template?

Of course I could simply copy the default template to the sub theme's templates directory, but that's not an ideal solution because it duplicates code and one would not take advantage of future (security?) updates in the default template.

My ideal solution would be smart enough to undo the template override provided by the base theme, but still allow for other overrides on the module level.


texts: How to setup drupal multisite in cpanel?

texts:
I want to setup a drupal multisite but without success. I have followed this tutorials (and search in drupal answer):
- 2 minutes multisite
- 5 minutes multisite
- Setting up a multisite
I have tried with subdomains and with alias. My first question is when I create the alias or subdomain in cPanel, should I create a redirec? Now, I've left it blank, but I'm not sure if I have to create a redirect.

I always get:

  The website encountered an unexpected error. Please try again later.

or

  CGI-Error. Sorry. The page you request is not available.

I don't know what else I could do. Could some one detail me the steps? Thanks.


texts: How to edit a webform block (not the webform itself)

texts:
I have one webform block I would like to edit. I know I can use hook_form_alter, the problem is that any changes I make using it are affecting the actual webform plus the block.

How can change stuff just on the webform block? It's just a captcha component I want to disable, thanks.


texts: Simpletest: working with sessions and custom function

texts:
I need to add a simpletest case to my custom module.

Module functionality:

The module has a function to store data on $_SESSION, on the next page load if $_SESSION has a custom value a javascript code is printed (drupal_add_js: inline) in the bottom of the page.

Test Steps:

Function execution that adds some keys on $_SESSION
User goes to frontpage.

Something like:

public function testCase() {

    // Store session flag.
    my_custom_function_that_stores_session_data();

    // Go to frontpage.
    $this->drupalGet('/');

    $this->assertRaw('myjscode', 'JS is found');

}

This code is not working:

The test do not pass $this->assertRaw('myjscode', 'JS is found');, How can I work with sessions in simpletest?

There is no problem to add a custom user if it will be necessary to prevent cache.


texts: Is `watchdog-show string` broken in 7.56?

texts:
On a test instance, drush watchdog-show shows, among three other entries, a message starting with "Notice: Undefined property:". However, both of the following commands print nothing at all:

drush watchdog-show "Notice"
drush watchdog-show "Undefined property"

drush watchdog-show ":" does print the message, but also other irrelevant message. So how do I search watchdog messages like it says in the documentation:

  drush watchdog-show "cron run succesful"  Show a listing of most recent 10 messages containing the string "cron run succesful".

?


texts: How can I add a flag for reporting abuse on private messages using hook_privatemsg_message_view_alter()?

texts:
I have a flag on my Drupal 7 site for alerting moderators regarding potential abuse.

I want a link to this flag to be displayed next to the Delete and Block links on the view private message screen (messages/view) provided by the Private Message module.

By inserting the following code below the code for the delete link (line 769) in the latest version of the module, I can render the link correctly.

$author = $vars['message']->author;
$vars['message_actions'][] = array('title' => t('Report abuse'), 'href' => 'flag/confirm/flag/abuse/flag/block/' . $author->uid .  '?destination=user/' . $author->uid );

However, I don't want to hack the module; I want to add this code to a custom module.  hook_privatemsg_message_view_alter() appears to be the function for this, but I don't understand how to use it.  Simply inserting the above code and calling the function from within my custom module does not result in any errors but the link is not displayed.  What do I need to show the link?

EDIT: The solution need not use hook_privatemsg_message_view_alter(); if there is a better way that doesn't involve hacking privatemsg, I'd be happy to hear of it.


texts:
On Drupal 8.1...

In my custom module hubBlock:

namespace Drupal\hub\Plugin\Block;

use Drupal\Core\Block\BlockBase;
use Drupal\Core\Block\BlockPluginInterface;
use Drupal\Core\Form\FormStateInterface;

class HubBlock extends BlockBase implements BlockPluginInterface {
    [...]
}

I have a block form:

public function blockForm($form, FormStateInterface $form_state) {
  $form = parent::blockForm($form, $form_state);

  $form['brand'] = array (
    '#type' => 'select',
    '#title' => $this->t('Brand'),
    '#description' => $this->t('The brand id articles to show?'),
    '#options' => array('0' => t('Select a brand'),"1" => 'brand1',"2" => 'brand2')
  );

  return $form;
}

and a block validate function:

public function blockValidate($form, FormStateInterface $form_state) {
  if($form_state->getValue('brand') === '0'){
    $form_state->setErrorByName('brand', $this->t('You need to select a brand'));
  }
  return $form_state;
}

When I do place block, I get the form. When I submit without changing the brand I should get an error message and the field should be red. But this only prevent the form to be submitted. There is no error message shown to the user and the field does not get the error class

ref: blockValidate

Is there a bug? Do I do something wrong?


texts: Making a custom theme and want to know how to style first post different from the rest

texts:
After months of figuring out how to upload a background image, I decided to scrap that and use a solid color with the color picker.

Now I moving on making a custom theme and it's very different from making a WordPress theme. So I need help with the following:

On my page.tpl.php, is there a way to have the first post different from the rest of the posts? Example: First post has a title, date, time and a description. The rest just have a date and title.

Also I don't want to use view module as it looks complicated to setup and I want to use as little of modules as possible.

All help is greatly appreciated and thanks for understanding my annoying questions for help,
Gregory S.

UPDATE: Looks like I'll have to do views after all.


texts:
I have 3 Drupal 8 sites. 2 have premium themes and one is Bartik themed.

When I built the 2 the sites with premium themes in Ubuntu I could log in fine but when I log in to them when online (CentOS server) the sites crashes with the error:

  The website encountered an unexpected error. Please try again later.

This doesn't happen with the Bartik site.

I wonder if I could debug the problem somehow with Drush or if there is anything else than drush wd-show just to make sure I cover the most I can with it?

The only way I know to debug problems with drush is drush wd-show.

Is there any command that could help me understand why site logins fail on that particular environment?

Update - Error from Drush & Cpanel error log:

  [Tue Jul 19 14:50:11.393827 2016] [:error] [pid 15721] [client
  79.177.142.239:33948] Uncaught PHP Exception RuntimeException: "Failed to start the session because headers have already been sent by
  "/home/zantech0/public_html/yoursitename.com/themes/business/includes/skins-menu/skins_menu.inc"
  at line 2."

  at
  /home/zantech0/public_html/yoursitename.com/vendor/symfony/http-foundation/Session/Storage/NativeSessionStorage.php
  line 140, referer: http://yoursitename.com/user/login

Head of the file:


texts: How can I stop a Rule action from being executed, programmatically?

texts: How can I stop sending an email, for example? Assume the event is before_sending_an_email.


texts:
I'm working on a Drupal 6 site using the mimemail module and have run into a problem. When I send emails longer then 900 ish characters the email comes through as a garbled text. Running this through base64 decode returns the correct html markup.

Any ideas on why the length of an email would cause it to do this? From hunting around the only thing that sounds possible is that I know the email standard only allows about 900 characters per line. But then I would imagine mimemail would handle this natively?

Any help would be appreciated.


texts: Cache problem on entity view mode teaser

texts:
I'm using two slightly different versions of a teaser of a node on two different pages. It's the same fields used for both, but different HTML around each field.

In both cases, I get the renderable array of my node this way :

$view_builder = \Drupal::entityTypeManager()->getViewBuilder('node');
$vars['renderable_node'] = $view_builder->view($referenced_node, 'teaser');

What I would like to have :

Page Node 1
Node 3 teaser version 1
Page Node 2
Node 3 teaser version 2

The problem is when I flush caches, the cache is set for the first time rendering the teaser of my node, but on my other page it render the same version.

Here is what I have then :

Page Node 1
Node 3 teaser version 1
Page Node 2
Node 3 teaser version 1

I looked into ['#cache']['max-age'] but I don't really want to set it to 0 because it's not appropriate for obvious performance reasons.

I see that there is also ['#cache']['keys'], ['#cache']['context'] and ['#cache']['tags'] but not sure what to do.


texts:
I have a view, displaying in a block, with a views-view--VIEWNAME--block-1.tpl.php:

    <?php
        print render($title_prefix);
        if ($title): print $title; endif;
        print render($title_suffix);
    ?>

    ...some view content...

Most of the content in this template has been copied straight from the template given by theme => information => display template in the view settings.

This displays (with some whitespace differences):

BLOCK TITLE

    ...some view content...

Why is the view not displaying the view title inside the
? The title is definitely set for the view.

I've put the following code in the view template:

print print_r(array_keys(get_defined_vars()), 1);

And the result (including "title" at index 30) is:

Array
(
    [0] => template_file
    [1] => variables
    [2] => view
    [3] => view_array
    [4] => theme_hook_suggestion
    [5] => theme_hook_suggestions
    [6] => zebra
    [7] => id
    [8] => directory
    [9] => classes_array
    [10] => attributes_array
    [11] => title_attributes_array
    [12] => content_attributes_array
    [13] => title_prefix
    [14] => title_suffix
    [15] => user
    [16] => db_is_active
    [17] => is_admin
    [18] => logged_in
    [19] => is_front
    [20] => rows
    [21] => css_name
    [22] => name
    [23] => display_id
    [24] => header
    [25] => footer
    [26] => exposed
    [27] => more
    [28] => feed_icon
    [29] => pager
    [30] => title
    [31] => attachment_before
    [32] => attachment_after
    [33] => dom_id
    [34] => classes
    [35] => attributes
    [36] => title_attributes
    [37] => content_attributes
)


texts:
After creating a custom configuration for my module "module_name.settings.yml" simpletest fails with this message:

  InvalidArgumentException: Invalid database prefix: in Drupal\Core\Test\TestDatabase->__construct() (line 81 of /path/to/installation/core/lib/Drupal/Core/Test/TestDatabase.php)

I reinstalled my module and everything works. I load the configuration with the following code.

$config = \Drupal::config('module_name.settings');
$base = $config->get('module_name.variable');

Still, I can't run my tests. If I remove the content from my configuration, tests run again.
I'm using Drupal 8.3.4, Apache 2.4.18, PHP 7.0.8, and MariaDB 10.1.25.


texts:
I am using Drupal API as api_driver to run BEHAT scenarios. Please see below scarios for creating a term for the taxonomy "test_new". While running, this got success but when I take the application and look for the new term created it showing on the listing page. But when clicking on Edit of that term, name and description is not get updated, its showing empty but parent field is correctly mapped.
Why is this happening?
  Given "test_new" terms:
    | name              | parent         | description_field    |
    | Test term one     | Test parent    | term one description |
    And I wait for 20 seconds


texts: What urls does a page manager intercept?

texts:
The custom page is set up to intercept /sections/%section.  Will it intercept an URl such as '/section/section-1/articlename' or only '/section/section-1'

Regarding answer from Berdir:
How do I get a custom page to ignore C and respond based upon /A/B regardless of what C value is presented? In my case, C is the name of a specific article of type /A/B and those settings determine the format to be applied to the page through panels. Is there a wildcard?.


texts: (current-user:points] token showing points of the full category

texts: The token [current-user:points] showing points of the full category. Example, the token value displays the points of all articles in the article section and I had added the token in every article and now it showing the misleading information. Now, I want to show the points of current article ONLY and not the full article category. Experts, please help me to solve my problem. I will be thankful to you.


texts: Allowed column type names and element type names for creating custom Field Types

texts:
I'm creating new Field Types in Drupal 8.
I recently asked which are the type names allowed for the DataDefinition::create() method, receiving a good answer.

Now I figured out that I need at least other two type names:

A column type name to use inside the method schema(...) from the FieldItemBase class.
Another type name to create elements inside the method formElement(...) from the class WidgetBase.

For example this is a snippet of code used to create a new Field Type, defining the schema() method:

public static function schema(FieldStorageDefinitionInterface $fd) {

  $columns = array(

    //

    // Here the column type name is 'varchar'
    'password' => array(
      'description' => 'A plain text password.',
      'type' => 'varchar',
    ),

    //

  );

  $schema = array(
    'columns' => $columns,
    'indexes' => array(),
    'foreign keys' => array(),
  );

  return $schema;
}

In the above code the column type name is 'varchar'.

And this is another snippet, defining the formElement method (always used defining the Field Type):

public function formElement(
  FieldItemListInterface $items,
  $delta,
  array $element,
  array &$form,
  FormStateInterface $form_state
) {

  //

  // Here the element type name is 'password'
  $element['passwordlist'] = array(
    '#type' => 'password',
    '#title' => t('Password'),
    '#description' => t('Select a password for the user'),
  );

  //

  return $element;
}

In the above code the element type name is 'password'.

What can I use for 'type' in the first case and '#type' in the second case?


texts: Unsure how a block has ended up on a page

texts:
I've inherited an old drupal 6 site.  I'm 2 weeks into understanding the whole drupal system.

I have a page which loads a branch locator map.  It looks as if the map is a block created with openlayers and views.

The page where this block appears is in a 'Site Page' called 'branch locator'

If I go to 'Content Management > List' and then edit 'Branch locator'.  I am able to edit the text that appears on the page, but there is no setting to add or remove the map block.

I can't get my head around how the map block has ended up on the branch locator 'site page'.

I have trawled through the menu system to see how these 2 are linked but don't seem to be able to find any clues.

I looked into the template files as well to see if there was a custom template for the branch locator page and was then calling the block into it, so far I have not found anything.

How else could this have been achieved?


texts: Module for using Twitter's timeline widget on user's profile pages?

texts:
I want to use twitter's timeline widget on my site. This is different from the twitter drupal module that imports tweets as drupal content. I need all users of my site to be able to show the timeline widget on their profiles.

Is there a module that can assist with this?

Ive looked at the twitter timeline module but its not ideal. It would require giving users permission to create or edit a blocks. Also you have to enter the widget ID which I think some users will find confusing.


texts:
I have a block which contains a form (I used the build() method) . One of the form elements has a suffix as follows:
  $form['test'] = array(
      '#type' => 'number',
      '#placeholder' => t('test'),
      '#title' => '',
      '#suffix' => Markup::create(''.t('My custom text').'')
    );

I would like when clicking on the suffix anchor element, to replace the current block with another one. Anyone has an idea how to go about this? Thanks for your help!


texts: How can I force administrator to provide a reason when cancelling a user account

texts:
I would like to find a way for drupal site administrator to provide a reason when an account has been cancelled / blocked.

I would need a radio list such as below, then an automatic email is sent with the details of the option chosen by the admin.

Your email address is not a personal address issued by your company
E.G. a.name@yourcompany.co.uk
You did not supply your full name
You did not supply your company name
You did not supply a full address
You did not supply your telephone number


texts: How to get values of selected options in Form api?

texts:
I am using Form api to build one form.In that I have used select type field and for that options are coming from an array. Below is the code

  $fnames = array();
  $dir_path = variable_get('file_public_path', conf_path(). '/files');
  $files1 = scandir($dir_path);
  $dirs = glob($dir_path . '/*' , GLOB_ONLYDIR);
    foreach($dirs as $directs){
     $names = explode('/', $directs);//
     $fnames[] = end($names);
    }

  $form['select_list'] = array(
    '#type' => 'select',
    '#title' => t('Folder Names'),
    '#options' => $fnames,
  );

While displaying on the select list it will display all names but when I will fetch the value in one of the submit function it will show only index value not the name.

function custom_submit_file_upload($form, &$form_state){
  $foldername = $form_state['values']['select_list'];
}

Here it shows,

$foldername = 0 or 1 or 2 whatever I select in the options,

but I need name of the selected element not the index values.
Please suggest me to get the names.Thank you in advance..


texts: How to work with multiple widgets with single faceted?

texts:
1) how to get 2 different blocks for the same facet each one has a different widget
We need have block using a collpaisble defined through the custom module and I need select list. I need both of them to use the same facet field.

We have defined the settings in hook_facetapi_default_facet_settings() and we are exporting the fields.

 $facet->enabled = TRUE;
 $facet->settings = array(
'weight' => 0,
'widget' => 'collapsible',
'filters' => array(),
'active_sorts' => array(
  'active' => 'active',
  'display' => 'display',
  'count' => 'count',
  'indexed' => 0,

Is there a way I can override the realm settings of the block and we can use multiple widgets? Kindly explain me with the example.

2) how can I import the fields to the new solr index throguh custom code/programmatically?


texts: How do you get the display settings of a field on a particular content type/display

texts:
I'm looking to preprocess a field.

The field type I'm wanting to preprocess is an entity reference field.

I need to know what view mode has been selected on the display settings for this field (see screenshot below).

This information is not made available in the $variables variable passed into preprocess_field.

So how can I get this load this information? I have tried looking for some Drupal-specific functions that would return these settings but haven't found anything that works.

Many thanks.


texts: How can I create comment on node insert?

texts:
I try to create comment on node insert using insert() hook but it collides with INSERT INTO {comment_entity_statistics} sql.

Integrity constraint violation: 1062 Duplicate entry '53-node-field_support' for key 'PRIMARY': INSERT INTO {comment_entity_statistics}

The code:

/**
 * Implements hook_ENTITY_TYPE_insert().
 */
function notifications_node_insert(Drupal\Core\Entity\EntityInterface $entity)
{
    $timestamp = mt_rand($entity->getCreatedTime(), REQUEST_TIME);
    $stub = array(
        'entity_type' => $entity->getEntityTypeId(),
        'entity_id' => $entity->id(),
        'field_name' => 'field_support',
        'name' => 'devel generate',
        'mail' => 'devel_generate@example.com',
        'timestamp' => $timestamp,
        'subject' => $_POST['field_support_message'],
        'uid' => \Drupal::currentUser()->id(),
        'langcode' => $entity->language()->getId(),
    );
    $comment = \Drupal\comment\Entity\Comment::create($stub);
    $comment->save();
}


texts: I have a View of taxonomy terms and for some reason I need to overwrite the terms' fields and link them "manually", using "Output this field as link". How can I process the '[name]' token through transliteration process before outputting it on the screen?


texts: EntityFieldQuery not returning Bundle data

texts:
I've defined an entity in hook_entity_info as follows:

function foo_entity_info() {
  return array(
    'Foo' => array(
      'label' => t('foo'),
      'base table' => 'foo',
      'entity keys' => array(
        'id' => 'bar',
        'label' => 'bar',
      ),
      'module' => 'foo',
      'fieldable' => TRUE,
      'bundles' => array(
        'Foo' => array(
          'label' => t('Foo'),
          'admin' => array(
              'path' => 'admin/config/foo/fields',
              'access arguments' => array('access content'),
          ),
        ),
      ),
      'views controller class' => 'EntityDefaultViewsController',
    ),
  );
}

When I run the following code:

$info = entity_get_info('Foo'); it all looks OK

When I run the following code:

  $query = new EntityFieldQuery();
  $query->entityCondition('entity_type','Foo');
  $result = $query->execute();

it all looks OK

But when I run the following code:

  $query = new EntityFieldQuery();
  $query->entityCondition('entity_type','Foo')
    ->entityCondition('bundle','Foo');
  $result = $query->execute();

I get an empty array in $result. This seems wrong.

What should I expect to see in $result and why aren't I seeing it?

Many thanks,

MB


texts: Notice: Undefined variable: key in comment_prepare_thread() /public_html/modules/comment/comment.module)

texts:
I'm getting two errors based on comments by users that no longer exist. I just updated from Drupal 6 to 7, and this seems to be an error that pops here and there, but I can't figure out how to fix it. The errors are:

  Notice: Undefined variable: key in comment_prepare_thread() (line 901 of /home2/cheffrog/public_html/modules/comment/comment.module).

  EntityMalformedException: Missing bundle property on entity of type comment. in entity_extract_ids() (line 7734 of /home2/cheffrog/public_html/includes/common.inc).

This is an article I came across that talks about the issue.

The problem is that, when I try SELECT * FROMcommentWHERE uid NOT IN (SELECT uid FROM users), it lists every user in my database, including the registered users.

The pages on which this error is triggered are inaccessible. However, if I edit the page and change all the comments to hidden, the page will display fine, minus the comments.

I have this error happening on a lot of pages, so I'm hoping there's a better fix than just hiding all the comments on every single page.


texts:
How to redirect page to specific url suppose blog-landing page to blog-landing/all page

How to target specific page /blog-landing page when user enters url into browser user should redirect to blog-landing/all

What i have tried :

 function bootstrap_preprocess_page(&$variables) {

 $request = \Drupal::request();
 $current_path = $request->getPathInfo();
 $path_args = explode('/', $current_path);
 $first_argument = $path_args[1];
  if($first_argument =="blog-landing")
  {
    $response = new Symfony\Component\HttpFoundation\RedirectResponse('/node/12/edit');
 $response->send();
return;

}

else
{

 echo "sorry not redirected";
 }
}
}


texts: How do you reorder the shipping services for drupal commerce?

texts: There doesn't seem to be a weight option. How would one reorder the shipping services for drupal commerce?


texts:
I wrote a custom module that records page views. So each time a user views a node, it creates an entry in a database table. Essentially I wanted my own custom statistics module.

The problem is, it's only called once. I would assume some kind of caching is applied to this function. I have this:

function hook_node_view( $node,  $display, $view_mode, $langcode)
{
    $nodeObject = $node['#node'];

    $insert = array(
        'created'    => REQUEST_TIME,
        'nid'        => $nodeObject->id(),
        'uid'        => \Drupal::currentUser()->id(),
        'ip'         => \Drupal::request()->getClientIp(),
        'session_id' => session_id(),
    );

    db_insert('node_view_log')
    ->fields($insert)
    ->execute();

}

But it is only called once per node, and not each time the node is viewed. Any idea as to why this is happening? Is there a way to turn of caching for this function only? Or is there perhaps a better place to log page views?


texts: Confused about choosing between line items and product attributes

texts:
I am making a website that will have image canvas size as the products. As you know the Canvas Sizes will change and also their price will also change. Let me tell you the actual steps.

The customer selects the Canvas Layout. These are the Products for me.
The customer selects the sizes for the selected canvas layouts.
The customer chooses the Wrap type for the Canvas.
The customer chooses the color of the wrap.
The customer chooses the Frame type of the Canvas.
The customer chooses the color of the Frame.
The customer adds the selected item to cart and go to checkout.

Please note that, once the customer starts customizing the product, the price of the product changes with each customization.

So my confusion is that, what will be the best suited practice to achieve this one. I am using Drupal Commerce. Should I go for the Product attributes or line items?
Is there any way I can achieve this one by custom Module to add line items dynamically? So then I can create the prices upon each customization. I am attaching one wireframe about my idea.


texts:
I'm developing a site in drupal 7 that needs a related content block. The problem is that I tried Similar entries and Similar by terms modules but it looks like they are not compatible with views 7.x-3.0 I'm using, yet.

There is an error message when I install both modules and in the bug reports I found posts with errors just like mine but without good solutions.

I was thinking until the modules are ready, maybe, I can, somehow, use views and show random content based on the taxonomy term in the node and not show the current node.

Is there a way to use contextual filters and use arguments from taxonomy in the current node?

If you know some other way or module to achieve something similar please point me in the right direction.


texts: How can I print $submitted in a region template?

texts:
I have a region--content.tpl.php and am trying to figure out how to print the $submitted variable (usually printed in node.tpl.php).

--- EDIT ---

Including here the final code I used.  This lets you print out the themed user link where as the original code only printed the name as plain text.

function theme_preprocess_region(&$vars) {
  if ($vars['region'] == 'content') {
    $node = menu_get_object();
    $user = user_load($node->uid);

    if ($node) {
      // Adapted from template_preprocess_node().
      $vars['submitted'] = 'By ' . theme('username', array('account' => $user)) . ' | ' . format_date($node->created, 'short');
    }
  }
}


texts:
I have a content type LAW with fields Title, law Category( Taxonomy Vocabulary) and Tags( Another taxonomy vocabulary) and last field is Description.

When Adding law content, I select in which category it belongs (lets say Labor law). I also add tags (e.g. Condemnation, Judgement) which are autocompleted as the default tags.

In view, I have displayed a list of all the categories, for example:

Labor law
Banking law
Land law

When Labor law is clicked, I want a list of tags (Condemnation, Judgement) related to labor law; on clicking Condemnation or Judgement the nodes should be displayed.


texts:
I'm adding a contextual filter to a view for a custom content type that has a taxonomy field. The contextual filter allows me to filter by the taxonomy tag id but not by the taxonomy tag name. Meaning with the given tags in the taxonomy:

1  | test1
2  | another tag
3  | taggy
......
99 | coolness

I can generate a contextual filter that will parse a URL like http://mydrupal/myview/3 to display all content that has been tagged with taggy BUT, the URL needs to pass the argument to lookup by tag name instead of tag id, e.g., http://mydrupal/myview/taggy to view all content tagged with taggy How can this be accomplished?


texts: How do I limit a normalizer to a given class or interface?

texts:
I'm creating a custom normalizer for node entities.

I want to restrict the normalizer to normalize Node entities only. It seems like there are two ways this can be done:

protected $supportedInterfaceOrClass = NodeInterface::class;
public function supportsNormalization($data, $format = NULL) {
  return (bool) $data instanceof NodeInterface;
}

Is there a difference between the two? Do I need both, or only one of them?

It seems like I don't need the $supportedInterfaceOrClass, but what is it used for? Can I just remove it and only use supportsNormalization()?

UPDATE: My class extends the NormalizerBase class.


texts: How do I create a redirect after using pathauto_node_update_alias()

texts:
I am using the Redirect module.  I have a feature, where I have an update hook, that updates (and fixes) the path alias of the nodes on the site (after I made a change to the pathauto pattern).  I need to create a redirect, as updating the path alias does not do this for you when you use pathauto_node_update_alias().  How do I go about this.  Below is the code I have:

function uw_cfg_redirect_update_7010(&$sandbox) {
  $query = "SELECT nid FROM {node} where status = 1";

  // If this is the first pass through this update function then set some variables.
  if (!isset($sandbox['total'])) {
    $result = db_query($query);
    $sandbox['total'] = $result->rowCount();
    $sandbox['current'] = 0;
  }

  // How many nodes should be processed per pass. The higher this number is, the faster your update will
  // complete, but the more likely your server will run out of memory or timeout.
  $nodes_per_pass = 50;

  // Get the nodes to process during this pass.
  $result = db_query_range($query, $sandbox['current'], $nodes_per_pass);
  while ($row = $result->fetchAssoc()) {
    $node = node_load($row['nid']);
    pathauto_node_update_alias($node);

    // TODO: [need to add redirect code here]

    // Increment "current" by 1.
    $sandbox['current']++;
  }

  // Set the value for finished. If current == total then finished will be 1, signifying we are done.
  // If not then this function will be trigger again.  See Drupal Batch API for more details.
  $sandbox['#finished'] = ($sandbox['current'] / $sandbox['total']);

  if ($sandbox['#finished'] === 1) {
    drupal_set_message(t('We processed @nodes nodes. DONE!!!', array('@nodes' => $sandbox['total'])));
    return t('Finish rewrite the path of all the nodes.');
  }

  return $sandbox;
}

Note:  This is not a problem if you use Global Redirect module.   This is not a problem when you resave a node, as redirect gets added.


texts:
I set permissions 777 to /www/sites/default/files folder and all subfolders. I did this because Drupal 7 would not let me save content. Drupal said me: The specified file temporary: //filetXbwF7 could not be copied, because the destination directory is not configured correctly.

Originally, these folders have the permission 755. But that did not work.

What risks are there to set permissions 777?

Thanks in advance!


texts:
I am using the adress field module and like to make only the postal code field required.
The rest of the fields i like to hide.

The hiding of the fields are no problem however i am having problems with making only the postalcode field required.
I can hide the whole field with:

<?php
 function my_form_user_profile_form_alter(&$form, $form_state,  $form_id) {

  if ($form_id == 'user_profile_form') {

  $form['field_adress']['und'][0]['#required'] = TRUE;
      }
    }
      ?>

but then this is not working

$form['field_adress']['und'][0]['locality_block']['postal_code']['#required'] = TRUE;

What am i missing?
Without succes i have tried solutions as:
In here
and here


texts: Get profile ID after using commerce_customer_profile_save()

texts:
Anyone has any idea how to get the profile_id after I created a new profile using commerce_customer_profile_save() ?

Apparently this function does not return the new profile object and I don't think it's very safe just to select last inserted profile from the database :(


texts:
I need to hide the pager's exposed options (results per page) when the view has no results. I looked everywhere but can't find anything.

Thanks


texts: drupal 6 to 7 site upgrade using drush_sup - how to download compatible drupal 7 modules

texts:
I used drush_sup to upgrade my drupal 6 to 7 site. everything went smooth except the drupal 7 modules were not downloaded to the upgraded website.

During the upgrade process it did list the installed D6 modules, and the recommended D7 counterparts. I'm not sure what caused it to skip downloading it or maybe it just doesn't?

Thanks, any help appreciated.


texts: Rules to Flag a node referenced by Commerce Order Line Item

texts:
I have a site selling edit access to specific nodes. The site uses Drupal 7, Commerce, Commerce License (selling a Role with edit permission), Rules and Flag.
On the Add to Cart I have a Line Item Entity Reference where the customer selects the Node they want access to. Upon payment a 12 month license is generated and the Role with edit permissions is added to the User. That all works fine.

Here's what I need:
When the payment is successful I need a Rule to trigger and set a Flag (premier_listing) on the Node that was selected during the Add to Cart process.
However I can't seem to access the Node Entity in Rules or access the Line Item Entity Reference that the User selected.
Anybody have an idea how this could be done?
Thanks


texts: I need to update the taxonomy field on nodes with the term from a new vocabulary. I could accomplish this easily in Drupal 6, and haven't been able to find a method in Drupal 7. I am looking for a UI based solution like VBO.


texts: How do I let the user create a custom menu in a node?

texts:
On all my pages there is a side bar menu acting as a node/page specific menu. Typically I would create an entity reference field and let the user choose menu items that way. Then I'd use a view to display the list the user created. However, this list is unique per page and they user may not want it in order my title or date, they may want it in a specific order.

Is there a module that would allow the user to select x number of pages and specify the order of the items selected?


texts: Restricted nodes don't show up in search results

texts:
On this Belgium version of the side users has to have the right permission to view specific nodes. I did this with Content Access module.

But now when you as anonymous user search any content the restricted nodes don't show up?

How do i manage the teasers show up always? But when you want to see full content it's restricted?


texts: How can I add a class to a link output via a form?

texts:
Based on this answer, I'm attempting to add a cancel link.  By default, however, the following code just displays a plain link with no ids and classes.

  if(arg(1) == 'add') {
    // If adding node link to node/add screen
    $link = l(t('Cancel'), 'node/add');
  }
  elseif(arg(2) == 'edit') {
    // If editing node, link to node view screen
    $link = l(t('Cancel'), 'node/'.arg(1));
  }
  $form['cancel'] = array(
    '#type' => 'markup',
    '#value' => $link,
    '#weight' => 0,
  );

How can I add arbitrary css classes and an id to the link that is output?


texts: Update existing node (not created by Migrate) via Migrate 8.5.x

texts: I have got existing Drpal 8.5 site with hundreds of nodes. With migrate, if i try to upgrade, new nodes are rather created. Node have a field which is being used as key however that seem to be not working. It seems that node are only updated if their record present in migrate_map_xyz. Any suggestions?


texts:
I upgraded from 8.6.15 to 8.7.0 and now my page will not load.  I've searched for the error I'm getting (see below) but the results do not seem to apply to my situation.

I'm using installatron from my host provider for install and update.  Here's the error I am getting:

  PHP Fatal error:  Trait 'Drupal\user\EntityOwnerTrait' not found in /[deleted for brevity]/core/modules/node/src/Entity/Node.php on line 86

I'm not using Drush (although, maybe installatron is?) and need andy advice for getting my site back up.

Thanks


texts: Drupal 7 views join two profile2 profiles together

texts:
I would like to join two profile2 profiles so they appear as one row in the view module and not two rows like the example below. Can this be done?

Fields

User: Name
Content: image_profile_image

Relationships

User: Profile
User: Content authored


texts: Change url alias for user profile pages based on role

texts:
I have two sets of users, faculty and staff, with corresponding Profile2 profiles.

I can't figure out how to get different paths for users dependent on roles, e.g, staff/userid or faculty/userid.

I've been trying with both Rules and Pathauto.  Seems like it should be simple but can't get work it out.


texts:
the view accordion is automatically assinging a tabindex -1 to header field.  like this :

<a href="#how_to_become_a_grantee-block-0" tabindex="-1">

how can I remove that tabindex -1 ? thank you


texts: How do I enable autocomplete on fields inside tableselect

texts:
I have form which outputs tableselect.
The tableselect have many textfields which should be autocomplete.

The problem is that textfields never become autocomplete fields and even form_process_autocomplete doesn't called.

/**
 * implements hook_overview_form
 */
function supplier_overview_form(&$form, Supplier $supplier) {
  $header = array(
    'supplier_data' => array('data' => t('Supplier data')),
    'vocabulary' => t('Vocabulary'),
    'term' => t('System Term'),
  );

  $query = db_select('supplier_data_mapping', 'sdm')
  ->fields('sdm')
    ->condition('supplier', $supplier->machine_name)
    ->orderBy('system_term', 'ASC');

  $result = $query->execute();

  $options = array();

  $title_field = array(
    '#type' => 'textfield',
    '#title' => t('Supplier data'),
    '#title_display' => 'invisible',
    '#value' => '',
    '#name' => 'supplier_data'
  );
  $vocabularies = array();

  $vocs = taxonomy_get_vocabularies();
  foreach ($vocs as $key => $info) {
    $vocabularies[$info->machine_name] = t($info->name);
  }

  $vocabulary_field = array(
    '#type' => 'select',
    '#options' => $vocabularies,
    '#title' => t('Select Vocabulary'),
    '#title_display' => 'invisible',
    '#name' => 'voc'
  );

  $term_field = array(
    '#type' => 'textfield',
    '#title' => t('Term'),
    '#title_display' => 'invisible',
    '#name' => 'term',
    '#attributes' => array('id' => 'term-autocomplete', 'class' => array('supplier-mapping-autocomplete')),
    '#autocomplete_path' => 'admin/supplier/term-autocomplete/265',
    '#default_value' => '',
  );

  while ($record = $result->fetchObject()) {
   $options[$record->mapping_id] = array(
    'supplier_data' => array('data' => $title_field),
    'vocabulary' => array('data' => $vocabulary_field),
    'term' => array('data' => $term_field),
   );

   $options[$record->mapping_id]['supplier_data']['data']['#title'] = t('Delete');
   $options[$record->mapping_id]['supplier_data']['data']['#name'] .= '[' . $record->mapping_id . ']';
   $options[$record->mapping_id]['supplier_data']['data']['#value'] = $record->supplier_data;

    $options[$record->mapping_id]['vocabulary']['data']['#value'] = $record->system_vocabulary;
    $options[$record->mapping_id]['vocabulary']['data']['#name'] .= '[' . $record->mapping_id . ']';

    if (!empty($record->system_term)) {
     $term = taxonomy_term_load($record->system_term);
     if ($term) {
         $options[$record->mapping_id]['term']['data']['#value'] = $term->name . ' ('.$term->tid.')';
      }
    }

   $options[$record->mapping_id]['term']['data']['#attributes']['id'] = 'term-autocomplete-' . $record->mapping_id;
   $options[$record->mapping_id]['term']['data']['#id'] = 'term-autocomplete-' . $record->mapping_id;
     //$options[$record->mapping_id]['term']['data']['#autocomplete_path'] .=  '/' . $record->system_vocabulary;
     $options[$record->mapping_id]['term']['data']['#name'] .=  '[' . $record->mapping_id . ']';
 }

  $form['maps'] = array(
    '#type' => 'tableselect',
    '#header' => $header,
    '#options' => $options,
    '#empty' => t('No content available.'),
    //'#attached' => array('js' => array(drupal_get_path('module', 'terp_supplier_data_map') . '/js/terp_supplier_data_map.js')),
  );
  $form['supplier'] = array(
   '#type' => 'value',
     '#value' => $supplier->machine_name,
  );
}


texts: Count of users who are logged in per day

texts:
I searched to find a way to display the number of users who are logged in per day.

I want to display a chart using views for last month to show the login statistics of the website.

Any suggestion?


texts:
I am using hook_theme_registry_alter() in my custom module for overriding the theme function.
I have done something like this in my module file aml.module

function aml_theme_registry_alter (&$theme_registry) {
  $theme_registry['aml']['function'] = 'theme_menu_item_link';
  dsm($theme_registry);

}

function theme_menu_item_link () {
  drupal_set_message("hello");
}

I don't know how and where to implement this function theme_menu_item_link


texts: How to show a specific amount of multivalue fields depending on a value of the parent node?

texts:
I need to show a specific amount of multivalued fields on a comment depending on the value of the node (field_optionsamount) that the comment is attached to. There are modules that allow to set the number of fields shown (e.g. https://www.drupal.org/project/multivalue_extras) but the limit is the same for all fields and does not depend on the node.

The code below removes the add more fields button and provides the amount of fields that need to be shown. I don't know how to show x fields though.

function customisations_form_comment_form_alter(&$form,&$form_state,$form_id) {
     $parentNode = $form['nid']['#value'];
     $node_data = node_load($parentNode);
     $amountOptions = $node_data->field_optionsamount['und'][0]['value'];
     drupal_set_message("Amount: ". $amountOptions);
     unset($form['field_toinvest']['und']['add_more']); //hides the add more button
}


texts: Taxonomy Menu: Display Descendants does not work

texts:
I could not find any good answer to this question online, so I decided to post
  it with the answer I found as it might help some people, I hope so :)

I am using Drupal 7.

In taxonomy menu 1.4 module, if you check option "Display Descendant" , nothing change in your menu.

In taxonomy menu 2.0alpha2 module, if you select the similar option: "Menu path type => Multiple terms" , the items in your menu that have descendants vanish from your menu

How to get this to work ?


texts: how to maintain imagecache in pressflow with load balancer?

texts:
I am planning to make load-balancer for my website, it is pressflow 6.2.
the question is: how can i maintain imagecache in the two servers?!!
i need something other than NFS. since NFS will cause overload and will break the website in case that the server that has the images is down!!
EDIT
is it possible to have a dedicated server for images using imagecache (if so, how?)
any idea is highly appreciated


texts:
I've read the main docs about this but find it lacking context. This did better job of explaining and it seems it should work. How to force a JavaScript library to load in the <head> of a Drupal 8 page
EVERY attempt I try returns

A colon cannot be used in an unquoted mapping value

Searching for this, I've attempted to enclose the include line in single quotes, without, but all within context of attempting
js-header

Since this YML, I'm making sure we're using two spaces for indentation and nothing else. What am I overlooking here? This is a snippet of mytheme.libraries.yml

  flexslider:
  version: 1.x
  css:
    theme:
      includes/flexslider/css/flexslider.css: {}
  js:
    includes/flexslider/js/jquery.flexslider-min.js: {}
  dependencies:
    - core/jquery

fontawesome:
  version: 1.x
  css:
    theme:
      includes/fontawesome/css/font-awesome.css: {}

global-styling:
  version: 1.3.2
  css:
    theme:
      includes/mapquest/css/mapquest.css: {}
  js-header:
    header: true
      js:
        includes/mapquest/js/mapquest.js: {}

This is portion of mytheme.info.yml that applies:

  #Libraries
  libraries:
  - mytheme/bootstrap
  - mytheme/flexslider
  - mytheme/fontawesome
  - mytheme/global-components
  - mytheme/global-styling


texts: Anonymous users can't access to image style field

texts:
Entity

Type : block
Field : 'Reference to entity : image style' (field_image_style)
Manage display : I display the Entity ID

Twig

In my twig template, I get the field_image_style data from content.field_image_style.

Issue

Works great on admin user, but not when browsing the website as an anonymous user.

This is not a image style generation error, or a wrong permission to files folders : you can access to both original image and generated styled image on anonymous.

And this is where it gets weird. It's working when you give the "Administer image styles" permission to anonymous users.

Dump

Just to show you what result I have, here's a dump of content.field_image_style with an admin user :

And with an anonymous user :


texts: How send argument to Services Module (Views+Contextual filters)

texts:
I'm using the Services Module to make a request from one website to a drupal website (The services module calls a view).

For this I'm using jQuery:

$.ajax({
    url: 'http://test.url/rest/viewname',
    success: function(){ alert('hi'); }
});

This works FINE !

Now I added a "Contextual Filter" to the View, to show only nodes of a specific user. My question: How can I send the uid with jquery?? I tried a lot of ways:

$.ajax({
        url: 'http://test.url/rest/viewname/555',
        ...
    });

Error 404!

$.ajax({
        url: 'http://test.url/rest/viewname?args[uid]=555',
        ...
    });

Argument ignored!

$.ajax({
        url: 'http://test.url/rest/viewname?arguments[0]=555',
        ...
    });

Argument ignored!

$.ajax({
        url: 'http://test.url/rest/viewname',
        data: { uid: '1' }
        ...
    });

Argument ignored!

... and much more :D

Can somebody helo me?


texts: Retrive $message variables in javascript file

texts:
I am using Drupal 7.

In the template file page.tpl.php there is a variable called $message which prints the messages like error, warning etc.

I want to access this variable in a JavaScript file. How can I do so?


texts: Using content field widget in custom block?

texts:
I'm trying to figure out an easy way to implement a content field type (image_field) with a widget (imagefield_crop) on a custom block.

The block currently has an upload image feature, but I want to implement the imagefield_crop widget when uploading the image in the block.

I have tried Beans(resets all current blocks), CCK Blocks (only implements one field type(need Date, Image, Body)), and some other modules. It would be easier to insert some code in my block.module, but I get negative results.

I am getting close to implementing the "function imagefield_crop_field_widget_form" into my code, but cannot reference the module nor get any positive responses.

The image type for the module is a 'managed_file'.

btw, I have been using Drupal for ~20 days and have not hit any major road blocks till now. (Pun intended?). I know that blocks are not entities and cannot contain field content types, not to mention Drupal 8 will implement blocks as entities(I can't wait that long). Thanks in advanced!


texts: Customized HTTP to HTTPS redirect with drupal multisite

texts:
I have a multisite setup with drupal 7.23 which is working fine. Websites are like this:

SITE1

http:// www.site1.info

SITE2 and 2 subdomains

https:// www.site2.com
https:// sub1.site2.com
https:// sub2.site2.com

SITE3

https:// www.site3.com

As you can see site2 and site3 are full SSL anabled but for site1 I have only some pages with SSL like this:

NO SSL:

http:// www.site1.info
http:// www.site1.info/page1

SSL:

https:// www.site1.info/page2
https:// www.site1.info/page2/subpage1

I have enabled non www. to www. redirect which drupal is offering by default and adjusted it a bit:

RewriteEngine on

  # I've also added these 2 lines to redirect HTTP to HTTPS because the next 3 lines didn't worked.
  RewriteCond %{HTTPS} !=on
  RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

  RewriteRule ^ - [E=protossl]
  RewriteCond %{HTTPS} on
  RewriteRule ^ - [E=protossl:s]

  RewriteCond %{HTTP_HOST} .
  RewriteCond %{HTTP_HOST} !^(www|sub1|sub2)\. [NC]
  RewriteRule ^ http%{ENV:protossl}://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

BUT here is where I'm stuck:
if I access for instance: https://www.site1.info it s not redirected to http://www.site1.info and keep SSL ony for the desired pages.
I'm not sure how to write all these rewrite rules given the fact that I'm no htaccess expert.


texts:
I updated a website to Drupal 8.9.6 version. I saw that the global variable $pager_total_items was used, but is deprecated since D8.8.0.
So, I'm looking for an alternative to retrieve the total items of the pager.
This was used on a Search API page.
The old code looks like this :
$variables['count_results']     = empty($GLOBALS['pager_total_items']) ? 0 : $GLOBALS['pager_total_items'][0];

And now, looking this change record : https://www.drupal.org/node/2779457 I try to replace this like this :
/** @var \Drupal\Core\Pager\PagerManager $pagerManager */
$pagerManager = \Drupal::service('pager.manager');
dpm($pagerManager->getPager());

This renders nothing in the dpm(), so no Pager was found. It appears that Search API doesn't use a Pager...


texts:
First of all, I'm using Drupal 6.

I'm developing a website where I want the users to automatically have their own "group"; this means they are only able to see their own nodes. If another user creates an account, he won't have access to other users' nodes. Also, users can add new terms to some fields (using "Hierarchical Select") and I want it to be restricted to each user too.

I also want a user (lets call it "user A") creates another user and they can have access to the user A's "group"; this means that they can see user A's nodes and terms.

I was looking for the Organic Groups module, but it doesn't seem able to do this. If it is, I don't know how to do that.

Do you have any suggestion?


texts:
I'd like to edit the way the Book navigation is structured.
I'd like to be able to edit the html output of the book.

I was looking for a way to do this with the book template but had no luck. Looking at book-navigation.tpl.php I did see that $tree contained the children of the current node. However it used like this

<?print $tree; ?>

I don't see a way to alter the html of how the tree is output.


texts: How to change privatemsg message participants

texts:
I am using private message drupal module.In my project there are many roles and these role type user can send message to another user.In default If user A send message to user B ,and user B is logged in then under read message tab there is a message label "Between you and email id of user A". similarly
for other user also.But my requirement is that message label should be as
"Between you and admin mail id" not mail id of that user who send this message.


texts: How to programmatically submit a form that has a file-field using drupal_form_submit()?

texts:
I'm working to allow the submission of an existing form via REST using the Services module and drupal_form_submit(). Though this is reasonably routine, the form in question takes a file-upload which is a required field.

To avoid embedding extra logic in the form itself to handle files differently under programmatic submission than under manual submission, is there a trick for getting Drupal to accept a file submitted "headlessly" via REST?

Most of this is not relevant to the answer, but for completeness, here's how I'm set up:

function mymodule_my_resource_create($data) {
    $form_state = array();
    $form_state['values'] = $data + form_state_defaults();
    drupal_form_submit('mymodule_form',$form_state);

    $errors = form_get_errors();
    $status = '200 OK';
    if (!empty($errors)) {
        $status = '400 Bad Request - submission caused errors';
    }
    drupal_add_http_header('status',$status);

    return (object)array(
        'message' => $status,
        'errors' => $errors,
    );
}

function mymodule_form($form,&$form_state) {
    return array(
        'spreadsheet' => array(
            '#type' => 'file',
            '#title' => 'Spreadsheet file',
            // '#required' => 1,
            // ^ there have been issues with this since 4.x...
            // https://www.drupal.org/node/59750
            // so this is done manually in the '#validate' function
        ),
        'reason' => array(
            '#type' => 'textfield',
            '#title' => 'Why file is being submitted',
            '#required' => 1,
        ),
        'submit' => array(
            '#value' => 'Submit',
            '#type' => 'submit',
            '#validate' => array('mymodule_form_validate_upload'),
        ),
    );
}

function mymodule_form_validate_upload($form,&$form_state) {
    if (!isset($_FILES['files']['name'] || !isset($_FILES['files']['name']['spreadsheet'])) {
        form_set_error('spreadsheet','File must be provided');
    }
}

function mymodule_services_resources() {
    return array(
        'my_resource' => array(
            'create' => array(
                'callback' => 'mymodule_my_resource_create'
                'args' => array(
                    'name' => 'post_data',
                    'type' => 'struct',
                    'description' => "Should match contents of $form_state['values'] when submitting through the UI.",
                    'source' => 'data',
                    'optional' => FALSE,
                ),
            ),
        ),
    );
}

function mymodule_actools_plugin_api($owner,$api) {
    if ($owner=='services' && $api=='services') {
        return array(
            'version' => 3,
            'file' => 'mymodule_services.inc',
            'path' => drupal_get_path('module','wos2'),
        );
    }
}

function mymodule_default_services_endpoint() {
    $endpoint = new stdClass();
    $endpoint->disabled = FALSE;
    $endpoint->api_version = 3;
    $endpoint->name = 'my_rest';
    $endpoint->server = 'rest_server';
    $endpoint->path = 'my_rest';
    $endpoint->authentication = array();
    $endpoint->server_settings = array();
    $endpoint->resources = array(
        'my_resource' => array(
            'operations' => array(
                'create' => array(
                    'enabled' => '1',
                ),
            ),
        ),
    );
    $endpoint->debug = 0;
    return array($endpoint);
}


texts:
I'm writing a Rule that sends an email when a user uploads a file to a node. How would I output the file's URL and filename in the body of the email?
First, some things to note:

This is an Entityform node
The File Upload field is a mulit-value field
Drupal 7 site

In rules, when I use the replacemement token for the File Upload field...
[entityform:field-file-upload]
...it returns...
property 0, property 1, property 2
There are three files uploaded to this Entityform node, so it appears that Drupal is accurately reporting the correct number of files. But this is all the info I've been able to can extract.
I've tried to change the token in few different way, like these:

[entityform:field-file-upload:file:url]

[entityform:field-file-upload:0:file:url]

[entityform:field-file-upload:url]

[entityform:field-file-upload:0:url]

These all return nothing. What is the corrent token string to return URL, filename, etc.?


texts:
I want to run some JavaScript code during the document ready phase.

Where can I place this code so that it runs each time a page is loaded?
I am using Drupal 7.


texts: Change field options after form has been filled with data

texts: When creating my form, I wasn't enough aware of the configuration for the default core description field. I don't want a summary field, but I did not pay much attention at that  when setting my form in the past. Now, when I try to change the field options to remove the summary field, I get the message "There is data for this field in the database. The field settings can no longer be changed.". Is it possible to override this restriction and force the change?


texts: Exclude tabs based on Tac Lite permissions

texts:
I'm currently using Tac Lite to grant editing permissions to individuals throughout the site. If a user has access to edit a particular node the edit tab appears, if they don't they won't see the tab. However, I also have both the Workflow and Revisions modules enabled and both the Workflow and Revisions tabs show up on every page, meaning that particular users are able to move content to other states (but can't edit it.)
This is due to having 3 roles - author, editor, and publisher. These 3 roles can move content through certain parts of the workflow.
Tac Lite controls who can view based off of department. For example Finance people can edit Finance content. So 2 roles together would be Finance + Author or Finance + Editor.

I am looking for the variable to use to check if an individual has access to edit a particular node and if not hide the workflow and revisions tabs from them.

So far the module looks like this

function tabremoval_menu_alter(&$items) {
//these are the menu items to hide
$item['node/%node/workflow']['access callback'] = 'tabremoval_override_access';
$item['node/%node/revisions']['access callback'] = 'tabremoval_override_access';

}
function tabremoval_override_access($node) {
if (node_access('update', $node, $user)) {
return TRUE;
}
}

But my if statement logic seems to be off. Any help would be greatly appreciated.


texts: How to add extra parameter in drupal core search?

texts:
Please check the image attached

How should I append this second field value with some conditions to core search?


texts: How can you group multiple answer fields?

texts:
Firstly, apologies if I don't use correct Drupal or database terminology - I'm still learning!

I am using Drupal 6 with the latest stable versions of CCK, Views and Date.

I have a content type that requires two 'sections' of fields - the first would be for standard fields, the second would be multiple entry fields where all the fields are related.

It's probably best explained with an example, so here goes:

Let's say the content type is for episodes of a TV show.

Firstly, we want to know the title of the episode, so there'll be a title field.

Secondly, we want a reference number for the episode, so there'll be an ID field.

Now for the grouped fields:

We want to know when the episode was broadcast, and on what channel.  However, it may be that the episode is repeated - and that repeat could be on another channel.  For example:

Top Gear was on BBC2 this evening (26/06/11) at 8pm.  It will be repeated on BBC2 on 28/06/11 at 11.20pm.  It will be repeated again on 29/06/11 at 7pm, this time on BBC3.

So I want to have an unlimited value datetime field.  However, this needs to be bound to an unlimited value text field for the channel (and likewise for any other field with unlimited value data).

How do I achieve this?

Thanks in advance for any assistance!  Please bear in mind that I'm not much more than a novice - I can install a module but I won't know how to do any advanced stuff without guidance!


texts:
I am looking for a solution which displays node list within the date range. Requirement is to display events from today to next 6 days group by date. I have a content type "Agenda" with a date field enabled. So the display should look like:

  2 Jan 2012
      -- 8:00 AM Agenda A
      -- 9:00 AM Agenda B
      3 Jan 2012
      -- 8:00 AM Agenda C
      -- 9:00 AM Agenda D
      4 Jan 2012
      -- 8:00 AM Agenda..
      -- 9:00 AM Agenda..
      5 Jan 2012
      -- 8:00 AM Agenda..
      -- 9:00 AM Agenda..
      6 Jan 2012
      -- No events scheduled
      7 Jan 2012
      -- No events scheduled

I tried with the Views module and the Calendar module also, but I don't want to display in calendar style format, and I need to display only these 6 days (now +6 day), not the entire month view. Other styles are not fulfilling my requirement.

Here I have display 6 dates and display node/event associated with its otherwise display "No events".

Could you please suggest something?


texts:
I have installed Kickstart Commerce 2. I have been able to allow facet searches on my collection pages, by simply adding collection/* under the "Show block on specific pages" section of the blocks that I want to have the facet search block appear on. It works great, except they are not appearing on the full content display pages. The URL path for my product's content type shows as "examplesite.com/lightfixtures/", but adding "lightfixtures/*" under the "Show block on specific pages" didn't make the block appear on my "lightfixtures" pages.

Currently, a user will see several products displayed in a teaser view. The user clicks on the product they want more information on and are brought to a full content display page of that one product. As this page contains no search facets, the user has to click their browser's back button in order to search for something else.

How do I allow facets on my full content display page?

Thank you to anyone they can offer some direction in this please.


texts: Which Rules Event in the Rules module gets triggered after clicking on a link?

texts:
If I click on a link in a node, I want to know which Rules Event in Rules gets triggered that I can use.

Notes:

On the home page, there are a lot of views blocks. So in that node title (or image or whatever is being clicked), in that link, I want to use some Rules Event.
I want to know if I click on that link, which event in Rules can be used in order to invoke. I tried Rules Event Content is viewed, but it didn't work.


texts: Adding Lightbox2 functionality-a how to?

texts:
So I've been using Lightbox2 for my Lightbox. Great module, but I am very confused on how to Add functionality, like captions, text, and links to the Lightbox that is show the image. I know I need to add html, but where?!?! (rel="lightbox")

What I would like to do is show text only and some links on the image that is being used by Lightbox. So say I have Lightbox setup with Views. I go to the page with the images(no text), click on the image, and the lightbox with the image appears. Well, I want to show a caption text and maybe a link to my Ubercart ?

Is this possible and how?

Also can you add a module like hover preview to integrate with Lightbox2 ?


texts: Querying a custom table does not return latest results for anonymous user

texts:
I have a custom module and a simple custom table in the database. When I try to query the table to get the row, it seems Drupal 8, or maybe mysql, is caching the results.

$connection = \Drupal::database();

$result = $connection->query("SELECT SQL_NO_CACHE * FROM {mytable} WHERE id = (:id)", [':id' => $key]);

$result->fetch()

We get the latest data if a I am  logged in to Drupal, but the data is cached if we are not logged in.


texts: Term reference field - print as other format

texts:
I'm using term reference field, which is displaying as entity.

I want to print this in the other place of node.tpl, not full entity but only names.

Is this possible?

I've tried

<?php print render($content['event_speakers']['und'][0]['value']); ?>

But it doesn't print anything


texts: Generating hierarchic URI's based on taxonomy

texts:
I was wondering whether it is possible to have a taxonomy whose URL's are based on taxonomy.
Example: I have a taxonomy list called 'Gallery type' which exists of the following items in which 'Pictures' and 'Movies' are higher in the hierarchy than the subitems:

pictures

pictures-2009
pictures-2010
pictures-2011
pictures-2012

movies

movies-2009
movies-2010
movies-2011
movies-2012

I also have a (gallery) content type in which it is obliged to select an item from the taxonomy list (actually a submitter should select two items: one main item and one subitem (e.g. 'pictures' AND 'pictures-2012'). Then I have made a view for every item in the taxonomy list so that every taxonomy term is a page that contains links to the pages that are created with the term as obliged option (I know that this is hard to follow, but please bear with me)

Example: I create a new gallery named 'Animals' and select the options 'pictures' and 'pictures-2012'. This gallery 'Animals' will be visible on the corresponding views, i.e. /pictures AND /pictures-2012. The page its URI however will be /content/animals. My question is then if it is possible to make the URI follow the hierarchy posed in the taxonomy. In this case it would be: /pictures/pictures-2012/animals

If anything is not clear, please do tell me! English is not my mother tongue, so forgive me if it contains a lot of syntactic and/or grammatical errors!


texts:
I would like to hide the block title when customizing a block, but I didn't find any solution on the internet, Can you please help me?

function custom_theme(&$existing, $type, $theme, $path) {

  $hooks['user_login_block'] = array(
    'template' => 'templates/user_login',
    'render element' => 'form',
    // other theme registration code...
  );
  return $hooks;
}


texts:
I'm doing something that works fine but I get the feeling there is a better way.

I have managed to extend the field settings in the field's manage page to add two new checkboxes. The checkboxes in this case, allow the input form field to be rendered with a Bootstap Add-ON for things like £ signs via my themes template.php

Adding the checkboxes using hook_field_widget_form_alter seems ok (although checking for args is a bit rubbish).

It's the 'wangle' I have to do in hook_widget_validate to get the settings to be incorporated in to the other field settings and saved to the database that is a bit nasty.

There must be a nicer way to do it than that so the question is ..

What is the standard (or better than this) way to extend a field's settings without creating a new widget ?

For reference, here is my code, firstly the added checkboxes  :

<?php
/**
 * Implements hook_field_widget_form_alter().
 */
function mymodule_field_widget_form_alter(&$element, &$form_state, $context) {
  if (arg(5) == 'fields' || arg(4) == 'fields') {
    if (isset($element['value'])) {
      $name = $context['field']['field_name'];
      // PREPEND.
      $val = 0;
      if (isset($form_state['field'][$name][LANGUAGE_NONE]['instance']['settings']['pre_on'])) {
        $val = $form_state['field'][$name][LANGUAGE_NONE]['instance']['settings']['pre_on'];
      }
      $element['#element_validate'][] = 'village_widget_validate';
      $element['pre_on']              = array(
        '#title'         => t('Render Prefix as Prepend'),
        '#type'          => 'checkbox',
        '#default_value' => $val,
      );
      // APPEND.
      $val = 0;
      if (isset($form_state['field'][$name][LANGUAGE_NONE]['instance']['settings']['app_on'])) {
        $val = $form_state['field'][$name][LANGUAGE_NONE]['instance']['settings']['app_on'];
      }
      $element['#element_validate'][] = 'village_widget_validate';
      $element['app_on']              = array(
        '#title'         => t('Render Suffix as Append'),
        '#type'          => 'checkbox',
        '#default_value' => $val,
      );
    }
  }
}
?>

The silly 'wangle' in the form validation to get the custom added fields to save as proper field instance settings that can be reteived.

<?
/**
 * Form validation handler for village_field_widget_form_alter().
 */
function mymodule_widget_validate($element, &$form_state) {
  if (isset($element['pre_on']['#value'])) {
    $form_state['values']['instance']['settings']['pre_on'] = $element['pre_on']['#value'];
  }
  if (isset($element['app_on']['#value'])) {
    $form_state['values']['instance']['settings']['app_on'] = $element['app_on']['#value'];
  }
}
?>

And for completeness here is the counterpart in my template.php that checks for the settings and adds some markup.

<?php
/**
 * Implements hook_form_element().
 */
function mytheme_form_element(&$variables) {
  // Default suffix.
  $suffix = isset($element['#field_suffix']) ? ' ' . $element['#field_suffix'] . '' : '';
  // Check for field settings.
  if(isset($element['#field_name'])){
      if (isset($element['#bundle'])) {
      $field_instance = field_info_instance($element['#entity_type'], $element['#field_name'], $element['#bundle']);
      if(isset($field_instance['settings']['app_on'])){
        // Our Bootstrapped suffix.
        $addoncls .= 'input-prepend ';
        $suffix = isset($element['#field_suffix']) ? ' ' . $element['#field_suffix'] . '' : '';
      }
    }
  }
  // Complied element.
  $output .= '
' . $prefix . $element['#children'] . $suffix . "
";
  return $output;
}
?>

The only bit of interest is the recalling via.

$field_instance = field_info_instance($element['#entity_type'], $element['#field_name'], $element['#bundle']);
$field_instance['settings']['app_on'];


texts: Is there any way to reset a node's properties?

texts: I would like to know if there is a way to reset a node's properties/fields?For example node's body, title,attachments, so as to re write the contents of the page.


texts:
The title field only has 1 row for text.  I want to expand it vertically with more rows.

How to add more rows?


texts:
I have a case where I need to add three custom fields to each image in an image field to hold data.  The content of these fields will not be displayed, but will only be indexed into Solr so they can be used in a custom image search. The logical place for these fields is in the same place that the Alt and Title fields are displayed (when enabled in the field settings), so that they can be entered in when the image is attached. Considering all the field API goodness in D7, it seemed like this would be pretty straightforward. However, it's not turning out that way.

One suggestion was to use the File Entity module, so I can add custom fields.  This seems to work great, in that it allows me to add fields through the UI to the file entity.  However, the problem is that these fields are not available when actually attaching the image to a node - they are only available when you add an image at /file/add.

After looking at the code in image.module, I noticed that the Alt and Title fields are added in the #process callback, which in turn is added in the hook_field_widget_form() imeplentation (image_field_widget_form()).  Since there is an alter hook (hook_field_widget_form_alter()), I implemented it and added my own #process callback:

function nb_alters_field_widget_form_alter(&$element, &$form_state, $context) {
  if ($element['#field_name'] == 'field_images') {
    // Add a custom #process function to add the fields.
    $element['#process'][] = 'nb_alters_image_process';
  }
}

and then added my callback (using code suggestion found here:

function nb_alters_image_process($element, &$form_state, $form) {
  if (isset($element['#type']) && ($info = element_info($element['#type'])) && isset($info['#process'])) {
    foreach ($info['#process'] as $process) {
      $process($element, $form_state);
    }
  }

  // Add the additional Person, and Organization fields.
  $element['person'] = array(
    '#title' => t('Person'),
    '#type' => 'textfield',
    //'#default_value' => isset($item['person']) ? $item['person'] : '',
    '#default_value' => t('Default Person text'),
    '#description' => t('The person'),
    // @see http://www.gawds.org/show.php?contentid=28
    '#maxlength' => 255,
    '#weight' => -2,
    //'#access' => (bool) $item['fid'] && $settings['alt_field'],
    '#access' => TRUE,
  );
  $element['organization'] = array(
    '#type' => 'textfield',
    '#title' => t('Organization'),
    //'#default_value' => isset($item['title']) ? $item['title'] : '',
    '#default_value' => t('Default Organization text'),
    '#description' => t('The organization the person in the image belongs to.'),
    '#maxlength' => 255,
    '#weight' => -1,
    //'#access' => (bool) $item['fid'] && $settings['title_field'],
    '#access' => TRUE,
  );

  return $element;
}

However, this doesn't work as expected. Instead of the fields being added to each image, they are added separately below the last uploaded image.

What do I need to do differently to get my fields to show up for each image? Am I on the right track?

Thanks.


texts: How can I programmatically insert/update thousands of nodes?

texts:
I have to insert 2k nodes with my custom module but it takes forever.
I know there is a way to delete a lot of nodes with only one operation:
$storage_handler = \Drupal::entityTypeManager()->getStorage("node");
$result = \Drupal::entityQuery("node")
->condition('type', 'node_type' )
->execute();
$fc = $storage_handler->loadMultiple($result);
$storage_handler->delete($fc);

I guess there is also a way to insert them with only one operation (and also a way to update them). How can I achieve that?
I get datas from API and for each set of data, i have to create a node. for the moment, this is what i do
foreach($datas as $data)
{
    $node = Node::create(['type'=>'node_type']);
    $node->set('my_field', $data);
    $node->save()
}

And here's an exemple of how I deactivate thousands of nodes
$storage_handler = \Drupal::entityTypeManager()->getStorage("node");
$result = \Drupal::entityQuery("node")
    ->condition('type', 'node_type' )
    ->condition('status', true)
    ->execute()
;
$nodes = $storage_handler->loadMultiple($result);
foreach($nodes as $node)
{
    $node->setPublished(false);
    $node->save();
}

it takes way too long for a simple update query


texts:
EXAMPLE : this is my sample for service resource hook, i'm using drupal 7. I have enabled the services module and ctools module. the end point is working fine, but when i browse the endpoint/commerce_rest/retrieve url is not working

It returns the following exception, exception 'ServicesException' with message 'Could not find resource retrieve.' as following:

/var/www/webui/drupal/sites/all/modules/services/includes/services.runtime.inc:359\nStack trace:\n#0
/var/www/webui/drupal/sites/all/modules/services/servers/rest_server/includes/RESTServer.inc(83): services_error('Could not find ...', 404)\n#1
/var/www/webui/drupal/sites/all/modules/services/servers/rest_server/includes/RESTServer.inc(36): RESTServer->getController()\n#2
/var/www/webui/drupal/sites/all/modules/services/servers/rest_server/rest_server.module(40): RESTServer->handle()\n#3 [internal function]: rest_server_server()\n#4
/var/www/webui/drupal/sites/all/modules/services/services.module(218):
 all_user_func('rest_server_ser...')\n#5
[internal function]: services_endpoint_callback('commerce_rest', 'retrieve')\n#6
/var/www/webui/drupal/includes/menu.inc(516): call_user_func_array('services_endpoi...', Array)\n#7
/var/www/webui/drupal/index.php(33): menu_execute_active_handler()\n#8 {main}

And the source code is:

function test_module_services_resources() {

   $resource = array(
      'commerce_rest' => array(
      'retrieve' => array(
        'file' => array('type' => 'inc', 'module' => 'search_service'),
        'callback' => 'test_module_search_service_results',
        'access callback' => 'search_access_callback',
        'access arguments' => array('view'),
        'access arguments append' => TRUE,
        ),
    )
 )
);
    return $resource;
}

this hook is not invoked, when I browse the url.


texts: How to show a block only if a specific user is logged in?

texts:
I have a block which act as a menu. And the block is created dynamically like that:

$menu_block = array(
    'module' => 'menu',
    'delta' => 'clientmenu' . $account->uid, // the id of the block
    'theme' => 'MYTHEME', // the current theme
    'title' => '<none>', // dispaly no title
    'visibility' => 1, // it is displayed only on those pages listed in $block->pages.
    'region' => 'menu',
    'status' => 1,
    'pages' => $onlythispages, // display the menu only for this client
);

drupal_write_record('block', $menu_block);

And content of the variable $onlythispages is:

// page to display the menu
$onlythispages = 'client/' . $account->name . '
client/' . $account->name . '/*' . '
all-products
product/*';

I created one menu for each created user. Each user has personal (only he can access) pages like:

client/' . $account->name
client/' . $account->name . '/*'

And each user has some common pages which share with all users, pages like:

all-products
product/*

So the problem is that when I go to common pages I see all the "menu blocks" from all the users. So is there a way to show a block only if a specific user id, which actually is the currently logged in user?

I use hook_node_access to handle the access to a node but, how can I do it handle the access to block?


texts: Building a search View that respects access control

texts:
I'm implementing search on a site using taxonomy access control with search api and search api solr.  Reading the help page node access section, I see:

  Needs details on how to build a View that respects access control.

… which is exactly what I need.  How can I make a search view properly respect the taxonomy access control?  I've got node access turned on in the index settings, and see the field available in the views filter, so I see some items with node_access_taxonomy_access_role:n set up, I could try to filter on this, but it would not affect the facets.

I have

  Additional access checks on result entities

turned on in query settings as a temporary measure, but that only filters the search results, and not any facets, etc.

One possible (though inefficient) solution seems like it could be to make two indexes and the have two displays in the search view, searching the right index depending on whether the user is authenticated or not, but I see no good way to limit the index based on the taxonomy term assigned.

It seems like my question extends beyond the boundaries of the search view, and onto the index itself.


texts: How to override page title by content type

texts:
I'm using the pagetitle core module to render a page title. However, for certain content types I want the page main title to be the content type label (e.g. "News") and not the node label (e.g. "Drupal 8 released!").

Is there a simple way to achieve it? My first guess was to use the template_preprocess_page_title but $variables has no context whatsoever about node, node type, etc...


texts: make more rare content type appear in result

texts:
I've made a view that pulls together results from two different content types - "blog posts" and "resources." This resources content type also has a field to further break down resource type (white paper, webinar, case study, etc.)

The problem: There are far more blog posts than resources. So resources get buried, several pages deep in results. How can I ensure that there's a better mix. I considered adding a weight field and grouping by it, but that doesn't seem like it would solve the problem so well. I don't want one weighted over the other. Just a better mix of the newest content, to always include those more rare resources.

I want each results page to show at least one latest 'white paper' resource, one latest 'case study' resource, one latest blog post, etcetera. Something that breaks up blog posts so they don't overpower other needed content.

Or maybe there's a way to force 'for every 2 blog posts, show a resource' ... anything that organically gets results to appear. I can't/don't want to do this manually.

Maybe something 'groupwise' but I'm not sure where/how to accomplish that.


texts: Does a user role change remove their Profile2 fields?

texts:
Say I have a user role PendingArtist, and its Profile2 fields: skills and about me.

How do I change the role of a user? And does the role change delete the PendingArtist's Profile2 fields?

Edited: Don't know why I asked this, could have tried it out myself. Please ignore this question.


texts: Why different available updates in Drush to admin/reports/updates?

texts:
e.g. in the GUI, I'm told (after running admin/reports/updates/update) that I can update 10 modules. But drush rf; drush up tells me that only three updates are available. Specific example: the GUI says I can update to Views 7.x-3.3, but drush up views says "no code updates available."

I usually prefer to use drush to do the updates since I don't want to pass credentials to my server's user account over the unencrypted web!

But I don't get why drush should report update status differently? Can anyone enlighten me?


texts: Adding multiple users to a field using user/autocomplete

texts:
I have the following code to add a field to my custom module to add in users. But I can only add in one user using the user/autocomplete feature.

$form['usershare'] = array(
  '#title' => t('Share Collection with:'),
  '#type' => 'textfield',
  '#autocomplete_path' => 'user/autocomplete'
);

How do I enable multiple users? These users should be separated by a comma on the back end for me to process it.


texts: Retrieve data from Field API programmatically

texts: I have a custom field called phone_number for the user. I need to retrieve the data in it from the database and use it to call other functions. I've looked through the Field API and I can't find the specific function. I read somewhere in the Field Attach API that most of the functions there take $entity as a variable but none of the functions there gives me what I need. Please help.


texts: Autocomplete won't work for entity reference field unless User > Administer Users permission is granted

texts:
I have an entity reference field (users) on a node in D8, and the autocomplete suggestions won't show unless the User > Administer Users permission is granted to the role.

I'm trying to let event creators select who is presenting a certain topic, but I don't want them to be able to edit users' settings. Any ideas?


texts: How to show a place holder block if a view is empty

texts:
I have a site that has multiple inventory views. When a view is empty (no items to list) I need to display a block that tells the user to check back later.

How can I do this?


texts: check webform is successfully submitted by ajax or not

texts:
i am using ajax webform module to submit a webform in block via ajax.the form is submitting properly with ajax without refreshing page. i want to hide a div on successful submision after validation ,so i want place a check either form is submitted sucessfully or not . what is the best way to accomplish this . i am using this code but its returning true even the form is vaildated or not .

 $( document ).ready(function() {
   $("#edit-webform-ajax-submit-15").click(function(){
    $.ajax({
    type: "POST",
    url: "http://xxxx/apptreetech/sites/all/modules/webform_ajax-7.x-1.1/webform_ajax/js/webform_ajax.js?n1uww0&_=1394090072820",
    dataType: "json",
    contentType: "application/json; charset=utf-8",
    complete: function (response) {
     console.log(response);

    },error: function () {
    alert("error is there");

    }
    });
    });
    });


texts: 504 Gateway Time-out error in batch process

texts:
I have submit the custom form using batch process in which process I have upload big xml file(min 200MB) and read xml file and inserted xml data in database

but after 30~35 minits batch process display the

  504 Gateway Time-out error.

Also I have increased memory size, excution time, max upload size and so on.

Please help me..


texts: Add a taxonomy term to many vocabularies

texts: Is there is any way to add one term to many vocabularies with the same name and same id in drupal 7


texts: How do I allow a user to create related accounts and edit their content?

texts:
Here is what I'm trying to achieve: The site has users who can add items to their wish lists (a wish item is one node); I'd like to enable these users to create subusers that are related to them and create wish items for them.
For example,  I'm a user, I added items that I wish I would have, but I want to create a profile for my kids, and add items to their wish list; in this way, I could share those lists with their uncle.

How can I achieve something like this in Drupal 7?

In the case somebody is going to suggest the Subuser module, I tried it, but I got a bunch of database errors just installing and enabling it.

The kind of answer I'm hoping for is a sort of overview of how to achieve something like this, just to push me in the right direction. I'm not expecting code.


texts: Programmatically setting video_embed_field URL

texts:
I am trying to populate nodes programmatically from a feed (migrating earlier site to Drupal 9). So far I have managed to get everything else to move, but I can't figure out, how to set video_embed_field or rather the URL-value of the video. I found an example, but it caters just youtube, but there are also other video providers used.
I have tried the following ideas:
$node->set("field_video", $videourl);

$node->field_video = ['input' => $videourl];

$node->field_video = ['value' => $videourl];

but so far nothing works.
Could anyone hint me to the right direction?