texts:
I have a simple form, presenting an "Order this" button. That form is placed on a node. When people press that button, I want to start an ordering-workflow.

Currently the Drupal-way seems to be:

Add form to node on node/123,
User clicks form-submit, POST goes to node/123.
hook_form_submit() gets fired, receives POSTed values trough form API.
In that function, the POSTed-data is stored in a Session; then a drupal_goto() sends redirect-header to /shop/checkout, user GETs /shop/checkout.
Code building the /shop/checkout page must retrieve information from Session to build the checkout-workflow.

How can I simply send the POST to /shop/checkout and present my HTML there, based on the POST, instead of all the intermediate goto and session-spaggetti?


texts: "Unable to generate the derived image located at public://styles/uc_category/public/tg.jpg"

texts:
(Drupal 7 under Linux)

This is clearly a Drupal permissions problem, but I'm baffled. If I

rm -rf styles

and refresh the page causing the error, styles and it's sub-dirs are re-created thus:

drwxr-xr-x 3 www-data www-data 4096 Jan 25 16:07 styles

drwxr-xr-x 3 www-data www-data 4096 Jan 25 16:07 uc_category

drwxrwxr-x 2 www-data www-data 4096 Jan 25 16:07 public

But I still get the error. And I still get it if I

chmod -R 777 styles

Any suggestions?


texts: Exposed filter value into the session and cookie?

texts:
I want users visit my site regularly. And I need to store their settings to session (cookie). These settings are: Views Exposed Filter on the FrontPage (like to hide materials from the black list users).

So I have the FrontPage View and Taxonomy Term View. These views have exposed filter.

Once visitor selected values in this filter they should to store during he browsing the site and more when he visit site again.

I do not want to use JavaScript. I want to store cookie with php and to get it with php.

And I want drupal cache all pages for all possible filter values.

Please, have I to write a new Drupal CMS or where have I to get the answer?


texts: Custom template files for multiple blocks provided by a custom module?

texts:
The custom module is called, "epic_module". It defines several blocks, say "awesome_block" and "epic_block".

function epic_module_block_info() {
  $blocks['awesome_block'] = array(
    'info' => t('Awesome block'),
    'cache' => DRUPAL_NO_CACHE,
  );

  $blocks['epic_block'] = array(
    'info' => t('Epic Block'),
    'cache' => DRUPAL_NO_CACHE,
  );

  return $blocks;
}

function epic_module_block_view($delta = '') {
  $block = array();

  switch ($delta) {
    case 'awesome_block':
      // TO-DO: Set $block['content'], etc...
      break;
    case 'epic_block':
      // TO-DO: Set $block['content'], etc...
      break;
  }
  return $block;
}

I have also created a templates directory under my module's directory.

I'm confused by the naming conventions. I want to link the template files for the specified blocks.


texts: Views Conditional Fields According to Devices

texts:
Does views allows to render fields according to device. For example is there a possibility to load field a if website is loading on iphone, load field b if device is loading on android.

or

load field 1 if website is loading on smart phones, load field 2 if tab and load field 3 if desktop.


texts: Form processing issue while generating a dynamic form and preparing via API calls directly

texts:
How can I fix the processing and submission of forms that I am preparing and rendering dynamically via API calls.

function drupal_set_confirmation($message, array $options, array $escape=array(), $type='warning', $details=NULL){
    $form = array();

    $form['title'] = array(
    '#markup' => '<h3>' . t($message) . '</h3>'
    );

    if (!empty($details)) {
        switch(gettype($details))   {
            case 'string':
                $form['details'] = array(
                    '#markup' => $details,
                );
            break;
            case 'array':
                $form['details'] = $details;
            break;
        }
    }

    if (!empty($options)) {
        $form['options'] = array(
            '#type' => 'container',
            '#attributes' => array('class' => array('user-confirmation-options')),
        );

        foreach($options as $key => $option) {
            $form['options'][$key] = array(
                '#submit' => array($option['callback']),
                '#type' => 'submit',
                '#value' => $option['title'],
                '#attributes' => $option['attributes'],
            );
        }

        if (!empty($escape)) {
            $form['options']['escape'] = array(
                '#markup' => l($escape['title'], $escape['path']),
            );
        } else {
            $form['options']['escape'] = array(
                '#markup' => l(t('Cancel'), current_path()),
            );
        }
    }

    $form_state = form_state_defaults();
    $form_id = 'form_user_confirmation';

    drupal_prepare_form($form_id, $form, $form_state);
    // I do not see any reason to call drupal_process_form while serving the form.
    //drupal_process_form($form_id, $form, $form_state);
    $rendered_form = drupal_render($form);
    return drupal_set_message($rendered_form, $type);
}

And it works greatly to show a dialog form of my own choice by calling.

drupal_set_confirmation(t('Do you really want to suicide?'), array(
        'okay' => array(
        'callback' => '_yes_kill_me',
        'title' => t('Yes'),
        'attributes' => array('class' => array('button', 'tiny')),
    ),
    ), array(
        'title' => t('No'),
        'path' => current_path(),
    ));

And callback function as #submit handler for a particular element is not invoked.

How can I fix the form processing and submission issue using this approach to work?


texts:
I need to customize part of the Fivestar module's output, so that I am able to assign points ( e.g. 1, 2, 3, 4, 5).

I want the module to sum up and display the total points received by the content or user, and I want to use my own icons in the widgets.

Is this possible?

I am using Drupal 7.


texts: Teaser display showing on full node content page

texts:
as my title says my teaser display had been showing up on the full content page of my nodes and we can't seem to figure out "Why".

The content type has 2 views and 2 blocks.

One view with all
One view with all of one author
One block with the newest 3
One block with the 3 most popular.

It started with one node that showed the teaser instead of the content? Then all the nodes in the blocks started doing this.
And now all the nodes show the teaser instead of the content page.
Even when accessing it through: Admin > sturcture > content.

This is what the content page used to look like

This is what the view page looks like

And this is what the content page NOW looks like

UPDATE: So I found out that when I remove the blocks out of the regions my content shows normal. When the Two blocks are IN a region the content page of ALL is messed up. Still don't know why.

UPDATE2: So I a part the problem.

The block view of the 3 most popular tours didn't have a restricted amount of items per page.

I noticed that when I removed the block out of the regions the content pages where fixed.

So I started to look at that block and that was the only thing that didn't fit. So I changed it to limited 3 items per page. And added the block again to the region.

Now the content that is shown in the blocks, when clicking them they still show a teaser on the content page. Event when accessing them through the view or admin panel.


texts: How do I know what variables are available for a theme function?

texts:
I am using the Menu block module. In one template I have used kpr($page); to see what hooks the menu block is calling. I then created the correct function in my theme's template.php file mytheme_menu_block_wrapper__1(). The examples I have read suggest that this should not take any arguments.

So what I'm really interested in learning is how to debug drupal.

Is there a function that I can call that will show me all the available variables, something like drupal_special_dump() that would show all variables I can use?  Any help would be appreciated.


texts: How to create a rule to combine the terms of 2 fields to create a new term stored it in a 3rd field?

texts:
I have a content type that has 3 term reference fields:

Field A, required, is a term reference using a vocabulary with machine name vocabulary_a.
Field B, required, is a term reference using a vocabulary with machine name vocabulary_b.
Field C, is a term reference using a vocabulary with machine name vocabulary_c and is generated automatically.

When creating or updating a node, values are entered for field A and B. I want to have a rule (using the Rules module) with some Rules Action to set a data value for field C, equal to the concatenation of the value entered for field A and B. Here is a picture of what I'm trying to achieve:

When I use a Rules Action of "Set a data value" (for field C), I can only refer to one value (eg the token from Field A), and not to the tokens from both Fields (A and B).

So how can I get this to work somehow?

Note that this is a followup to these prior questions (which are not duplicates ...):

How to create a rule to combine the terms of 2 fields to create a new term and store it in a 3rd field? : that question assumes the taxonomies for the 3 fields are the same (as per the "The tags from those 3 fields all relate to the same taxonomy." in it). While this question here is about "Each of these 3 fields have their own taxonomy (they are different)".
How to correct my rule to prevent duplicate taxonomy terms to be created? : that question is about preventing the creation of duplicate terms for the "Field C" (when using the rule in the linked question). And inherently (since it is a followup question) also is about the same taxonomy for the 3 fields.

So this question here is about (a) those 3 fields which each have their own taxonomy and (b) at the same time avoiding the duplicate terms to be created.


texts: hide the webform after submission in webform 3.0

texts:
I have a webform (webform 3 module) embedded on my websites homepage. I was looking for a way to hide the webform after it has been submitted.

-> Tried to check the $_POST but that does not work
-> Maybe the webform API could help?

Thanks.


texts: How output JSON for multiple "Rest export" views?

texts:
In Drupal 8, I'd like to retrieve JSON for multiple Rest export views, not just a single one.
Example of data I want to see (cars and tires being two seperate content types):

{
    "cars": [
      { "nid": 1, "brand": "BMW", "weight": 100, "compatible_tire_nids": [100,101,102] },
      { "nid": 2, "brand": "Mazda", "weight": 100, "compatible_tire_nids": [102] },
      { "nid": 3, "brand": "Volvo", "weight": 1000, "compatible_tire_nids": [103] }
    ],
    "tires": [
      { "nid": 100, "brand": "Michelin" },
      { "nid": 101, "brand": "Good Year" },
      { "nid": 102, "brand": "Dunlop" }
    ]
}

I can output the JSON fine seperately, so you visit one url to get cars, and another URL to get tires. But I can't figure out how to merge the two.

Can anyone help me figure this out, or anyone who can point me in the right direction to achieve this?


texts: Using Ajax-Callback with ajax_command_invoke to invoke custom jQuery command

texts:
I have a button on a form that when clicked adds an additional subsection to the form via ajax. Now I need to make it so the form automatically scrolls to the start of the newly added content.

I rewrote the ajax callback function so it returns an ajax command array instead of just the changed form data, and added an ajax_command_replace call in the array to still have my content replaced. This works and from the user side everything is unchanged.

Now I found out that I can add an ajax_command_invoke command to have a jQuery function called upon the DOM element I want to interact with. Unfortunately there didn't seem to be an in-built scrollTo jQuery function, so I had to add my own.

This function works when I call it via Firebug, but the ajax callback just gives me an error:

  TypeError: $element[response.method] is undefined
  $element[response.method].apply($element, response.arguments);

So I guess my problem is that my custom jQuery module isn't actually added to jQuery at the time the callback is handled, but only after that?

Here's my configuration (sensitive data hidden with <...>:

Within the Drupal Module, my callback function:

function callback($form,&$form_state) {

  drupal_add_js(drupal_get_path('module', '<...>') . '/js/jquery_plugins.js');

  $commands = array();

  $commands[] = ajax_command_replace(NULL, drupal_render($form[<element>]));
  $commands[] = ajax_command_invoke('<...>', 'scrollTo', array(750));

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

}

In the included file, my jQuery scrollTo function:

(function(jQuery) {
  jQuery.fn.scrollTo = function(data) {
    jQuery('html, body').animate({
      scrollTop: jQuery(this).offset().top
    }, data);
  };
})(jQuery);

Where should I include my jQuery module so the callback knows what I want from it when it's handled?

Update:

I had most of my help until that point from this similar discussion on Drupal.org. It seems to have worked for them.


texts: How to make the name of an organic group unique

texts:
can someone explain how to make groupnames unique? If i create 2 groups with the same name, i want to become a validation error. Actually i tested og in the commons distribution an there i can create groups with same names, but in the list of all groups are only one of the same groups listed.

Thanks for your help.

Greats Daniel


texts:
We have a content type with 3 field, title, body and  image field, client side in cross platform mobile application (e.g. Angular or jQuery). We want the mobile users to be able to create a node with the RESTful service.

I read POST for creating content entities and JavaScript and Drupal 8 RESTful Web Services, Services Quick Start Up Guide and all the examples I saw are about simple text fields.

How can we pass images to the REST service?

Let's suppose our field machine names are title, body, and image.


texts:
I am hoping to find a drupal module that can transform a PDF to image and merge that image with another one.
Use case scenario is basically placing an endorsement stamp on an image.

Thanks


texts: Get Paragraph's Parent Node Before the Node is Saved in Constraint

texts:
I have created a Paragraphs Constraint and I am unable to get access to the parent node's bundle in the constraint because the node has not been saved yet.
public function validate($entity, Constraint $constraint) {
  $node = $entity->getParentEntity();
  $type = $node->getType();
}

In the case above, $node is null if the node has not been saved yet.
The above only works if I edit an existing node.
Is there another way to grab the paragraph's parent node bundle before the node has been saved?


texts: How to update only one field using Views?

texts:
Is it possible to update only one field using Views? Say, you use Views to list all property items. Property content type has one field called 'Position' with option values as 'Featured', 'Hot', 'Sold', 'Vacant', etc.. For each item in a row listed you have what looks like the following:

Views Display:

ID   Title     Type       Address       Total Size (sq Ft)     Position        Action
123  Bay View  Apartment  Moroco        1245                   (combobox)      Update

There are other fields for this content type that will not be included, hence, only those relevant fields are shown in this particular Views. So when you click 'Update' button the item will be updated accordingly, that is, only the 'Position' will be updated.

And maybe for other instances, a few fields - instead of one as above - can also be updated. The above is only an example with one field.

Any ideas?


texts: How do I upgrade to Google's Universal Analytics using the Google Analytics module?

texts:
I have a site using version 1.4 of the Google Analytics module and I wanted to upgrade to Universal Analytics.  The module page says that I need the 2.x version of the module, so I updated to 2.x-dev, ran update.php (no updates necessary), and cleared the cache.

I then logged into Google Analytics and went to Audience -> Demographics -> Overview, after which I clicked Validate tracking code, but this failed.

So, I went to the module's config page (admin/config/system/googleanalytics) and checked Track display features under Search and advertising.  I then cleared the cache.

I again tried to re-validate but it continues to ask me to validate.

What more do I need to do to upgrade to Universal Analytics?


texts: How do I add custom validation constraints to Entity fields?

texts:
I'm trying to add validation (i.e. constraints) to a field added to a specific (node) entity.

As per documentation here https://drupal.org/node/2015613 i'm trying to change the Field Definition to add a constraint through setPropertyConstraints().

I seem to be able to do so through hook_entity_bundle_field_info_alter(), but only for base fields, not for fields added with Field UI.

My code so far:

function validation_test_entity_bundle_field_info_alter(&$fields, \Drupal\Core\Entity\EntityTypeInterface $entity_type, $bundle) {
  if ($entity_type->id() == 'node' && $bundle == 'article') {
    // This works!
    $fields['title']->setPropertyConstraints('value', array('Length' => array('max' => 3)));
    // This doesn't - setPropertyConstraints() doesn't seem to exist
    if (!empty($fields['field_test_field'])) {
      $fields['field_test_field']->setPropertyConstraints('value', array('Length' => array('max' => 3)));
    }
  }
}

Though hook_entity_bundle_field_info_alter somewhat implies that the $fields array would be FieldDefinition classes (or subclasses), this doesn't seem to be the case? At least the setPropertyConstraints() method is not callable.

I've been debugging for a few hours to find out how this works, but I'm probably missing something obvious. Anyone has any pointers? Am I using the wrong hook or place to try to alter it?

Thanks!
Sven


texts:
Do Config entities have views support? What I have:

ConfigEntity which have fields: id, admin_label, display_label, config_options.
ContentEntity with fields: id, entity_config_id, author.
entity_config_id is an entity_reference to ConfigEntity entity.
I use views to show all ContentEntity entities and I outputted fields: entity_config_id, author.

What I need:

I want to output in views with ContentEntity some additional fields from ConfigEntity(e.g. display_label). But I can't do it, because I don't see any way how to integrate ConfigEntity with views.


texts: Drupal for Firebug does not work in FF> Works fine in Chrome

texts:
I have downloaded and installed Drupal for firebug Module and FF and Chrome extensions.

I log in as admin (uid 1) and do a simple output call:

firep("this is some message", "Message Title");

On chrome I can see the output fine, but in firefox I get the following message:

  No Drupal for Firebug data was found.

Either this site is not running Drupal or the Drupal for Firebug module has not been installed/enabled.


texts: Views + entity translation - show list of translated languages

texts:
I need a view in table format for an administration page, next to each node I want a list of the currently translated languages in it's own table cell. It would look like:

title  |  languages
node1  |  english
node2  |  english, chinese

I have seen this post which does it by grouping (which I don't want):

Display node's languages in views

And this, which I can't seem to get to work (filtering by source language does nothing - presumably as it doesn't use entity translation?):

Any idea how this can be done?


texts:
Drupal 8.6.1

I have some menu items  I would like to hide from some users: An administration menu with documentation about site admin; A contributors menu with documentation for contributors. etc.

It appears that Drupal prefers every menu entry to link to something. I have these menus pointing to route:<nolink> and have the content hanging from them, tagged as required to implement https://www.drupal.org/project/permissions_by_term.

The result of this is that the top level menu items are visible to everyone.

Is the Drupal philosophy to create some content/view and assign permissions to that for these top-level menus?


texts:
The following steps lead to a situation where drush cc all would fail.

Build a site, with fields and stuff. Especially one or some fields for the user entity.
Install an alternative cache plugin, e.g. mongodb.
Change the site configuration. E.g. remove one of the fields on user entity.
Disable the alternative cache plugin, switch back to database cache.

Now the database cache contains really old data (or this is how I imagine it), still referencing fields that have long been deleted.

On drush cc all, drush first wants to bootstrap Drupal. Doing this, it also tries to load a user account for login. This lets it use cached data for user fields.

I get a crash with mysql exception from field_sql_storage_field_storage_load(), because it tries to load non-existing fields.

I suppose this is just one example for a site being broked due to really old cache data, after switching the cache plugin.

How can one recover from this situation?


texts:
In Drupal 7 I could go to any entity's "manage display" and choose "expert" or "minimal," etc.

In Drupal 8, I can see a Twig template for expert, and a Plugin for expert (ex.g.) as well. But how do I get the UI where I can choose 'expert'?

If it's no longer in the UI, how do I implement my own Plugin? How can I write twig for just that field? If I'm doing that, why do I need Display Suite anyway (as I'm just using a one-col layout)? Do I?


texts:
I am trying to use Views org chart module in drupal.
I have created a node type contact using CCK module which stores in personal details of any person.
I have used relation module to  create relation between contacts like father - son relationship.

Now I wish to display the records in the hierarchical format.

For this i am trying to use Org chart module

Here is my setting for views.

I have added a relation isFatherof in relationship in views and in tile have checked in option is relationship

Below is my setting of org chart module

The view doesnt work but gives weird results


texts: Rules: save a node but not "fire" a rule that create a loop

texts:
I have a rule that "fire" on a condition of "node save". Now in the action of this rule I get the node that I receive via "arguments" and set/change some values if some other values are foo or bar.

My problem is: how can I save the node without create a loop ?


texts: How to keep theming of a view after changing type of view?

texts:
I am using a Drupal distro(Recruiter).
The distro has a view of type "Rendered entity".
However I am interested to change the type of the view to "Fields".
However when I make the change,the default theming of the view dissapears.So I am interested to keep the default theming of the view.
How can I do that?What shall I inspect?I am not a theming/css guy so any help would be appreciated.
thanks!


texts: Photo Gallery attached to Story - How to Create

texts:
I figured out a way to add a photo gallery to the bottom of a story using a custom content type for the photos, then creating a view with clickable thumbnails and saving it as a block. The problem is I can't reuse this for the next story. I would need to create yet another content type and another view. How can I set it up so I can post a different gallery to a different story?

Is there a module that might help with this?  I tried Views Galleriffic, but it doesn't seem to work as a block.  I couldn't find any way to make the gallery appear at the bottom of a story.


texts: Populate multiselect options onchange of dropdown using AJAX

texts:
I have created a content type (Geological Locations) with 2 fields, Country and States.

The Country field is a select box, and States field is a multiselect. So if i select a Country, the States multiselect should be populated based on the selected Country using AJAX.

In my custom module, i used node_form_alter() to customize the node creation form.

I have tried the below code, but it is not working as expected.

function demo_form_geological_locations_node_form_alter(&$form, &$form_state, $form_id) {
    $form['additional_settings']['#access'] = false;
    $form['field_country']['und']['#options'] = array(''=>'Select', 'india'=>'India', 'usa'=>'USA');
    $selected = isset($form_state['values']['field_country']) ? $form_state['values']['field_country'] : '';

    $form['field_country']['und']['#ajax'] = array(
          'callback' => 'ajax_states_callback',
          'wrapper' => 'states-wrapper',
    );

    $form['field_states']['#prefix'] = '
';
    $form['field_states']['#suffix'] = '
';
    $form['field_states']['und']['#options'] = ajax_get_state_options($selected);

    return $form;
}

function ajax_states_callback($form, $form_state) {
    return $form['field_states'];
}

function ajax_get_state_options($key = '') {
    $options = array(
        t('usa') => drupal_map_assoc(
          array(
            t('Florida'),
            t('Georgia'),
            t('Atlanta')
          )
        ),
        t('india') => drupal_map_assoc(
          array(
            t('Maharashtra'),
            t('Gujarat'),
            t('Karnataka')
          )
        )
    );

    if (isset($options[$key])) {
        return $options[$key];
    }
    else {
        return array();
    }
}

Can anyone tell me where i am going wrong?
I am expecting the output like below screenshot, when i select the Country "India":


texts: Can't drupal_execute('filter_admin_format_form') on hook_install?

texts:
I'm attempting to configure an input format on hook_install() with the following code:

module_load_include('inc', 'filter', 'filter.admin');
$form_state = array(
  'values' => array(
    'name' => 'Full HTML',
    'format' => '2',
    'roles' => array(
      1 => 0,
      2 => 0,
      3 => 1,
    ),
  ),
);
$arg = filter_format_load(2);
drupal_execute('filter_admin_format_form', $form_state, $arg);

However this produces the error:

Filter format names need to be unique. A format named Full HTML already exists.

However if I run the same code on hook_init(), then it runs without error.


texts: For Drupal 7, is there a hook debug mode equivalent to the theme debug mode?

texts:
As a beginning developer, it seems like I spend a significant percentage of my time googling to find out what hook to call in order to modify something before it renders.

In the drupal 7.33 release, the theme debug mode was introduced, which provides contextual information in the page's HTML to theme developers and can be accessed by setting the theme_debug variable to TRUE.

Obviously there is no hook debug mode supported in core, but is anyone aware of a module that would provides contextual information about attempted hook calls, similar to how theme debug mode displays theme suggestion attempts?

Specifically, I am wondering if there is a module that would generate a list  of every call to drupal_alter(), module_invoke_all(), or module_invoke(), along with the $type, $module, and/or $hook arguments supplied to these functions.


texts: How do I override an entity view controller?

texts:
I am trying to override the entity view controller for a commerce product view, so that I can  redirect the user based on certain conditions.
I am trying to do this through the RouteSubscriber::alterRoutes implementation.
class RouteSubscriber extends RouteSubscriberBase {

  /**
   * {@inheritdoc}
   */
  protected function alterRoutes(RouteCollection $collection) {
    if ($route = $collection->get('entity.commerce_product.canonical')) {
      $route->addDefaults(['_controller' => '\Drupal\mymodule\Controller\ProductViewController::view']);
    }
  }

}

My custom controller is acknowledged, but I'm getting the following error:

RuntimeException: Controller "Drupal\mymodule\Controller\ProductViewController::view()" requires that you provide a value for the "$_entity" argument. Either the argument is nullable and no null value has been provided, no default value has been provided or because there is a non optional argument after this one. in Symfony\Component\HttpKernel\Controller\ArgumentResolver->getArguments() (line 78 of /var/www/html/vendor/symfony/http-kernel/Controller/ArgumentResolver.php).

My ProductViewController extends the Drupal\Core\Entity\Controller\EntityViewController.
class ProductViewController extends EntityViewController {

  public function view(EntityInterface $_entity, $view_mode = 'full')
  {
    return parent::view($_entity, $view_mode);
  }

}

Can anyone tell what additional route context parameters I need to add to get this working?


texts: How to subscribe to the "order placed" "order paid" event?

texts:
I created a module for generating a license and recording it in the user field, I want to create an event, it should be triggered when the user has completed a purchase (bought an item or paid for an item), but I don’t know how here is an example of an example of a commerce module site's documentation site.
modulename.services.yml
   services:
  modulename.event_subscriber:
    class: Drupal\modulename\EventSubscriber\CartEventSubscriber
    arguments: ['@messenger', '@commerce_cart.cart_manager']
    tags:
      - { name: event_subscriber }

CartEventSubscriber.php
    <?php

namespace Drupal\modulename\EventSubscriber;

use Drupal\commerce_cart\CartManagerInterface;
use Drupal\commerce_cart\Event\CartEntityAddEvent;
use Drupal\commerce_cart\Event\CartEvents;
use Drupal\commerce_product\Entity\ProductVariation;
use Drupal\Core\Messenger\MessengerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

/**
 * Cart Event Subscriber.
 */
class CartEventSubscriber implements EventSubscriberInterface {

  /**
   * The messenger.
   *
   * @var \Drupal\Core\Messenger\MessengerInterface
   */
  protected $messenger;

  /**
   * The cart manager.
   *
   * @var \Drupal\commerce_cart\CartManagerInterface
   */
  protected $cartManager;

  /**
   * Constructs event subscriber.
   *
   * @param \Drupal\Core\Messenger\MessengerInterface $messenger
   *   The messenger.
   */
  public function __construct(MessengerInterface $messenger, CartManagerInterface $cart_manager) {
    $this->messenger = $messenger;
    $this->cartManager = $cart_manager;
  }

  /**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents() {
    return [
      CartEvents::CART_ENTITY_ADD => [['addToCart', 100]]
    ];
  }

  /**
   * Add a related product automatically
   *
   * @param \Drupal\commerce_cart\Event\CartEntityAddEvent $event
   *   The cart add event.
   *
   * @throws \Drupal\Core\TypedData\Exception\ReadOnlyException
   */
  public function addToCart(CartEntityAddEvent $event) {
    /** @var \Drupal\commerce_product\Entity\ProductVariationInterface $product_variation */
    $product_variation = $event->getEntity();
    if ($product_variation->getSku() === 'some_sku') {
      $cart = $event->getCart();

      // Load a known other product variation.
      $variation = ProductVariation::load(5);

      // Create a new order item based on the loaded variation.
      $new_order_item = $this->cartManager->createOrderItem($variation);
      $new_order_item->setQuantity(1);

      // Add it to the cart.
      $this->cartManager->addOrderItem($cart, $new_order_item);

    }
  }

}


texts: Month and year to display based on content post date

texts: I have a magazine blog that I am creating in Drupal 7. I have the date displayed in the upper right hand corner (JAN 2012). How could I have this display work dynamically based on the post date of the article shown or current month if on the main view (blog) landing page? Each blog landing page is a view so the content is filtered that way. I two custom content types to help filter content and custom field created on each as the publish date to push and pull content based on the month. I need to use that publish date field as the date. How do I tap into that field for the date I need?


texts:
I want a form with checkboxes that will have all the severity levels and when the user (e.g selects only the error i want to select only the errors from watchdog. My problem now is that in watchdog the severities are with numbers :/ :/ :/.....here is my form:

/**
 * Settings form for the user.
 */
function kkkk_admin_settings() {

    // Form for the severity checkboxes.
    $kkkk_severity_levels = variable_get('kkkk_severity_levels', array());

    // Declare empty options array.
    $kkkk_severity_options = array();

    // Loop through each severity level and push to options array for form.
    foreach (watchdog_severity_levels() as $number_select => $severity) {
      $kkkk_severity_options[$severity] = drupal_ucfirst(
        $severity);
    }
    $kkkk_form['kkkk_severity_levels'] = array(
      '#type'          => 'checkboxes',
      '#title'         => t('Type of log messages'),
      '#options'       => $kkkk_severity_options,
      '#default_value' => array_values($kkkk_severity_levels),
      '#required'      => TRUE,
    );
    dsm($kkkk_severity_levels);
    return system_settings_form($kkkk_form);
  }
}

this dsm($kkkk_severity_levels);if i have selected error gets me out:

error (String, 4 characters ) error
emergency (Integer) 0
alert (Integer) 0
critical (Integer) 0
warning (Integer) 0
notice (Integer) 0
info (Integer) 0
debug (Integer) 0

I need to take out :

    error (String, 4 characters ) 3
    emergency (Integer) 0
    alert (Integer) 0
    critical (Integer) 0
    warning (Integer) 0
    notice (Integer) 0
    info (Integer) 0
    debug (Integer) 0

where 3 is the number of the error severity. I need to take this number in order in my function to select only the error messages from watchdog.... Could someone help?? If I need a new form could you help with that form plz ?? I am new in coding.. :/ :/ :/


texts:
I have a view where I show nodes of content type, with some filters exposed .
But , I wish that these filters also show results of users (based on their username and a field of them).

Exposed Filters (nodes):

Title node (TextField)
Body (TextField)
Field Category (Dropdown)

Exposed Filters for Users (desired):

Username (TextField)
Field Category (Dropdown)

In this case , I wish that the Title_Node and Username are the same TextField(Is it posible). And the field_category serve to search both.

Is it posible to show content types and users in a views in Drupal 7 with filters exposed?

Sorry for my English. Thanks in advance.


texts: How to exclude Views results for custom entities for which a user has no permission to view them?

texts:
I have a custom entity which I list in views. I set access control for them, but when I list in views these entities, all entities shows up, those one too, which  the user does not have permission to access.

What do I need to implement to filter out those entities, which the user does not have right to view?


texts: Exclude the current node in a view with related items in case of multiple contextual filters

texts:
Excluding the current node from a display with related items is fairly straight forward. However, in my case there's already another contextual filter (NID) in the game for other purposes.

Adding the exclude functionality on the existing contextual filter isn't working, so I guess an extra contextual filter should be applied in this case. However, simply adding another contextual filter (NID) that's configured to exclude the current node results in no items at all (that moment when you're confronted with the lack of grouped AND or NOT filters for contextual filters).

This situation doesn't feel very unusual to me, so I guess there must be a correct approach for this. My guess is that something must be done with the already existing contextual filter, but can't seem to figure out what exactly.

Can anyone help?


texts: Add followers' list at the end of discussion

texts:
I want to add following functionalities in Drupal 7.

Any forum-user can have followers, So I want to show followers list on forum-user's profile page. (Like this)
Those followers should be automatically subscribed to all the posts by that author.

I'm using Advanced Forum module. How to do this using Views module or any other possible way?


texts:
I am unable to edit a page content on my site even with the admin account.I have a page with the profile informations of the committee, I can see that page on the site but when i click the edit button it shows nothing.

I have seen the log and it is showing a error message as:

  call_user_func_array() expects parameter 1 to be a valid callback, function 'access_denied_node_form' not found or invalid function name in /var/www/includes/form.inc on line 377.


texts: Remove empty url argument from view with exposed filter

texts:
I have a view with exposed filter "Has taxonomy term" (filter identifier: "topic") and exposed sort: Created (default one) and Rating.
On a view page, when I change sort option to Rating, url of a view page is becoming
?topic=&sort_by=rating

How to remove this empty argument from page url?

I tried

  $('#views-exposed-form-taxonomy-term-page').find(':input[value=""]').attr('disabled', true);

and

  $('#views-exposed-form-taxonomy-term-page').submit(function() {
    $(':input', this).each(function() {
        this.disabled = !($(this).val());
    });
  });

but it didn't work.


texts: I have a list of nodes (ubercart products) filtered by taxonomy term. How can I attach a term description to the view?


texts: Language switcher with country code and title

texts:
For my responsive site i try to override the language switcher block to get both, the long title of the country and the short code. So I can change the display for smartphone or desktop.

I dont know whats the best solution, print a second block or gives out an array with 2 links in a list element. These code overrides only the title.

   function mytheme_links__locale_block(&$vars) {
      foreach($vars['links'] as $language => $langInfo) {
        $vars['links'][$language]['title'] = $vars['links'][$language]['language']->language;
      }
      $content = theme_links($vars);
      return $content;
}


texts: Cannot alter clientside validation error messages for fields added with the field UI module

texts:
I am adding some custom fields to a registration page using the field UI module. I'm also using the clientside validation module to display error messages on required fields. I am able to change the error messages for the default fields I have not added using the field UI, but not for the fields added with the field UI. I have tried many different ways of targeting the fields to no avail. I'm using Drupal 7.

I can see the custom rule is actually being set when I kpr($js_rules):

$js_rules['field_first_name']['messages']['required']
<span data-thmr='thmr_13' class='devel-themer-wrapper'>Please enter your first name.</span

...but the default error message still shows. I have a feeling this is due to the <input> element's name attribute being field_first_name[und][0][value], but I was even  unsuccessful in targeting this rule using that string in the _clientside_validation_set_required() function.

The difference between the default fields and my custom fileds are the custom fields values are very heavily nested within multiple arrays.

However, I'm unsuccessful in changing the input element's name attribute using any of the following:

$form['field_first_name'][#name], $form['field_first_name'][#field_name], $form['field_first_name']['und'][0]['value'][#field_name], $form['field_first_name'][#name], etc.

My custom rules:

_clientside_validation_set_required(
  $element['#name'],
  $element['#title'],
  isset($element['#required']) ? $element['#required'] : FALSE,
  $js_rules,
  t('Please enter your company email.')
);

Which works for the drupal default email field. However, this (or any of the many ways I've tried referencing the element's name) does not change the error message for my custom "first name" field:

_clientside_validation_set_required(
  $element['#field_name'],
  $element['#title'],
  isset($element['#required']) ? $element['#required'] : FALSE,
  $js_rules,
  t('Please enter your first name.')
);

Update

It turns out it IS the name attribute. When I hard code the name as field_first_name using theme_textfield(), my custom error message shows up. The problem with this is it prevents the proper values from being written to the database. Is there a way to escape the brackets in field_first_name[und][0][value] in order to use that as the first argument of _clientside_validation_set_required()?


texts: How to restrict access to page by URL depending on which page you came from

texts: I have page which implements by hook_menu and i want to permit access for this page if user come from certain form but not from just url string. How can i solve it? Thanks.


texts:
/**
 * Gets the nodequeue id by nodequeue name
 */
function my_module_get_nodequeue_id_by_name($name) {
  $data = db_query('SELECT qid FROM {nodequeue_queue} WHERE title = :title', array(':title' => $name))->fetchField();
  return $data->qid;
}

The above code produced this kind of notice:

Notice: Trying to get property of non-object in my_module_get_nodequeue_id_by_name() (line 30 of my_module/my_module.module).


texts: Startup Growth Lite - How To Set Width For Content Type

texts:
I'm using the theme Startup Growth Lite for which we've created a content type but I can't find how/where to set it's default width. We want it to be the same width as the 'Basic Page' but for some some reason our content type is always much narrower as if it's expecting left & right sidebar content (I've checked the blocks and there are none assigned).

Pulling my hair out on this one!

Thanks


texts: DDEV php/twig error "Unknown "link_attributes" filter."

texts:
So I'm trying to setup a local environment with ddev for the first time. I got it running, cloned my live files with git and imported my DB.
Site ain't working and got this in the log : "PHP message: Uncaught PHP Exception Twig\Error\SyntaxError: "Unknown "link_attributes" filter." at /var/www/html/web/themes/customs/myTheme/templates/menu--main.html.twig
Any pointer how to fix that ? I did :

ddev exec drush en link_attributes
-> [notice] Already enabled: link_attributes

This site with the same file/db is working on 2 VPS. What's going on ?


texts: Is there a way to set up a default layout for a scholar site in Open Scholar?

texts: I would like new scholar sites to have a specific widget found in the Open Scholar layout editor set in a certain region. Is it possible to set up/change the default template for the layout of scholar sites?


texts: Use swipe to switch blocks for mobile screen

texts:
In the mobile version of my site I would like to use swipe to cycle through different blocks.
E.g. a certain block (view) is displayed and swiping the screen would show the next one in the same region. Is it possible to achieve this? Thanks!


texts:
I have a views with to page displays with following paths:

/question/%/popular (page, title - Popular)
/question/%/new (page_1, title - New)

The views has a contextual filter (argument) tid. I set the first page to be default tab (with parent menu item as Normal menu item in main menu), and the second one - a tab.

I expect at url /question/all to see a views display "page", with argument value "all", active Popular tab (with url /question/all) and also New tab (with url /question/all/new).

But I've got an error

Notice: Undefined index: localized_options in menu_navigation_links() (line 1861 of /var/www/notlookatme/data/www/qa.winfaq.info/includes/menu.inc).

And an item in main menu with url /question/%25

How can I fix it?


texts: Updating settings.php breaks website hosted from subfolder

texts:
This is somewhat linked to this question.  I have 2 Drupal 7 sites hosted in subfolders, one of which is intended to be a production site (public_html/site1) and the other is the testing site (public_html/site1-test).

The main url (i.e., site1.com) should be shown when accessing the production site.  When I go to my main url, it shows correctly.  However, all links and content are shown via the subfolder (e.g., site1.com/site1/content/... rather than site1/content).

To facilitate the change, I updated the $base_url variable in the settings.php file to serve the base URL (i.e., site1.com) and that completely breaks the site.  The theme stops showing, logins don't work, etc.

Is there a way around this problem?  The main site should mask off the subfolder in the url, however I don't think I can do that without updating the $base_url


texts: Redirect a form just if the form is loaded in specific page(url)

texts:
I've implemented a menu using hook_menu(),the page callback function checks if user is login or not, if user is logged in a form for creating a content of type 'request' is loaded if not using drupal_get_form, user login block is loaded.

Now what I'm looking for is when user signed-in, he/she returned back to this page so now he can fill the form.

I don't want all user login event redirected to this page, so now my question is :

  How to redirect a form just if the form is loaded in specific page(url)?


texts: programmatically add body classes with template preprocessing

texts:
Is there a way to add body classes programmatically through template preprocessing without the use of a Javascript or a drupal module?

If so how would one do that? p.s. Using omega theme.

E.g.: I need to add a class to the body to change a particular background color.


texts: Can Salesforce Suite handle many-to-many relationships with SF junction objects?

texts:
My salesforce implementation has a bunch of objects with many-to-many relationships, just as Drupal's node references are many-to-many. But in Salesforce I need to create junction objects to hold these relationships. I am not sure how to use Drupal's SalesforceSuite to traverse the junction objects in order to create the appropriate node/entity references.

Do I need to create a custom module to handle this?


texts: Migrating disqus comments from non drupal site to drupal 7 site

texts: I have installed an set up Disqus (add shortname and public key). How can i show/migrate my old comments to my new drupal site.


texts: How can I limit the password reset attempts?

texts: I have Google Recaptcha, but some users try to recovery password too often. I didn't find any solution for this problem. I want to make 5 attempts limit for this.


texts: How do I override LoginTobbogan so that it redirects to Front Page on 403?

texts:
We have a Commerce Kickstart 2 site using LoginToboggan.

What we want is this: if an anonymous visitor goes directly to a node which is unpublished we want them to be redirected to the front page.

We do NOT want them to get a 403 (Access Denied) or to see a login form ... which seem to be the only two options available.

I've tried using Rules, but unfortunately Logintoboggan seems to take precedence over Rules.

Is there a way to override Logintoboggan's 403 behaviour?

OR is there another login module we can use which allows for login by either user name OR e-mail address that doesn't hijack 403? (That's basically the only reason we're using LT--people have gotten used to using e-mail addy to login.)


texts: In testing, how do I get an attribute using XPath?

texts:
In Drupal BrowserTestBase, I am trying to access an attribute value using XPath:
$query = $this->xpath('//a[text() = "View"]/@data-drupal-link-system-path');

I can't figure out any way to get the actual value.
$path = $query[0]->value;

Results in error message:
Undefined property: Behat\Mink\Element\NodeElement::$value
$path = $query[0]->getValue();

Results in error message:
Error: Call to undefined method DOMAttr::hasAttribute()
$path = $query[0]->getAttribute('data-drupal-link-system-path');

Results in error message:
Error: Call to undefined method DOMAttr::hasAttribute()
The following works, but isn't the XPath I want to use:
$query = $this->xpath('//a[text() = "View"]');
$path = $query[0]->getAttribute('data-drupal-link-system-path');

Is there any way to get at the value of an attribute from an XPath attribute query?


texts: Redirect from node page after form submission?

texts: When editing some fields, after I click the save button, I want the page to redirect to a particular page. Is there any module for this requirement?


texts: How do I restrict GraphQL access with Basic Auth?

texts:
According to this Gitbook (near the bottom), its possible to require GraphQL query authentication with Drupal Core's Basic Auth module. This allows GraphQL to authenticate against a user stored in the Drupal DB.
https://drupal-graphql.gitbook.io/graphql/authentication/authentication
I created an event subscriber that adds the Basic Auth option to the route like this:
use Drupal\Core\Routing\RouteSubscriberBase;
use Symfony\Component\Routing\RouteCollection;

class RouteSubscriber extends RouteSubscriberBase {

  /**
   * {@inheritdoc}
   */
  protected function alterRoutes(RouteCollection $collection) {
    if ($route = $collection->get('graphql.query.default:default')) {
      $route->setOptions(['_auth' => ['basic_auth']]);
    }
  }
}

However, when I make a curl request without an Authorization header it still goes through:
curl -X POST -H "Content-Type: application/json"   --data '{"query":"{fileById(id: \"33\") {changed}}","variables":null,"operationName":null}' http://MYLOCALHOST/graphql

Response:
{"data":{"fileById":{"changed":1572374455}}}

I did enable my custom module with the RouteSubscriber information above and also the Basic Auth module. When I visit the /graphql Drupal path in a browser, access is denied but when I make the CURL request it goes through. I was hoping to restrict CURL access as well.
Here is the Drupal 8 documentation on Basic Auth:
https://www.drupal.org/docs/8/core/modules/basic_auth/overview
I am using v3 of the Drupal 8 GraphQL module.


texts: How to dynamically pass contextual filter to a block view without changing view settings

texts:
I have a content type called artists. In various locations I want to feature one of the artists. I have a view block that has a contextual filter for the node id.

I want to display this this block on various locations of the website. I want site admins to be able to change the featured artist ( node id ) but I don't want them to have access to the views interface ) how can I pass the the node id via the blocks interface or is there some other way that I can make a mini admin screen that will let site admins choose the featured artist?

I don't want to use the promoted to homepage feature on the content type or any other field on the content type as the artist themselves have access to edit their content.

Any advice would be greatly appreciated.


texts: How would I have got blog and news pages to list articles/blogposts, how do I edit?

texts:
I have a 'blog' page that lists blog posts and a 'news/events' page that lists articles.

I cannot remember how they got there, if they were automatically generated. I think I had to do something at least for the articles page, but I cannot find anything about why mysite.com/news lists all the articles and how mysite.com/blog lists blog posts. I've looked through structure and content and views and don't see where this is coming from and I have no hover in the admin interface to edit the whole page (just individual posts). These pages seem not to have any titles set, either.

The main concern here is in the menu right now they are absolute links and I want to be dynamic, relative paths.. but I don't know what to put for that. I also need to make sure they properly get an 'active' state in the menu, which currently they do not!


texts: How to display the same views exposed form block twice?

texts:
I'm trying to display the same views exposed from block twice. Once in the left nav and once in content top. With multi block I can clone the block and I am able to display both. However, I would like the left nav form to have less exposed filters.

The problem is that in hook_form_alter() and hook_preprocess_views_exposed_from() there are no unique identifiers that I can check to alter the form. It runs through the hooks twice but I cannot seem to know if I am dealing with the left nav form or the content top form.

Does anyone have any insight into this?

I tried the code below which works for views 2 and was going to create my own block and render the form. But I cannot get the code to work for views 3.

$view = views_get_view('brands');
$view->set_display('page_2');
$view->init_handlers();

$form_state = array(
  'view' => $view,
  'display' => $view->display_handler->display,
  'method' => 'get',
  'rerender' => TRUE,
  'no_redirect' => TRUE,
);

$output = drupal_build_form('views_exposed_form', $form_state);
$blocks['content'] = $output;

Am I looking in the wrong direction?


texts: How to handle new nodes with draggable views?

texts:
I have been using draggableviews to allow for arbitrary sorting nodes on one of my views. My idea was to have the view show 20 items, and the draggableview show 30 items, ideally then the first 20 items are what shows up and the next 10 are the latest nodes so editors have nodes to pick from to add to the main view. Unfortunately once you save the form all 30 get a weight which means new nodes will show up on page 2 and won't be easy to add to the top 20. Did I set something wrong? Or is this how it's supposed to work?

Their docs mentioned a setting for "Behavior of new nodes" but I can't find this anywhere. I used grep on the module code and could not find this wording anywhere either so I'm guessing the docs are outdated?

I do have "New items appear bottom of the list" checked under Draggableviews: Weight if that makes any difference.

My only solution so far is to run this query every time a node gets inserted:

DELETE FROM `draggableviews_structure` WHERE `weight` > 19 AND `view_name` = 'my_draggable_view';

But this seems like a hack. There's gotta be a way to do this with the module, is there?


texts:
I have a content type with image and body fields. I am trying to edit the css so that the picture is on the left and the body/text is on the right with all the text staying in a column on the right rather than wrapping around the bottom of the picture. I attached a picture. I want what is show on the bottom. What is shown on the top is what I currently have. I don't want to use a module such as Panels or Display Suite.

Thanks for you input!


texts: print custom image field for taxonomy page (page--taxonomy.html.twig) template

texts:
How do I load an image from a taxonomy custom field into a custom location on the taxonomy page template?

It's easy to accomplish it when the image is in a node. The following code works for images, but it doesn't work for taxonomy pages.

    {{ file_url(node.field_reference_background.entity.uri.value) }}

How can I accomplish the same for taxonomy pages?


texts: Authorize.Net DPM payment method collecting credit card info after order completion

texts:
I am using the Drupal 7 Commerce Authorize.Net SIM/DPM Payment Methods module. It requires a direct post to Authorize.net from the Payment section of the checkout process. My problem is on the "Review Order" page of the checkout process. When a user selects the Authorize.net DPM credit card payment option, then clicks the submit button and advances from the "Review Order" page to the "Payment" page, the shopping cart is emptied before the user enters their credit card information. Once they submit their credit card information, a receipt is emailed to the user with no products listed.

It seems like Drupal considers the submitting of the form on the "Review Order" page to be the completion of the Checkout process, and therefore empties the shopping cart. How can I get the Drupal checkout process to work properly with the Authorize.Net DPM payment method?


texts: How do I change icons in the "Mobile sliding menu" module?

texts:
I want to change the menu-item icons for the Mobile sliding menu module. I have set up the icomoon library and changed the CSS file according to the documentation. I have added custom icon classes to the menu items (which works as long as they are not as block in a mmenu). The mmenu always overwrites this with its own markup.

I have found some occurrences of menu icon assignments in the source code, but I don't want to hack modules.

mmenu.api.php describes some hooks.

/**
* Allows modules to add more mmenu icon classes.
*/
function hook_mmenu_icon() {
  $icons = array(
    'path' => array(
      'home' => 'icon-home',
      'about' => 'icon-office',
      'contact' => 'icon-envelope',
    ),
    'block' => array(
      array(
        'module' => 'system',
        'delta' => 'main-menu',
        'icon_class' => 'icon-enter',
      ),
    ),
  );
  return $icons;
}

/**
 * Allows modules to alter mmenu icon class settings.
 */
function hook_mmenu_icon_alter(&$icons) {
  $icons['path']['home'] = 'icon-home1';
}

I have no clue how to use these. I have tried to put them in my template.php like this.

function mythemename_mmenu_icon() {...}

It's not working. Apart from that, this wouldn't be a user-friendly solution. Ideally it would support icon-api. So any help is highly appreciated.


texts: During which bootstrap phase hook_exit & hook_boot will be invoked?

texts:
Project Documentation says.. Both are invoked even for cached page views. hook_boot says

  This hook is run at the beginning of the page request. It is typically
  used to set up global parameters that are needed later in the request.

  Only use this hook if your code must run even for cached page views.
  This hook is called before the theme, modules, or most include files
  are loaded into memory. It happens while Drupal is still in bootstrap
  mode.

hook_exit says...

  Perform cleanup tasks.

  This hook is run at the end of most regular page requests. It is often
  used for page logging and specialized cleanup. This hook MUST NOT
  print anything because by the time it runs the response is already
  sent to the browser.

  Only use this hook if your code must run even for cached page views.
  If you have code which must run once on all non-cached pages, use
  hook_init() instead. That is the usual case. If you implement this
  hook and see an error like 'Call to undefined function', it is likely
  that you are depending on the presence of a module which has not been
  loaded yet. It is not loaded because Drupal is still in bootstrap
  mode.

Interested to know during which bootstrap phases hook_boot & hook_exit getting invoked so that it will be helpful in cases where above hooks can be used....


texts:
I am trying to generate html output of whole page and then pass it to response array.I am doing something like this:

  $page = array(
  '#theme' => 'html',
  '#page_object' => new HtmlPage(render($content)),
   );

$content is a render array and new HtmlPage creates a HtmlPage object from an existing page. I am passing render($page) to the response object, but I am getting error this error:

  LogicException: A stray drupal_render() invocation with $is_root_call = TRUE is causing bubbling of attached assets to break. in Drupal\Core\Render\Renderer->doRender() (line 377 of core\lib\Drupal\Core\Render\Renderer.php).

What should I do to make this correct? Thanks


texts:
I have a .htaccess file in the files directory and the .htaccess file permission is 444.

On running security review , I get the following response

"The .htaccess file exists but does not contain the correct content. It is possible
it's been maliciously altered."

Is this a security breach?

I am trying to fix out the security check but facing the above issue.
I have even tried removing the .htaccess file and updated
with that of .htaccess file(sites/default/files/.htaccess) from fresh drupal install.

Still It shows the same error.
I would like to figure out the following issue.

I would also like to know the permissions which are assigned to .htaccess file and what should be the content inside it.?


texts: How to add a image in your drupal.org bio?

texts:
Some www.drupal.org profiles like https://www.drupal.org/u/artofeclipse have a image in the Bio section like this:

So, I trying to achieve the same in my profile (https://www.drupal.org/u/adriancid) but with another image. The problem is that the site always says this:

But if you go to see the image it exists in drupal.org, but the site always says Only local images are allowed.

How can I add a picture in my drupal.org profile?


texts:
I am new to rather new to Drupal (coming from Django/Python), and was wondering if there was anyway I could use a token in the minimum field of my registration.

What I basically have is a registration from, which is then a field in one of my content types. In this content type I also have a field called minimum deposit. So I wondering if I could somehow link the value in the minimum deposit field to the minimum in my registration? Like for the minimum value have: [node:minimum_deposit].


texts:
I have path aliasing, which gets the path from the title of the News article, working fine.

However, in the Google index, I noticed that the canonical URL for nodes is working as well. So, Google is indexing the node pages twice: with the canonical URL and with the path alias.

I want to disable the canonical URL for nodes, so I tried installing the node_page_disable module.  It installed fine, and I enabled it with Drupal 6.

In http://www.example.com/admin/settings/site-information, there is a  Default front page textbox, which by default contains node. If I remove node from the textbox, and save the settings, Drupal complains with:

  Default front page field is required.

The module I installed adds a Retain /node as an active url? checkbox.
If I click on that, I am required to remove node from the Default front page textbox.

How can I do it, since removing node causes Drupal to complain about a required value not given?


texts:
I was trying to modify the search results page using a preprocess function:

function arras_preprocess_search_result(&$variables) {

    $type = $variables['result']['node']->type;
    $variables['search_results'] = '';
    $nodeTypes = node_type_get_types();
    $resultTypes = array();

      $resultTypes[$type][] = $variables['result'];

    foreach ($resultTypes as $resultType => $resultTypeResults)
    {
        echo $resultType;
        $value = "";
        // loop through entries
        foreach ($resultTypeResults as $result)
        {
            $value .= theme('search_result', $result,$resultType);
        }

        // add fieldset
        $variables['search_results'] .= theme('fieldset',
            array(
                '#title' => $nodeTypes[$resultType]->name,
                '#collapsible' => TRUE,
                '#collapsed' => FALSE,
                '#value' => $value,
            )
        );

    };

}

but I get this error:

( ! ) Fatal error: Unsupported operand types in L:\wamp\www\drupal\includes\theme.inc on line 830

i.e on the line

        $value .= theme('search_result', $result, 'cameras');

What is wrong?


texts: How to make a multi field reference multiple content types?

texts:
I'm trying to implement a Project Member relationship but I don't know how to do that. I have as a content types: Project, Member and Position as the attached UML diagram shows. My doubts are about the team field in Project.

I need to relate team members with a certain positon (which can be different from default position) to the Project. One way would be to create another content type called ProjectMember, but I'm trying to avoid that.

What would be the fastest vs the most elegant way to implement that?

Is Field Collection module a suitable way to go?


texts: Getting granular data in template from an entity referenced in the entity_reference field, in a way that would respect Drupal's caching

texts:
I have a case where in my node's template I need an image style URL from the Media entity referenced by this node. I need a raw value of this URL to use it like that: <div style="background-image: url('[my-image-url-goes-here]')">

I know multiple ways of achieving this, like using twig_tweak module (but I think it would be an overkill) or preprocessing hook (feels ugly), or creating custom twig filters for extracting data that I need. Actually I could even do something like that: content.field_media_image|render|striptags|spaceless to isolate URL returned by rendered Media display but that is especially ridiculous and would work with only single value. After few hours of research I started considering creating a custom formatter for entity_reference fields, that would just output raw data, like for example:

[
  '#url' => $my_image_style_url,
]

That looks nice, I could then just set it as a formatter of my entity_reference field referencing my Media image entity and I could use this #url in my node as I wish. But it seems to have one weakness. I cannot set cache tags on that, because it's not renderable - it would be rendered in parent template that may not have cache tags that would ensure that it would be cleared if one of values sent to it that way, would change for reasons unrelated to this node. So it doesn't feel like a right solution in the end.

Now I'm starting to realize that I cannot reliably do what I wanted, because by isolating one information from a field like that, I'm automatically ignoring its cache tags. Is making ugly preprocessing hooks the only option I have for that? Am I missing something?


texts:
I' am trying to make a custom module to set an active trail path to a menu. I created a views page. The active trail must be to a node or taxonmy term. When I open the pages created by the view the active trail is not active.

I wrote the script here below but it doesn't work, can somebody please help???

function mymodule_views_default_views(&$view, &$display_id, &$args){
  if( $view->name = 'productdetail';)
    {menu_tree_set_path('menu-categorie', 'node/39');
 }
}


texts: How to get the user ID from the last profile page?

texts: So, I have a user's profile page where there is a Message button. When I click the message button it should redirect me to a custom page with a form in it. How can I get the user ID from the profile page I visited in order to know where to send the message?


texts:
So I'm building a community website for a local photography group and I'm trying to set up a "well equiped" group photo grallery that registered members can upload photos to. The gallery should include basic gallery features such as a view counter, to record how many people viewed a certain image. As well as the ability to comment on the photo.

I am a complete Drupal noob, this is my first Drupal project migrating over from WordPress because I believe Drupal has better flexibility and features as a CMS. I've created a view for our gallery, and am using the colorbox module for a stylish and professional presentation of the photos when clicked. I am also using the statistic module.

The road block I am at is that using the statistics module in partnership with the colorbox module image views are not being recorded. I believe this is because when you click on the image you don't actually navigate to the node, instead the image is pulled from the node and displayed in a colorbox modal. So, no matter the web traffic to the gallery and the photos being clicked or not, it always displays 0 views.

Is there a way to make it so when a image is clicked in the gallery and colorbox presents the image to the viewer it counts as a view?

The in-progress site I'm working on is beta.semiphoto.org The gallery can be found here. Please don't judge, I haven't addressed themeing and am still learning drupal. :-)


texts: How to show the product "add to cart" button on a product kit?

texts:
I would like to add a "add to cart" button on a product kit, for each product in the product kit. How may I achieve that? I have been searching for a while now. Ubercart 3.

This would be similar to iTunes when viewing an album, the user may buy a single song of the album. Currently with product kit, the user has to click the product link to get to the song then be able to buy it.


texts: How to disable i18n language dropdown in node form?

texts:
I'ld like to prevent editors from changing the language of a node. Role check works. But I how to disable the language field? Why doesn't it work like any other form field? How is this field placed there? Where can I alter it? This doesn't work:

function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
    global $user;
    $editor = in_array('editor', $user->roles) ? TRUE : FALSE;
    $node_edit = isset($form['#node_edit_form']) && $form['#node_edit_form'] ? TRUE : FALSE;

    if ($node_edit && $editor) {
        $form['language']['#disabled'] = TRUE;
        $form['language']['#access'] = FALSE;
    }
}


texts:
I am creating a form to collect data for a specific content type which has a field collection in it.

So basically I am creating nodes manually through form API.
What I need to do is to add a field collection table to my form which corresponds to the field collection I declared in the node type.

I have got how the table is rendered in the original add content form, which is like this:

[field_student_grades] => Array
    (
        [#type] => container
        [#attributes] => Array
            (
                [class] => Array
                    (
                        [0] => field-type-field-collection
                        [1] => field-name-field-student-grades
                        [2] => field-widget-field-collection-table
                    )

            )

        [#weight] => 5
        [#tree] => 1
        [#language] => und
        [und] => Array
            (
                [0] => Array
                    (
                        [#entity_type] => field_collection_item
                        [#entity] => FieldCollectionItemEntity Object
                            (
                                [fieldInfo:protected] =>
                                [hostEntity:protected] => stdClass Object
                                    (
                                        [uid] => 1

But I do not know how to deal with the [und] and [hostEntity:protected] and stdClass Object in code.


texts: Images in content type: reusing and limit

texts:
In a content type template, I allow images. The only widget that appears for that field, is a File Upload widget. What if I want to reuse the image that has already been uploaded?

Also, how do I raise the limit of uploaded images from 10 to more?

Thanks
Artur


texts: Can I call menu_rebuild() only for one module or specific hook_menu?

texts:
Is there a way to call menu_rebuild so it will only update items
in selected module and / or hook_menu ?

I need it to update links ( if they are already existing ) and add new
( if they are now ).

Don't want the menu_rebuild to clear the menu_router.


texts: How can I create a link, within a form, for a user to download a file?

texts:
I'm new to Drupal.

I have a custom form, within a custom module, using Drupal 8.

I would like to provide a simple link (or button, whatever the correct terminology would be), that when a user clicks will download a file that I specify.

How do I create the clickable part in the first place? Is there something like '#type' => 'download', similar to the way '#type' => 'managed_file' is used for uploads? Or is using the 'type' => '#submit' route the best way to go?
Where do I place the file, and how do I make the clickable part grab that file?

The file will be a .xlsx in my case, but I've seen similar questions asking how to do this for a .pdf file, .doc file, etc., but none of them have a concrete answer.

I don't care what the user does with the file once they've downloaded it. It doesn't need to be protected or "read-only" or anything fancy. I just want someone to be able to download the file and save it to their computer.

Code examples would be extremely helpful. So far my best guess is something like this:

// Taxonomy Download
    $form['taxonomy_download'] = [
      '#type' => 'submit',
      '#value' => t('Download Default Taxonomy Terms'),
      '#submit' => array('::downloadFile'),
    ];

(...)

public function downloadFile() {
     //Get file from /file/path/
     //return $file
}


texts: If Drupal Commerce Cart is not Empty, add a class to body

texts:
I'd like to add a class to body if the current user's cart is not empty.

I'd like to take the preprocess approach and not using rules.

so far using commerce_cart_order_load function I came up with this in template.php:

function THEME_preprocess_html(&$vars) {
    global $user;
    $order = commerce_cart_order_load($user->uid);

    if ($order != 0) {
        $vars['classes_array'][] = 'cart-loaded';
    }
}

but unfortunately it throws an unknown error.


texts:
I am displaying a Slideshow on each node. I want to display image of current node on start of slideshow. Then other images related to that node.

I added a taxonomy field in content type. I get the top 10 nodes related to tags selected in content. I displayed the views using views_embed_view in node.tpl.php

How to include current node image with in the views?


texts:
I have an Article node type where Expert node's can be referenced via autocompletion (as in: X Expert was consulted for this article)

I created a views for internal use, listing all the experts with exposed filters, easing up the journalist workflow to find suitable experts to contact for certain situations.

I'd like to list under each expert the Article nodes that they were referenced in, but as to how, I'm baffled, I attempted to create a relation with:

Content: Expert (field_expert_nid) - reverse
Relate each Content referencing the node through Expert.

But that's about how far I've gotten, any help or suggestions how to tackle this greatly appreciated :)


texts: Module getting "$entity" argument error with hook_entity_presave()

texts:
I am trying to create a module in Drupal 8 (8.9.11) and this module uses the function hook_entity_presave in order to update a node / entity programmatically. I've tried the answers from hook_entity_presave() doesn't work, I was able to add those in my code.
sno.routing.yml
sno.content:
  path: /node/add/issuances
  defaults:
    _controller: Drupal\sno\Controller\SnoController::sno_entity_presave
  requirements:
    _permission: 'access content'

src/Controller/SnoController.php
namespace Drupal\sno\Controller;
use Drupal\Core\Entity\EntityInterface;
use Drupal\node\NodeInterface;
class SnoController {

  public function sno_entity_presave(\Drupal\Core\Entity\EntityInterface $entity) {
    if ($entity->getEntityType()->id() == 'issuances') {
      $entity->set('field_s', ', s. ');
    }
  }

}

When I got into adding a content of content type issuance (/node/add/issuances), I am getting the following error.

The website encountered an unexpected error. Please try again later.
RuntimeException: Controller "Drupal\sno\Controller\SnoController::sno_entity_presave()" requires that you provide a value for the "$entity" argument. Either the argument is nullable and no null value has been provided, no default value has been provided or because there is a non optional argument after this one. in Symfony\Component\HttpKernel\Controller\ArgumentResolver->getArguments() (line 78 of /var/www/senate-library/vendor/symfony/http-kernel/Controller/ArgumentResolver.php).


texts: View contextual filter only applies to first filter AND/OR group

texts:
I have a view that returns two different content types in its results. Each content type needs different filters, so I group them using OR and AND. See below:

This view represents a category page and filters the results using a contextual filter. Both content types share the same category field. However, the contextual filter (a taxonomy term based on the URL) only applies to the first group of filters before the "OR". This shows up in the query it generates:

SELECT DISTINCT node.nid AS nid, node.created AS node_created, node.title AS node_title, node.sticky AS node_sticky, node.nid AS node_nid, 'node' AS field_data_field_image_node_entity_type, 'node' AS field_data_field_duration_node_entity_type, 'node' AS field_data_field_slug_node_entity_type, 'node' AS field_data_field_stickybit_expiretime_node_entity_type, 'node' AS field_data_field_ribbon_color_node_entity_type, 'node' AS field_data_field_ribbon_text_node_entity_type, 'node' AS field_data_field_blog_thumbnail_node_entity_type
FROM
{node} node
LEFT JOIN {field_data_field_segment} field_data_field_segment ON node.nid = field_data_field_segment.entity_id AND (field_data_field_segment.entity_type = 'node' AND field_data_field_segment.deleted = '0')
LEFT JOIN {field_data_field_submitted} field_data_field_submitted ON node.nid = field_data_field_submitted.entity_id AND (field_data_field_submitted.entity_type = 'node' AND field_data_field_submitted.deleted = '0')
WHERE (( (node.type IN  ('story')) AND (node.status = '1')
        AND (field_data_field_segment.field_segment_value IS NULL )
        AND (field_data_field_submitted.field_submitted_value NOT IN  ('2'))
        AND (node.nid IN
          (SELECT tn.nid AS nid FROM {taxonomy_index} tn
          LEFT OUTER JOIN {taxonomy_term_hierarchy} th ON th.tid = tn.tid
          LEFT OUTER JOIN {taxonomy_term_hierarchy} th1 ON th.parent = th1.tid
          LEFT OUTER JOIN {taxonomy_term_hierarchy} th2 ON th1.parent = th2.tid
          LEFT OUTER JOIN {taxonomy_term_hierarchy} th3 ON th2.parent = th3.tid
          LEFT OUTER JOIN {taxonomy_term_hierarchy} th4 ON th3.parent = th4.tid
          LEFT OUTER JOIN {taxonomy_term_hierarchy} th5 ON th4.parent = th5.tid
          LEFT OUTER JOIN {taxonomy_term_hierarchy} th6 ON th5.parent = th6.tid
          LEFT OUTER JOIN {taxonomy_term_hierarchy} th7 ON th6.parent = th7.tid
          LEFT OUTER JOIN {taxonomy_term_hierarchy} th8 ON th7.parent = th8.tid
          LEFT OUTER JOIN {taxonomy_term_hierarchy} th9 ON th8.parent = th9.tid
          LEFT OUTER JOIN {taxonomy_term_hierarchy} th10 ON th9.parent = th10.tid
          WHERE ( (tn.tid = '205') OR (th1.tid = '205') OR (th2.tid = '205')
            OR (th3.tid = '205') OR (th4.tid = '205') OR (th5.tid = '205')
            OR (th6.tid = '205') OR (th7.tid = '205') OR (th8.tid = '205')
            OR (th9.tid = '205') OR (th10.tid = '205') )
        ))
      )
      OR ( (node.type IN  ('blog')) AND (node.status = '1') ))
ORDER BY node_sticky DESC, node_created DESC, node_nid DESC
LIMIT 12 OFFSET 0

You can see that the contextual filter is applied only to the first group, not both. Is there any way to get the contextual filter to apply to both?

Drupal 7.8
Views 7.x-3.0-rc1
Views UI 7.x-3.0-rc1


texts: How to get a themed form via Ajax in D7?

texts:
I'm trying to get a D7 form into a Bootstrap modal dialog.  I had this working on D6, through a semi-straightforward process:

The jQuery code that's building and showing the modal does an $.ajax call to a url on my site to get the form contents -- something like /get_my_form/123.  This request is picked up by a Drupal menu entry that makes a call to drupal_get_form() with the appropriate form function and various parameters.  The usual Drupal form-creation thing.
There's a theme function for the form that does a couple of things and then sends the results back to jQuery by doing:

print json_encode($the_form_contents);
exit;
The ajax handler, which is expecting a json object, gets the results and sticks them into the body of the modal, and puts it up.

In moving this code to D7, I've been following the same route.  It almost works, but the ajax call continually fails because the response string from the server includes the HTML from a page template, up to the point where the "exit" in the theming function kills the PHP request.  That HTML is obviously not a expected part of the JSON object, but I can't figure out how to get rid of it.  I've tried using drupal_json_encode in place of json_encode, and replacing the "print" statement with a call to drupal_json_output, but the page template stuff keeps coming.  I'm definitely not adding it to what's produced in the theme function, so there must be some other part of Drupal that's squirting it out in ajax's direction.

Any ideas?  This has REALLY been driving me crazy this afternoon.  Thanks!


texts:
I've started learning Drupal (I'm starting with Drupal 7) and the best way to do that seemed to me to be in creating a custom theme from scratch.

I'm trying to create a menu in which the login form is displayed if the users are not logged in and the user menu if they are logged in. How do I go about doing this in proper Drupal fashion?


texts: Concatenate fields in a view with comma when values may be empty

texts:
One can easily concatenate fields in views with a re-write rule.. However, I have two fields, age_range and warning, the second of which may be empty. I want to display them like this:

Ages 2+
Ages 4-10, choking hazard

If warning is empty, I don't want to show a comma. If I make a rewrite rule like this
[age_range], [warning]

Then I get a result like this:

Ages 2+,
Ages 4-10, choking hazard

How can I avoid a trailing comma?


texts: Search API - how to have blank page on initial page load

texts: I am using Search API with Apachesolr module. I have created a view on the index, but for some reason, before I do any search (or if I search for a blank screen) I get full results. How do I make the initial search screen blank? I tried setting the No Results setting in the view, but that only sets the text when you entered a bad search entry.


texts: How do I set the private file system path's permissions?

texts: There is an option in Configuration > File system which let you  define a path for private files. After setting a path in this field, the access for all users is restricted (including admin). I need to give the permission of accessing this directory and its files to some users. How?


texts: How to get the count on the select list in views?

texts:
For example, I have a content type with field. The field is select list. The select list has four default values as well as it is required.

I want the output of a view as:

Provincial (2)
Federal (6)
Institutional (3)
...
Value (#)

where # is the number of nodes with this value

How can I accomplish this?


texts:
I made it mandatory for anonymous users to leave contact information while commenting along with comment notify so as to improve the user engagement. There are two problems that crept in because of this:

A homepage field also got added with the email field. I want to remove only the homepage field, leaving the email field in place. I could not figure out how to do this.
People comment with fake email addresses.

Can anybody tell me a workaround for these problems?


texts:
In entity node, I want to check if 'abc' field exists or not. If exists, I will get its value by $value->get('abc').

But the content type where this field doesn't exists, gives error:

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

How to check if field exists in an entity?


texts:
I have a local site I am testing. I have PhPMailer installed which works fine to send plain text email with the Sender name populated properly.  However when I installed MimeMail and try to use the same rule, except using action send HTML mail, the Sender name no longer appears.  Any help would be great.
{ "rules_entityform_client_confirmation_email" : {
"LABEL" : "Entityform Client Confirmation Email",
"PLUGIN" : "rule",
"OWNER" : "rules",
"TAGS" : [ "entity_rules_entityform_submission" ],
"REQUIRES" : [ "rules", "mimemail" ],
"USES VARIABLES" : {
  "entity" : { "label" : "Entity", "type" : "entityform" },
  "continue" : { "label" : "Continue Rules", "type" : "boolean" }
},
"IF" : [
  { "user_has_role" : { "account" : [ "entity:user" ], "roles" : { "value" : { "4" : "4" } } } }
],
"DO" : [
  { "drupal_message" : { "message" : "Email to: [entity:user:mail]\r\nHi [entity:user],\r\nThanks for creating a new project\r\n" } },
  { "mimemail" : {
      "USING" : {
        "key" : [ "entity:entityform-id" ],
        "to" : [ "entity:user:mail" ],
        "from_name" : "[site:name]",
        "subject" : "New Project Created",
        "body" : "Hi [entity:user],\r\nThanks for creating a new project",
        "plaintext" : "Hi [entity:user],\r\nThanks for creating a new project",
        "language" : [ "" ]
      },
      "PROVIDE" : { "send_status" : { "send_status" : "Send status" } }
    }
  }
],
"PROVIDES VARIABLES" : [ "continue" ]
}
}


texts: Add custom submission buttons to navigate through different wizard pages

texts:
I need to navigate the user through different pages of a multistep webform. I have added additional submit button to the webform using following code.

function mymodule_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
if($form_id == 'mywebform_id') {
    $form['actions']['submit_button_step_1'] = array(
      '#type' => 'submit',
      '#value' => t('Go to Step 1'),
      '#submit' => array('custom_navigation'),
    );
    $form['actions']['submit_button_step_2'] = array(
      '#type' => 'submit',
      '#value' => t('Go to Step 2'),
      '#submit' => array('custom_navigation'),
    );
}
}

But now How could I navigate the user to the pages based on user clicks on which button?

I found this in community website. But not able to understand where should I put this code in my custom module.

How to programmatically skip pages in wizard forms


texts: How do you remove or hide the 'Permalink' in comments?

texts:
Does anyone know how to remove or hide the 'permalink' in the comments section (i.e on posted comments).Here is a copy of one of my comments -

" Permalink Submitted by Jade K on Fri, 11/11/2011 - 14:28"

Additionally, does anyone know how to rename or remove 'submitted by' from comments?


texts:
I'm very new to drupal, I've got a basic understanding of PHP and how it should be written but I think I'm still struggling with the concept of where to add code, at what point I need to jump in to edit things and make my own style do its thing

All I want to do is change my default user menu from:

User Menu

 - My Account
 - Log out

To

Logged in as:
[username]

My Account

Log Out (where both buttons have mybtn class applied to them rather than in a ul)

I've seen I can remove the ul function from the list that is outputted with the following code

function MYTHEME_menu_tree__user_menu(&$variables) {
 return $variables['tree'];
}

And I've also tried to add the username to the content of the username with this block

function MYTHEME_preprocess_block(&$vars){

  global $user;
  $block =& $vars['block'];

  if ($block->module == 'system' && $block->delta == 'user-menu') {
    if (user_is_logged_in()) {
      $block->content .= check_plain($user->name);
    }
  }

}

(this code was modified from someone explaining how to change the subject of the block to the username)

I'd really appreciate any help with where to go next

Kind regards


texts: Show 404 on page for node path url instead of redirecting to it's alias

texts: I'm currently using the Redirect module in Drupal 8 along with Pathauto to create aliases on all url's.  So for example /node/23 would be /article/some-text-here.  When a user types in /node/23 in the url it automatically redirects them to the alias url.  I want to show a 404 whenever the user uses the node path url instead of redirecting that way they don't ever have a chance to find something they shouldn't by traversing through my site with that pattern.


texts: Views Data Export: Multiple Columns with Unique Rows (D7)

texts:
I'm using Drupal 7

I have a view displaying users that are referenced by another entity that has a date field, like this:

John Doe      5/6/12
John Doe      5/8/12
John Doe      5/16/12
Mary Jane     5/5/12
Mary Jane     5/7/12

So, behind the scenes, there's a content type of "Reservation" with a date field and a user reference field.  I'm pulling in all of these reservations and displaying the user name alongside the dates of their reservations.

When I use the views_data_export module, I'm able to export this data as an xls file, which allows this data to open nicely in MS Excel.

The solution I'm looking for is to be able to group this data by user, to create unique rows with multiple columns, like this:

John Doe      5/6/12   5/8/12   5/16/12
Mary Jane     5/5/12   5/7/12

So, if a user has 20 pieces of data, then 20 columns will display next to that user with each column displaying each piece of data.


texts: What happens to fields that don't have corresponding database columns?

texts:
I'm doing some work around the Salesforce Suite in Drupal 7. It's a suite of modules that load the Salesforce REST API, map objects and fields between Drupal and Salesforce, push data from Drupal to WordPress, pull data down from Salesforce, manage queues for the data, etc.

I'm trying to understand how Drupal handles a flag called salesforce_pull (from the salesforce_pull module within the Salesforce Suite). This code runs when Drupal knows about a new Salesforce row (presumably on cron or on an Ajax call):

  try {
  // Create entity from mapping object and field maps.
  $entity_info = entity_get_info($sf_mapping->drupal_entity_type);

  // Define values to pass to entity_create().
  $values = array();
  if (isset($entity_info['entity keys']['bundle']) &&
    !empty($entity_info['entity keys']['bundle'])
  ) {
    $values[$entity_info['entity keys']['bundle']] = $sf_mapping->drupal_bundle;

    // Because creating term via entities actually needs vid and won't be
    // fixed in Entity API (https://www.drupal.org/node/1409256).
    if (isset($values['vocabulary_machine_name'])) {
      $vocabulary = taxonomy_vocabulary_machine_name_load($values['vocabulary_machine_name']);
      $values['vid'] = $vocabulary->vid;
    }
  }
  else {
    // Not all entities will have bundle defined under entity keys,
    // e.g. the User entity.
    $values[$sf_mapping->drupal_bundle] = $sf_mapping->drupal_bundle;
  }

  // See note above about flag.
  $values['salesforce_pull'] = TRUE;

  // Create entity.
  $entity = entity_create($sf_mapping->drupal_entity_type, $values);

  // Flag this entity as having been processed. This does not persist,
  // but is used by salesforce_push to avoid duplicate processing.
  $entity->salesforce_pull = TRUE;
  $wrapper = entity_metadata_wrapper($sf_mapping->drupal_entity_type, $entity);

  salesforce_pull_map_fields($sf_mapping->field_mappings, $wrapper, $sf_object);

A comment there says "// See note above about flag." but the only thing I found was the same flag for other events (update, delete of Salesforce rows). It looks like this (which is fine, but I still am unclear how it works/how to use it):

// Flag this entity as having been processed. This does not persist,
// but is used by salesforce_push to avoid duplicate processing.
$entity->salesforce_pull = TRUE;

That part about salesforce_push using it is what I'd like to understand.

I have not found a database field for salesforce_pull (on any of the entities). I've also done a database search (through phpMyAdmin so it could search the whole thing) for TRUE values and the salesforce_pull phrase with nothing that seems to be related to this, including in the cache tables.

It seems like the Fields API (at least in D7) has a way to save data that doesn't have a corresponding field in the database. If this is the case, where does the field get saved? How long does it stay before it gets reset? How does it get reset? How do I access it?

I'd like to be able to use this convention, but I don't understand how it works and haven't been able to find any documentation on it.


texts: How to add a custom field to a taxonomy term

texts:
I am developing a module and I would like to know how to add a field to a taxonomy term?

My section is named special and I want to add terms in this section

I have this code:

function add($form,&$form_state) {
    $form['name'] = array(
        '#type' => 'textfield',
        '#title' => t('name'),
        '#required' => TRUE,
    );

    $form['submit_button'] = array(
        '#type' => 'submit',
        '#value' => t('send'),
    );

    $form['#submit'][] = 'special_add_submit';

    return $form;
}

function special_add_submit ($form, &$form_state) {
    $instance = array(
        'field_name' => 'nombre',
        'entity_type' => 'taxonomy_term',
        // This is the vocabulary
        'bundle' => 'special',
        'label' => t('Relates to option'),
        'description' => t('This is the description'),
        'required' => true,
        'widget' => array(
        'type' => 'text_textfield',
        'settings'=> array(
            'max_width'=>80)
        ),
        );
    field_create_instance($instance);
}

How to do that?

i create a field named name when i save that field i want to add the value to taxonomy term named special


texts: How to grep Rules to search for a deprecated function?

texts:
I'm removing an obsolete custom module, but I want to make sure it isn't referenced in any rules.

Is there a way for me to search / grep for a function name within all the rules on my site?


texts: How to test the existence of a file in a webform email twig template

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

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

  Questions

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

 {% endif %}

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

I tried

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

or

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

or

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

and none of them work.

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


texts: How to trigger an event when node is saved?

texts:
I am trying to execute a piece of code when a node is saved. I am using hook_node_update, but it's never triggered when updating a node. Here is my code:

function custom_node_update(Drupal Core Entity EntityInterface $node) {
 // Logs a notice
 \Drupal::logger('custom')->notice("entity was updated");
}

What is wrong with my code?


texts:
My client is having a terrible time managing multi-lingual content in drupal 7.  I'm using the internationalization module and drupal 7's default capabilities in managing multiple languages.  Here's an example workflow my client executes, with bold statements that indicate challenges.

Client begins to add new content of content type page.  He fills out title and selects language as English.
Client clicks on menu settings, and select Provide a menu link.  Under Parent item, client selects from the drop down tree About.
Client publishes the page.
Client clicks on Translate to translate the page.
Client clicks on add translation for French to see the add content page.
Client notices all the fields except menu settings is populated.  This irritates the client.   Client expects the CMS to know that the A Propos menu link is the french equivalent for About menu link, and to have populated accordingly.  But instead, client must go through hundreds of link.

Here's another example workflow that illustrates a big problem.

Client wants to re-structure the site map.
Client goes to an ENGLISH page in the CMS, goes to menu settings, and changes the Parent item to the Home menu link.
Client presses Save.
Client goes to FRENCH version of the same page.  Client needs to repeat the process of Parent item but find Accuiel menu link.  This irritates the client because client expects the CMS to be smart enough to know Accuiel menu link is the french version of Home menu link, and when the English page was moved from About to Home, then the French page should have moved from A Propos to Accuiel.

As it stands now, the client feels like he's managing two websites individually.  Can anyone suggest a workflow that can reduce the client's workload by about half ?  Simply having drupal reflect site map changes in english into french would reduce workload by about half.


texts: Install Drush on shared hosting with SSH access?

texts:
I have SSH access on shared hosting and I followed this guide to install the composer: https://getcomposer.org/download/

php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"
php -r "if (hash_file('SHA384', 'composer-setup.php') === '669656bab3166a7aff8a7506b8cb2d1c292f042046c5a994c43155c0be6190fa0355160742ab2e1c88d40d5be660b410') { echo 'Installer verified'; } else { echo 'Installer corrupt'; unlink('composer-setup.php'); } echo PHP_EOL;"
php composer-setup.php
php -r "unlink('composer-setup.php');"

I got the composer.phar installed/downloaded into custom dir /composer/composer.phar

And it works if you run it php composer.phar.

Then I ran php composer.phar require drush/drush:7.x to install drush. And it installed in the /composer/vendor/bin.

Now, if I run php composer.phar drush I get error:

[Symfony\Component\Console\Exception\CommandNotFoundException]
  Command "drush" is not defined.

I set paths PATH=$PATH:~/composer/vendor/bin and PATH=$PATH:~/composer/

If I run just composer or drush I get The program 'composer' is currently not installed. To run 'composer' please ask your administrator to install the package 'composer'.


texts: Email not to admin, When user create an account

texts:
I want to send an email to another email, rather than admin Email, When user create an account

Can Anybody tell me how to do that . I am using drupal 7

Thanks


texts: Rabbit hole: what's the recommended setting for content that should not be directly accessible?

texts:
I have one content type, as well as several vocabularies (taxonomy) that are only shown on the site through views and therefore should not be accessible on their own. I'm using the rabbit hole module to prevent that from happening.

My question is this: from an SEO point of view, is it better to use a 301 redirect (to the front page), or a "page not found" response?

Maybe I should point out that the site isn't online yet, so it hasn't been crawled by search engines.