How to get workflow state transition history for a node? In the admin section, for any given node, I need to add a dropdown field that lets QA assign that node to a developer who had previously made changes to the node's workflow state. I am currently using the workflow module (https://www.drupal.org/project/workflow). This field needs to be populated with users who have changed the node's workflow state before. So, I'm working on a module that can do this. My question is, how do you programmatically get the workflow state transition history for a given element?

For every revision of a given node that has involved a workflow change, I would need the following information:

The state or state id (sid) that it was changed to.
The uid of the user that made the change.
The order in which the workflow state transitions were made.

I tried node_revision_list, but it does not include revisions that only change the workflow state. (Because it's not looking at the workflow_node_history table).

I can get the information I need directly from the database by running the following query, but I don't want to do any database-hacking if this functionality is already in Drupal somewhere.

SELECT sid, uid  FROM `workflow_node_history` WHERE `nid` = ? ORDER BY stamp asc

Is there a Drupal function that already does this?

The Workflow module has a lot of API calls that you can use to get the relevant information you need.

Here are all the workflow functions you can access

It seems like you might be looking specifically for the workflow_get_workflow_node_history_by_nid function

Here you supply a node ID and it will return the history results as an object where you can find the information you need.  It even joins it with the users table so you have all the relevant user information.


How to eliminate extra Drupal Logout Link Hi, there, I am working with Organic Groups on an existing drupal 7 site. For some reason, there are three log out links. I checked with User Menu, which is not even enabled in this site. How can I find out why there are three log out links?

Any ideas?
Thanks!

Try using the Devel Themer (https://drupal.org/project/devel_themer). That works kinda like a firebug/backtrace for themeing, and it should point you to where those links are coming from. Keep in mind Themer is a bit buggy, and can cause some issues, so you might want to switch it off when your done, but it should help you diagnose your problem.


Get user account content object loaded in node.tpl.php By default $account->content object is loaded only on user page.

I want to print $account->content in node.tpl.php.

In user-profile.tpl.php, I tried echo "<pre>"; print_r($account); and $account->content is fully loaded.

How would I do the the same in node.tpl.php ? I tried with user_load(1); but account->content is not built.

try this

global $user;
$account = user_load($user->uid);


How do you normally structure your Menus? I am using the Sitemap module, and in order to display the pages available on the site, I need to enable which Menus are displayed. It then lists them in sections, with a Menu title above each section.

I have 5 menus at the moment, so the sitemap generated looks very messy. What is the best way around this? How do you structure your Menus so it all looks neat in the Sitemap, but is also functional?

Also, do you  normally rename the Main and Navigation menus to Primary links and secondary links, or do you leave them as they are? Do you  hide the Menu headings from being displayed in the Sitemap?

One option you have is to leave your menus as they are and use CSS to style the page so it appears nicer.

You can do things like reduce the amount of space between menus.

Another way (this depends on your sites menu requirements - it may not fit with what you need), is to have primary links be your sitemap.
Add everything you want in your site map to the primary links, going in as many levels deep as you need.
Then don't actually display all the levels in your menu (unless you want to and have deep drop down menus).
Then have the site map just display the primary links menu.

This will give you a nicer looking site map.

In my opinion, site maps are something drupal does not do well (short of doing something more custom). I have never seen a satisfactory result (to my standards) from using the site_map module.

Another option would be to use the menu_block module, which would allow you to create a bunch of menu blocks for specific menus (and levels of those menus), which you could then position on your site map page in a grid (or whatever layout you prefer).
This allows you to be very specific with what is displayed on the sitemap and how it is displayed.
Menu blocks also means you can customise the heading specifically for that block, without changing the name of the menu.
You could assign the blocks to a node page that has some introduction text for the body, of you could use something like the empty_page module to add a non-node sitemap page to assign your blocks to.

You can call your menus whatever you prefer, but I would not rename them to primary and secondary links. It is better to use more semantic names.
This is important in cases where you want the menu title displayed with the menu, and also when the menu title is there but hidden, to give screen readers better context, for accessibility.

Whether or not to display the manu titles in the site map also depends on your site setup and what you want to achieve.
If your menus are for distinct sections of the site it might be useful to have those sections stated in the sitemap, however if the title is not really relevant, for example "Main manu", "Navigation", "Footer links" etc., then it would likely be best to not show them.


How to place Contact form in block? I have to embed a contact form inside of a block, and I'm trying to use the entity.form_builder service, But I'm not sure which entity I should give it, I found Message and ContactForm entity, so what I'm thinking is to create a contact form entity and give it to the entityFormBuilder->getForm($contactFormEntity)

My current code is:

<?php

/**
 * @file
 * Contains Drupal\pid_contactform_block\Plugin\Block\TellUsYourStoryBlock
 */

namespace Drupal\pid_contactform_block\Plugin\Block;

use Drupal\Core\Block\BlockBase;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Class TellUsYourStoryBlock
 * @package Drupal\pid_contactform_block\Plugin\Block
 * @Block(
 *     id = "tell_us_your_story_block_id",
 *     admin_label = "Tell us your story block",
 *     module = "pid_contactform_block"
 * )
 */
class TellUsYourStoryBlock extends BlockBase implements ContainerFactoryPluginInterface {
    protected $entityFormBuilder;

public function __construct(array $configuration, $plugin_id, $plugin_definition, $entityFormBuilder) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);
    $this->entityFormBuilder = $entityFormBuilder;
}
/**
 * Builds and returns the renderable array for this block plugin.
 *
 * If a block should not be rendered because it has no content, then this
 * method must also ensure to return no content: it must then only return an
 * empty array, or an empty array with #cache set (with cacheability metadata
 * indicating the circumstances for it being empty).
 *
 * @return array
 *   A renderable array representing the content of the block.
 *
 * @see \Drupal\block\BlockViewBuilder
 */
public function build()
{
    return $this->entityFormBuilder->getForm();

}

/**
 * Creates an instance of the plugin.
 *
 * @param \Symfony\Component\DependencyInjection\ContainerInterface $container
 *   The container to pull out services used in the plugin.
 * @param array $configuration
 *   A configuration array containing information about the plugin instance.
 * @param string $plugin_id
 *   The plugin ID for the plugin instance.
 * @param mixed $plugin_definition
 *   The plugin implementation definition.
 *
 * @return static
 *   Returns an instance of this plugin.
 */
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition)
{
    return new static(
        $configuration,
        $plugin_id,
        $plugin_definition,
        $container->get('entity.form_builder')
    );
}

}

My question is basically:

Am i doing it the right way?
How do I initialize the ContactForm entity correctly, if I am right, should I just import it or should I require it through a service or something?
If I'm not right, do you have any idea how I should do it then?

Try Contact block module, which provides the contact form in a block.

From module documentation,

  The Contact Block module provides contact forms in a block. It uses the contact forms that can be created using the Drupal 8 core Contact module.


How do I get rules to select a random node? I'm working on my cron rule that will post to twitter every cron run. Thing is for this rule I need it to post a random node that either conforms to specific values in certain fields, or does something else if that value is false. I could use some help figuring this out.

Basically if The value of X=y I want the view to respond with one action, but if the value of X <> y then I want it to do another. And I need it to do this on random nodes of a sepcific content type.

Any ideas?

See How to Use EntityFieldQuery, particularly the section "Random ordering".


How can I override date field validation? I'm overriding the date field to hide the "day" part with this code:

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

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

This hides the day and allows the user to input the month and year.  If the field is required, everything is fine.

However, if the field is not required, and the user does not input any value on the form, then the form validation fails because the day of the date field has been set to 15, and the date module validation only accepts "every part (year + month + day) filled out" or "no part filled out."

So, on this specific field in my content type, I want to disable the date module's validation for the "day" alone-- or, I just want to disable validation for the entire date field.  How can I do that?

You can achieve this by prepending your own custom #element_validate function before Datelist::validateDatelist().

As in your question, you have to add an after_build function to access the individual parts (year, month, day) of the form element:

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

You can make the form element disappear by setting '#access' to FALSE.
Then prepend your custom #element_validate function to the array #element_validate on the element.

function MYMODULE_date_remove_day_after_build($form, &$form_state) {
  $form['field_MYFIELD']['widget'][0]['value']['day']['#access'] = FALSE;
  array_unshift($form['field_MYFIELD']['widget'][0]['value']['#element_validate'], 'mymodule_date_set_day');
  return $form;
}

Then in your custom element validate function, unset everything if Year or Month are unset, otherwise, set the day.  Notice you have to create the object before passing it to Datelist::validateDatelist().

use Drupal\Core\Form\FormStateInterface;
use Drupal\Component\Utility\NestedArray;
use Drupal\Core\Datetime\DrupalDateTime;

function mymodule_date_set_day(&$element, FormStateInterface $form_state, &$complete_form) {

  $input = NestedArray::getValue($form_state->getValues(), $element['#parents']);

  if (empty($input['year']) || empty($input['month'])) {
    $form_state->setValueForElement($element, []);
  }
  else {
    $input['day'] = "15";
    $timezone = !empty($element['#date_timezone']) ? $element['#date_timezone'] : NULL;
    $input['object'] = DrupalDateTime::createFromArray($input, $timezone);
    $form_state->setValueForElement($element, $input);
  }
}


How can I override Drupal\Component\Datetime\DateTimePlus::createFromArray I have to form datelist field. If user select incorrect date, for example 1970-02-31, displayed exception Exception:

  The array contains invalid values. in
  Drupal\Component\Datetime\DateTimePlus::createFromArray() (line 149 of
  core/lib/Drupal/Component/Datetime/DateTimePlus.php).

backtrace:

  Drupal\Component\Datetime\DateTimePlus::createFromArray() called
  at [/var/www/drupal8/core/modules/datetime/datetime.module:802]
  form_type_datelist_value() 2  call_user_func_array() called at
  [/var/www/drupal8/core/lib/Drupal/Core/Form/FormBuilder.php:1542]
  Drupal\Core\Form\FormBuilder->handleInputElement() called at
  [/var/www/drupal8/core/lib/Drupal/Core/Form/FormBuilder.php:1328]
  Drupal\Core\Form\FormBuilder->doBuildForm() called at
  [/var/www/drupal8/core/lib/Drupal/Core/Form/FormBuilder.php:1390]
  Drupal\Core\Form\FormBuilder->doBuildForm() called at
  [/var/www/drupal8/core/lib/Drupal/Core/Form/FormBuilder.php:1390]

I want override exception to return FALSE, and display to user warning about incorrect date.

How do I it?

As @Daniel Wehner suggests, this can easily be done by wrapping the calling code in a try - catch block. That's what it is for.


Grouping content types in group nodes I have created 2 different groups and updated content(basic pages & article) using group module in my drupal 8 project.

Currently it is listed in nodes tab of group.

I have used an view module to group based on the content type. But i couldn't make it.

Can anyone help me out?

The Group module provides Views 'relationships' to any node's parent group.

Try these steps to create your view:

Add a relationship to the parent group.
Add a contextual filter on the group's id (gid).
Create a page, a block, a content pane, etc (whatever fits your needs).


How to theme menus in a custom twig I've fetched the main menu for the website using the code below.

public function build() {
    $menu_name = 'main';
    $menu_tree = \Drupal::menuTree();
    $parameters = $menu_tree->getCurrentRouteMenuTreeParameters($menu_name);
    $parameters->setMinDepth(0);
    $tree = $menu_tree->load($menu_name, $parameters);
    $manipulators = array(
      array('callable' => 'menu.default_tree_manipulators:checkAccess'),
      array('callable' => 'menu.default_tree_manipulators:generateIndexAndSort'),
    );
    $tree = $menu_tree->transform($tree, $manipulators);
    $build['menu'] = $menu_tree->build($tree);

return array(
      '#theme' => 'allofus_menu_footer',
      '#build' => $build,
    );
  }

I'm trying to put it as a block, but I want to show it as a 2 coloumn. In the first coloumn, first main menu and its sub menus and the rest of main and sub menus in the second coloumn.

I've created a twig but it does not print anything except markup. I've tried to foreach but it is not working.

allofus-menu-footer.html.twig:

{% if build %}
    <nav id ="secondary-menu" class="navigation" role="navigation">
        {{ build }}
    </nav>
{% endif %}

I just did a lot of this with Menu Block. I prefer Menu Block as it is a little more flexible and offers more template suggestions and hooks than the core menu module. It kind of looks like you are building your own block above, I can't tell, but you can save time by using Menu Block in that case.

In one of my menus, this is the twig file that handles the output. I did not do any preprocess or extra stuff, just built around the macro concept used in menu.html.twig. Every parent item has children, and if those children items exceed 7, it will start a new list. For example, if the menu link has 14 children, then my code will have a drop down consisting of 2 unordered lists with 7 links each. Our style then makes them into columns. This is a little different from your use case, but should get you on the right track.

{#
/**
 * @file
 * Theme override to display a menu.
 *
 * Available variables:
 * - menu_name: The machine name of the menu.
 * - items: A nested list of menu items. Each menu item contains:
 *   - attributes: HTML attributes for the menu item.
 *   - below: The menu item child items.
 *   - title: The menu link title.
 *   - url: The menu link url, instance of \Drupal\Core\Url
 *   - localized_options: Menu link localized options.
 *   - is_expanded: TRUE if the link has visible children within the current
 *     menu tree.
 *   - is_collapsed: TRUE if the link has children within the current menu tree
 *     that are not currently visible.
 *   - in_active_trail: TRUE if the link is in the active trail.
 */
#}
{% import _self as menus %}

{#
  We call a macro which calls itself to render the full tree.
  @see http://twig.sensiolabs.org/doc/tags/macro.html
#}
{{ menus.menu_links(items, attributes, 0) }}

{% macro menu_links(items, attributes, menu_level) %}
  {% import _self as menus %}
  {% if items %}

      {% for item in items %}
        {%
          set classes = [
            'global-top__utility-item',
            'js-utility-item',
            item.in_active_trail ? 'active-trail',
            item.below ? 'has-submenu'
          ]
        %}

          {{ link(item.title, item.url) }}
          {% if item.below %}
            {{ menus.submenu_links(item.below, attributes, menu_level + 1) }}
          {% endif %}

      {% endfor %}

  {% endif %}
{% endmacro %}

{% macro submenu_links(items, attributes, menu_level) %}
  {% import _self as menus %}

    {% for chunk in items|batch(7) %}

        {% for item in chunk %}

            {{ link(item.title, item.url) }}

        {% endfor %}

    {% endfor %}

{% endmacro %}


Permission Conflict - Commerce Order - Please give me a guidance Today I a faced a confusing problem in my project.

let me introduce my project briefly.

I am creating a shop with drupal 7 and commerce module.

In my site 2 kinds of people exist. some people are seller and the others are customer.
I have created a role called "SELLER" for seller users.

as you know each member has a specific page in his client area called "orders". in this page a member is able to see his orders (it is history of user orders)

and in drupal 7 permission, it is defined that each person is able to see his/her orders only. there is no permission to see the other people's orders. (ONLY ADMINISTRATORS CAN SEE ALL ORDERS)

but in my project, I want to give permission to the sellers to see the other people' orders that contains at least a product that the current seller has introduced.

let me give you an example.
Imagine that we have a seller user in our site. his id is "seller_1"
seller_1 is selling product_1, product_2 and product_3 in site.

now a new user we called him "customer_1" wants to but product_1 .
he make an order and complete it. imagine that order number is "100".

now an order is saved in database and "customer_1" is able to see this order (order number 100) in orders page.

but in my plan the user "seller_1" must be able to see the order number 100 in a specific page that is created via a view.

=============================================

I tried to run this scenario but I have not found a solution yet.

in permission page, I gave "ability to see all orders" permission to seller roles. this modification solved my problem but it really breaks the security of site. because if we grant ability to see all orders to "SELLER" roles, the seller people are able to see all orders in the site even though there is no related product in the orders.

Now, do you have any suggestion for me?

Thanks a lot for your helps.

You would need to produce a custom permission using hook_permission that grants permission for sellers to see orders of their customers.


Translating the title of a custom block I am using the Bluemaster theme on a Drupal 7 site. I want to translate my site and everything is OK, but the title of the block I adde is not translated and still shows as "User menu" even when the language is not English.

How can I change the block title so that it appears in the language set for the site?

Try this:
in '/admin/structure/block' find your block, click on configure link beside it  then in Language setting tab Check "Make this block's title translatable"
Then Go to Translate interface admin/config/regional/translate/translate
Then enter the block title above and limit search to "block"


CCK ahah image upload working if admin, but not for others! A content type have image field. When uploading image as admin, everything works fine. But If i logged in as a normal user, and click on upload , it gives error ahah http error alert!

Also found add another button also giving same error.

What could be the issue?

What Drupal version do you use?
May I have list of modules you have?
What messages do you have in watchdog?

First think I have is drupal permission problem.


Display nodes by a date field from/to I have a content type with a Date text field. User can enter from and to dates to control when  this node will display. In my views filter, I'm adding both the from and to fields. 'From' is less than or equal to now and 'To' is greater than or equal to now.

The resulting query is not combining the range of dates, so all nodes show up in the result set.

Can I resolve this with just Date module? I don't want to use scheduler.

Drupal 6
Date 6.x-2.9

You need to select Method of handling multiple date fields in the same query as AND in the view exposed field setting.

Click on the * icon next to field in exposed filters section as shown below to complete above setting.


Adding custom layer to openlayers map I'm working with Openlayers and I would like to add a custom layer to a map with markers from a webservice.

It should works in this way:

I create a map with Openlayers UI and display it in a page;
I call an external webservice that returns me X elements with lat/long informations;
I show these elements in the map as a normal layer, with markers etc.

The questions are:

Have I to create with Openlayers UI a custom layer and then I've to populate it with js/ajax?
Or I should create a map without a layer and add this layers js/ajax, and popoulate it with js/ajax?

One way to do this is with a views geojson layer. This seems to be the only way that works right now...at least for me.

With static data, you create a views display of type feed (create a view with no page or block and set it to type feed). Then, set the format to geojson. You'll have to set the settings to your geofield, and add your geofield as a field to the view. Then finally, create a layer through the OL UI and set your feed as a source. Hope this helps.


Conditional on Header on a View Page? How can I put a condition on the Header in a View to not display the Header if the View has content?

There's an option to display a Header/Footer absent any content, but I'm looking for the opposite effect.

You can user template_preprocess_views_view function to do it

function mymodule_preprocess_views_view(&$variables) {
  if ($variables['view']->name == 'my_view') {
    if ($variables['view']->current_display == 'my_display' && !empty($variables['rows'])) {
      $variables['header'] = '';
      $variables['footer'] = '';
    }
  }
}


Creating custom blocks I am  building a custom block. The content of module_name/src/Plugin/Block/MyCustomblockName.php is the following.

    namespace Drupal\module_name\Plugin\Block;

    use Drupal\block\BlockBase;
    use Drupal\Core\Session\AccountInterface;

    /**
     * Provides a 'Demo' block.
     *
     * @Block(
     *   id = "demo_block",
     *   admin_label = @Translation("Demo block"),
     * )
     */

    class MyCustomblockName extends BlockBase {

      /**
       * {@inheritdoc}
       */
      public function build() {
        return array(
          '#markup' => $this->t('Hello World!'),
        );
      }

      /**
       * {@inheritdoc}
       */

  public function access(AccountInterface $account) {
    return $account->hasPermission('access content');
  }

}

It doesn't display the block at all. What could be the reason?

From the above code replace:

use Drupal\block\BlockBase;

with:

use Drupal\Core\Block\BlockBase;

Then Flush cache and check.
Go to Structure, BlockLayout and click on Place block.


How can I display a taxonomy term's ancestral tree on a content page? I am using Drupal 8. I have a hierarchical taxonomy vocabulary like this (simplified):

Animals
-Vertebrates
--Fishes
---Butterflyfishes
----Chevron Butterflyfish

On a taxonomy term's page, I automatically get the ancestral tree as breadcrumbs. For example, on drupal/Butterflyfishes I see this:

Animals >> Vertebrates >> Fishes

If I add Butterflyfishes as a Taxonomy term entity reference on a content page (i.e. not the taxonomy term's page itself), how can I also display such an ancestral tree on that content page?

2 possible solutions: a) programmatically via an own custom module providing a custom formatter or via a custom theme function. Or b) via contrib modules providing a field formatter to view the whole term path instead of only the end point (default).

In your case I assume you ask for the second. The module Hierarchical select used to provide this view widget (field formatter) in D7 and maybe alternative modules like SHS or CSHS in D8 will provide it? If not, you can try to work with the Custom formatter module, which enables you to build own formatters in admin UI without creating own modules for this purpose. It comes with examples showing how it works, and it can be used even if the user has no advanced module development knowledge.


Customized Node Display for 'Document Template' Content-Type I want to filter the nodes of content-type Document Template. I know this can be done with .tpl.php files.

I was wondering, what was the right file name convention. I tried the the naming convention but it does not work.

node--document template.tpl.php

Where did I go wrong?

Where did I go wrong?

You used the wrong format. Replace the space with a -:

node--document-template.tpl.php


Commerce Kickstart 2 Display color as visual colour In the 'Tops' Content type/Product Variation, the color selection in the 'catalog' shows up as multiple color blocks below the 'From $00.00' price information.

I've made up a new Content type and Product Variation, also with color. How do I get all the available product variation colors to show up as blocks of color below the price instead of just a single link to the first variations colour?

Go to Store setting -> Product settings -> Variation types -> your content type -> manage fields -> edit color(term reference)
enable the settings under "ATTRIBUTE FIELD SETTINGS"


Set link location on logo only I want the logo on my site to go somewhere other than the home page, but I can't seem to figure out where to change that.

I'd appreciate any help you can give

The answer to your question very much depends on your how your theme is built and what you want to accomplish. If you want just to link the site logo to another location, I would suggest you to find a corresponding piece of code in page.tpl.php of your theme and replace it with correct link.

If you want to give your site administrators  ability to change that link to whatever they want, then I would do this this way:

Create a module that adds a page to admin menu of drupal (using hook_menu).
On that page render a form with one input field. When the form is loaded extract previously saved value using variable_get function.
On form submit save the form value using variable_set function
In your hook_preprocess_page extract value using variable_get, compose correct link and pass it to the template
In your page.tpl.php just render it in the proper place


Postpaid license billing type does not work with Commerce Stripe This has been placed on https://www.drupal.org/node/2634778, but since there is no any reaction there yet I thought I'd have better chances here on Drupal Questions.

This has been tested well on a clean Drupal Commerce setup:

If a product configured with prepaid license billing type (see different billing types on https://www.drupal.org/node/2127603) is checked out, then everything works well - Drupal Commerce creates two orders: one already processed and one for the next billing period with the "Recurring: Open" status.

However, if a product with postpaid license billing type is checked out, then Drupal Commerce creates only one initial order that never recurs. What is interesting, if a postpaid product is checked out together with a prepaid product in a single order (just to get an order with "Recurring: Open" status created) and then if prepaid product gets cancelled, then the postpaid one keeps recurring successfully.

At the same time, if "Example payment" is used instead of "Commerce Stripe" as the payment method, then both pre and postpaid products recur without problems. Which makes me to believe that something in Commerce Stripe is not triggered when postpaid product is ordered.

This is just to let every one interested know, that Aviindub was kind enough to reply to my post on https://www.drupal.org/node/2634778#comment-10669204, after which I have re-installed everything from scratch once again, but in little bit different order, and postpaid orders started to recur too.


Error trying to submit webform programatically multiple times: Duplicate entry for key 'PRIMARY' I'm trying to programatically send submissions to a webform n times, but when I submit the submission info to the webform for the second time, I get an Integrity constraint violation: 1062 Duplicate entry 'nnnnn' for key 'PRIMARY' error. It appears the second submission has the same sid as the first submission, but I'm not sure why as I'm submitting NULL for the sid. How can I submit the webform again with the same information, but get a new sid? Drupal 7.
Here is the error in full:
PDOException: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '211-82916-1-0' for key 'PRIMARY': INSERT INTO {webform_submitted_data} (nid, sid, cid, no, data) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2, :db_insert_placeholder_3, :db_insert_placeholder_4); Array ( [:db_insert_placeholder_0] => 211 [:db_insert_placeholder_1] => 82916 [:db_insert_placeholder_2] => 1 [:db_insert_placeholder_3] => 0 [:db_insert_placeholder_4] => Bob ) in drupal_write_record() (line 7471 of /var/www/html/includes/common.inc).
And the code:
function wildsight_raffle_tickets_webform_submission_insert($node, $submission) {
  if ($submission->nid == 210) {

  $node_out = node_load('211');
  global $user;

  $data = array(
    'first_name' => $submission->data[3][0],
    'last_name' => $submission->data[4][0],
    'email' => $submission->data[14][0],
  );

  module_load_include('inc', 'webform', 'webform.module');
  module_load_include('inc', 'webform', 'includes/webform.submissions');

  // This methods will arrange $data in the right way
  $data = _webform_client_form_submit_flatten($node_out, $data);
  $data = webform_submission_data($node_out, $data);

  $submission_out = (object) array(
    'nid' => '211',
    'uid' => $user->uid,
    'sid' => NULL,
    'submitted' => REQUEST_TIME,
    'completed' => REQUEST_TIME,
    'remote_addr' => ip_address(),
    'is_draft' => FALSE,
    'data' => $data,
  );

  $number_of_tickets = $submission->data[24][0];
  while ($number_of_tickets > 0) {
    webform_submission_insert($node_out, $submission_out);
    $number_of_tickets -= 1;
  }
}
}

Not entirely sure why, but moving the line that sets $submission_out inside the loop fixes this problem.


Content type - manage display based on roles? Is there a way to define a custom display setting under Manage Display on a content type? I want to hide certain fields (when viewing, not editing) from non-authenticated users. I know I can do this with a custom .tpl file; just wondering if there's another way (without additional modules.)

As far as implementing a new view mode yourself goes it's pretty easy, without any contrib modules.

You can implement hook_entity_info_alter() to add a custom view mode to any entity. For example this code adds a new view mode called "Test View" to the node entity type:

function MYMODULE_entity_info_alter(&$info) {
  $info['node']['view modes']['test_view'] = array(
    'label' => 'Test View',
    'custom settings' => TRUE
  );
}

After a cache clear that view mode will appear in all the places you'd expect (manage display, views, etc.)


String Override limited to certain pages? I'm using the Fivestar module on different areas of the site. It displays "x votes" below the rating widget.

On some areas on the site it would like to change "votes" to "reviews". How could I do that?

The 'votes' text seems to be hard-coded into the theme_fivestar_summary() function (around line 264 of 'includes/fivestar.theme.inc'). It is run through format_plural() (so will eventually make itself available to string overrides), but I don't know of a way of defining complex conditions/contexts for string overrides.

The only (easy) way I can see to solve this is to re-implement that theme function in your own theme, copying the full function code from theme_fivestar_summary() to MYTHEME_fivestar_summary(), and introducing a contextual condition to alter the specific text that you want to change.

You'd be basically looking at changing these lines:

if (isset($votes) && !(isset($user_rating) || isset($average_rating))) {
  $output .= ' '. format_plural($votes, '@count vote', '@count votes') .'';
  $div_class = 'count';
}
elseif (isset($votes)) {
  $output .= ' ('. format_plural($votes, '@count vote', '@count votes') .')';
}

to:

$context = MYTHEME_get_fivestar_context();
if ($context == 'something') {
  $metric = 'review';
}
else if ($context == 'something_else') {
  $metric = 'vote';
}

if (isset($votes) && !(isset($user_rating) || isset($average_rating))) {
  $output .= ' '. format_plural($votes, '@count ' . $metric, '@count ' . $metric . 's') .'';
  $div_class = 'count';
}
elseif (isset($votes)) {
  $output .= ' ('. format_plural($votes, '@count ' . $metric, '@count ' . $metric . 's') .')';
}

It's not particularly pretty, but I think it's about the most efficient way to do it.


Calling a view from code gives no results I have a view that I use to grab a related node field given a user ID. I only call this view from code. The problem is, I just can't get it to work for a certain case.

To start with, here's the code that I use to call the view. The view accepts one argument (the user ID) and displays one field (the related node field). (I use multiple displays in this view for different code functions, thus why I build 'block_3'. Also, I'm calling this code from within a "User has logged in" Rule, which is why I use $account instead of global $user.)

$view = views_get_view('my_view_name');
$view->set_arguments( $account->uid );
$view->build('block_3');
$view->execute();

For the user ID "5", this works perfectly. But for the user ID "14", it returns no results. The frustrating part is that in the View settings, I can enter "14" for the preview argument and it ALSO works perfectly!

I'm at my wit's end. Why would the view work perfectly fine in the preview and for one user ID, but not for another?

Some notes

I've confirmed with dpm() that $account->uid is being set properly. I've also changed User ID 14's roles to match User ID 5's, and even swapped the related nodes for the two accounts, but User ID 14 always fails to work while User ID 5 has no issues.
If I pass $view->result to dpm(), I get empty text; dpm($view) returns the $view object, where I can see that $view->result is an empty text.

The View set_arguments() method takes an array as it's first parameter; currently you're passing a string/int.

This code will work.

$view->set_arguments(array($account->uid));

I think you're right about the C-style access to a string-as-an-array-of-chars in PHP. The following code prints the letter e, which would certainly support that theory.

$x = 'test';
print $x[1];

I must say I'm surprised that Views doesn't check the validity of the parameter passed to it, but hey ho!


Preferred way of loading a specific entity revision In drupal 7 you can do this to load an entity revision using

entity_load($entity_type, $ids = FALSE, $conditions = array(), $reset = FALSE)

like this:

$old_revision = entity_load('node', array(), array('vid' => 123));

However now $conditions is being deprecated.
Pretty much wherever you go you see people saying that you should use EntityFieldQuery instead of conditions, however that doesn't help in this case.
You can use age() to query revisions using EntityFieldQuery however it doesn't give you fully loaded node results so you then still have to load the entity and how do you load that revision of that entity without the conditions.

Currently the preferred way is to get the storage instance (EntityStorageInterface) for the entity type from the EntityTypeManager and then use its loadRevision() function. For example, you could do this for a node:

$node_revision = \Drupal::entityTypeManager()
  ->getStorage('node')
  ->loadRevision($node_revision_id);

Previously to this you would get the storage instance from the EntityManager like this:

$node_revision = \Drupal::entityManager()
  ->getStorage('node')
  ->loadRevision($node_revision_id);

This still currently works however it has been deprecated in favour of the first method. The change record relating to this is at https://www.drupal.org/node/2549139

The old way, which still currently works in Drupal 8 but is also deprecated, is the function entity_revision_load(), which is also available in drupal 7 via entity_revision_load() in the Entity API module.

This function replaces the use of conditions to load old entity revisions.
You can see the history of this change in the Drupal core issue about Remove deprecated $conditions support from entity controller.

The way you would use this function as per the original question is:

$old_revision = entity_revision_load('node', 123);


Call internal pages with drupal_http_request I'm writing a little module, and I need to call several pages of my site using drupal_http_request(), which accepts only absolute URLs.
I don't want to add a variable to store the domain of the site, also because on my company we have proxy etc.

Which is the best way to add the domain of the site?

Here is what I'm using in a similar situation, with $base_url as Baysaa mentioned above.

$path_to_file = '/path/to/feed.xml';
$base_url = $GLOBALS['base_url']; // Not sure if this line is necessary.
$file_over_http = $base_url . $path_to_file;
$http_result = drupal_http_request($file_over_http);


Can't set view title in hook_views_views_pre_view I am trying to change the title of the view based on some conditions view object. I figured that I could simply run

drupal_set_title('New title');

from inside the hook_views_views_pre_view, but its not changing the title. I tried it in hook_views_query_alter too, but it wouldn't change. I've confirmed that its actually entering the hook by doing a printout of the view object.

Should I be able to set the title from these hooks?

It's probably the Views module is calling drupal_set_title() right after invoking those hooks, so calling drupal_set_title() in those hook doesn't have the effect you are expecting. You could eventually use view::set_title in hook_views_pre_view() or hook_views_pre_render().

function mymodule_views_pre_view(&$view) {
  if ($view->name == 'the view you need to alter') {
    $view->set_title(t('New title'));
  }
}

You cannot assume those hooks are invoked when a view page is being rendered; it could be the view is embedded in a page for which the title change is not desired. This is similar as assuming hook_node_view() is being invoked when a node is rendered in its own page, and then calling drupal_goto() from that hook.


Entity print get variable in twig template I'm using entity print and I would like to get node variables in my twig template, so I can call them like {{ content.field_name }}.

I tried using a preprocess function but I'm not sure I'm doing things well.

Assuming I have a twig template called entity-print.html.twig, here the preprocess functions I tried :

function THEMENAME_template_preprocess_entity_print(&$vars) {
    $vars['field_name'] = $entity->get('field_name')->getValue();
  }

I also tried

  function THEMENAME_template_preprocess_entity_print(&$vars) {
    $vars['field_name'] = $entity->get('field_name')->value;
  }

I'm calling field_name with all of this twig variable for debugging purpose :

   1 {{ content.field_name.0 }}
   2 {{ content.field_name.value }}
   3 {{ content.field_name.0.value }}
   4 {{ field_name.content }}
   5 {{ content.field_name[0] }}
   6 {{ node.field_name.value }}

Nothing come. What am I doing wrong ? Do I have to make a custom module ?

Looks like you need to review Entity Print in Drupal 8 again. I am using the Entity Print module and it works just fine. Here are some pointers I would recommend below. Your original post is regarding printing node variables in twig templates

On your content type, navigate to Manage Display-->Expand Custom Display Settings-->Enable PDF. This will create a PDF view mode (which is used for printing)
Create a twig template node--article--pdf.html.twig (replace article with machine name of your content type)
Update your_theme.info.yml and your_theme.libraries.yml as suggested in Entity Print in Drupal 8 so you can control the theme and assign a css file only for print
Copy and add entity-print.html.twig to your subtheme
Using node--article--pdf.html.twig, you can control whatever variable you need. However, I recommend you use the PDF view mode first to see what it can do for you.

I have yet to use a preprocess function and you should only need that if you need additional processing. Using the PDF view mode, entity-print.html.twig and the node--article--pdf.html.twig templates you will be able to print as you need.

Ultimately, you should use the PDF view mode so you can manage the PDF view mode (add classes, divs, order, add/hide/remove fields, etc.) through the UI. I have found that managing what fields are displayed through code can be cumbersome if you have a lot. The view mode can handle a lot of what you need, but you need to enable the PDf view mode first.

Sample entity-print.html.twig

<!DOCTYPE html>

  <meta charset="utf-8">
  <title>{{ title }}</title>
  {{ entity_print_css }}

      {{ content }}

Sample node--article--pdf.html.twig:

  {{ content.field_name }}
  {{ content.body }}
  {{ label }}
  {{ content.field_name.0.value }}


How do I configure meta tags for a panel page? How do I configure meta tags for a panel page? I want to change title, keywords and description.

Ideally I want to use Yoast.

I have the same requirement and one of the patches attached in the issue titled "Panels / Page Manager integration" worked for me. This patch basically adds a module of panel pages which when enabled, provides interface to configure meta tags for each panel pages under /admin/config/search/metatag.


How to tell the filter views is using I'm in the process of writing a custom views filter handler. In order to learn from the existing filters, I'd like to know how I can tell which filter class views is using when I'm configuring an (exposed) filter on the GUI.

Adding an exposed view filter inserts the following (sample) code into the view output:

        ...

        <form action="..." accept-charset="UTF-8" method="get" id="views-exposed-form-...">

                     ...

                           <select name="tid" class="form-select" id="edit-tid" >
                              <option value="All">...</option>...
                           </select>

                    <input type="submit" id="edit-submit-..." class="form-submit" />
                 ...

It is not clear, though, why you can't find out the same by simply creating a view, exposing its filter and looking up the source code. Perhaps you could explain your question better?


How can I use cookies on Webform? I'm using Drupal 7 and Webform and I want, remember input texts on next submissions for registered users.

How can I do it?

Try the Webform Field Repeat  module

  The Webform Field Repeat module enables the webform to remember selected field entries from current submission for up to an hour. It uses the $_SESSION to do so. If the session is active, the form will be populated with selected entries from remembered submission when opened again.


Is it possible to update Drupal page cache right after it is cleared? I am trying to improve Drupal performance and I have all the tuning usual suspects setup:

Varnish
Memcache
APC
Drupal core cache

From what I understand when you clear the Drupal cache it does not replenish page caches until an anonymous end user makes a request for the page. Drupal then builds the cache and the following page requests are snappy. The problem with this is the non cached call can take 2- 4 seconds to finish. We would like all page requests to be as snappy as a cached request. So we are looking into either a way auto replenish or set up a cron that would hopefully make the non cached page request before an end user.

If my assumptions are correct is there a module or way to automatically replenish all page caches? I am assuming that since this does not automatically happen that it is potentially a resource issue to cache the entire site at once. But if we set Drupals cache to live for 1 or 2 days and cleared cache on a cron in the middle of the night it might be ok to automatically replenish. Has anyone ever tried to solution this?

Cache Warmer Module is the one you are looking for.

  cache_warmer is a drush command that hits a set of URIs of a drupal
  site based on the freshness of the content.

It is a drush integration for warming the caches using httprl, which means calls can be made parallely as well.

Since it is a drush extension you can tie it up easily with your cron as well.


Account creation emails not being sent but other emails are I have a site that was upgraded from D6 to D7 and is now hosted on Pantheon. I'm using the SMTP module and SendGrid for deliverability. The "require email verification when a visitor creates an account" setting is checked. When someone registers as a new user, the message saying that an email has been sent to their account is displayed on screen. However, neither watchdog nor Maillog shows any evidence that an email was sent, and no email is received.

Other emails, including password reset, Webform emails, Comment Notify, etc. all are sent and received as expected.

What could be causing the new user email not to be triggered?

I would create a clean Drupal site on Pantheon and configure just SendGrid.  Do all emails get sent as expected from the new site?  If so, it's likely that there is some custom code running on the problematic site calling hook_mail_alter or altering the normal mail handling in some other way.

You'll also find some great tips to help troubleshoot email issues in http://www.webomelette.com/drupal-modules-debug-emails


In form alter what is the different way of hiding fields and what is the difference between them? I am currently using the following code to hide the fields in the form

1.  $form['field_name']['#access'] = FALSE;
2.  hide($form['picture']);
3.  unset($form['picture']);
4.  $form['account']['mail']['#disabled'] = TRUE;

i saw this post https://stackoverflow.com/a/21041471/2251933 , https://drupal.stackexchange.com/a/49985/36808 explains some of the point but not all.

i want to retain the values in the form after form save but for some reason i want to hide the fields in the form.

what is the best way to do it and why it is so.

The basic differences are:

$form['field_name']['#access'] = FALSE; hides the form element. When saving the form Drupal will not touch the field. That means the initial value will remain. Maybe interesting: Other users can do with that node's field what ever they want. You saving the node will not undo their changes, although you only know about the old value of that field.

hide($form['picture']); is afaik used in theme functions only. It can cause forms to break because after saving a form this field is expected to have a value but is not even rendered. So use this with care. When you hide a field that is important make sure to manually render it later. Calling hide will also hide all child elements of the element you hide. A use case could be: Render child elements of a form manully and call hide on those elements. When you now render the parent element only those child elements are rendered that did not go through hide.

unset($form['picture']); should not be used. It just drops parts of an array. It is better to use one of the other three functions that keep the data consistent and not delete stuff Drupal expects.

$form['account']['mail']['#disabled'] = TRUE; will not hide the element but just make it unchangable (greyed dropdowns, etc.). It acts like a normal field but the initial value cannot be changed by the user.

In addition to what you asked, Clive added something:

Form elements are commonly converted to array('#type' => 'value', '#value' => 'foo') to remove them from the form but keep them server side, and not mess up the submission process. It's the best of all available methods IMO

Hope that help although I am not completely sure about the consequences of unset.

cheers,
j


Form redirect in hook alter submit is not working in Drupal 8 I want to create multi step form based on tabs created using Fieldgroups. I have been able to alter the ECK form as well as added my own custom submit handler.

In the custom submit handler, I have added a form redirect that redirects to the same form but with a fragment so that the next tab gets shown. I am able to generate the fragment for the route, but its not working. In-fact, the redirect seems to not work at all for any valid internal route. Kindly advise.

Please find the form redirect url.

$url = new Drupal\Core\Url('eck.entity.add'
, ['eck_entity_type' => 'registration_configuration' , 'eck_entity_bundle' => 'config_2']
, ['fragment' => 'edit-group-add']);
$form_state->setRedirectUrl($url);

I was executing setRebuild()! I added another submit button and started doing the steps in my previous submit logic one by one, then it hit me. Form redirection will not happen if your submit is rebuilding the same form :)

$form_state->setRebuild();


Drupal 7, superfish menu hidden in garland theme I am using the default theme garland in Drupal 7.23 with a superfish menu put on the first sidebar block . (the side on the left).

But when I try to open the menu, and on my content block I have a view or a nivo slideshow block the menu is hidden. Where should I put the z-index? (tried on the theme and on the menu but nothing worked)

Thank you

In page.tpl.php page search with keyword menu,

 <div id="main-menu" style="z-index:99">

you can put style z-inex here.


How to make specific field disabled on node submit, but enabled on node edit? In content type testtype I have 2 required field: field_one & field_two.

I need to make field_one only enabled on node submit, while field_two only enabled on node edit.

So, when submitting, we can only see field_one, and when editing, we can only see field_two

you can solve this problem in different ways.

The first is quite easy: you can show/hide the fields from CSS.

When you create a node, the default body classes contain this CSS class: "page-node-add". Instead when you edit a node you'll have the class "page-node-edit".

So you can add this CSS code:

.page-node-add .field_two{ display:none }
.page-node-edit .field_one{ display:none }

This solution is not elegant and it could be a potential security hole.

A better solution is to implement hook_form_alter() from your theme or from a custom module.

The code could be something like:

function yourmodulename_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'testtype_node_form' && arg(1) == 'add' ) {
    $form['field_two']['#access'] = 0;
  }
  if ($form_id == 'testtype_node_form' && arg(2) == 'edit' ) {
    $form['field_one']['#access'] = 0;
  }
}

Good work!


List of User's Comments - show one latest comment on node only I have a views block that lists a user's comments on the site.

For example user JohnA has posted 5 comments total on the site like so:

Node 1: 2 comments
Node 2: 1 comment
Node 3: 2 comments

In my view, I want to create a list of nodes that JohnA has commented on with the following Format:

Node Title

By Node Author

You commented on this 2 months ago

However, when a create a view and add the field Comment: Post Date, Node 1 and Node 3, which JohnA has commented on twice, show up twice (because JohnA has two values for that field in this context).

The view works fine until adding any comment specific field, such as comment post date, comment body, etc...

I'm thinking about using the Views View Field module as a potential solution. I feel like there is a simple solution that I am missing.

Any help would be greatly appreciated.

I would use the Views Field View or a similar module for this.

The reasons is that you are trying to filter on two things:
* Most recent comment
* Unique node

I would create a "parent" view that shows all nodes the user has commented on and then a "child" view that filters the comments on each node to show the most recent one.

See my detailed answer here to a question about getting the latest node per user.

An alternative is to play around with Views aggregation settings.


How to debug TransactionOutOfOrderException: in DatabaseConnection->rollback() in database.inc? I'm just trying to create an order in code like this:

$selected_month = $form_state['values']['month'];
$selected_year = $form_state['values']['year'];
$order = commerce_order_new($form_state['values']['user'], 'checkout_checkout');
commerce_order_save($order);
$order_wrapper = entity_metadata_wrapper('commerce_order', $order);
$product = commerce_product_load($form_state['values']['product']);
$line_item = commerce_product_line_item_new($product, 1, $order->order_id);
commerce_line_item_save($line_item);
$order_wrapper->commerce_line_items[] = $line_item;
dpm($order_wrapper->value());
$order_wrapper->save();

This in inside an form submit callback, so I have all the data needed like productId, userId, etc., but suddenly it stopped working. Apache says nothing and can't see MySQL logs but i contacted my provider and says that there is no logs either.

I'm using commerce_addressbook, but not using commerce_coupon or commerce_discount. Not altering the order_id in rules.

Looks like some kind of order_id problems but not sure, it looks like the second order_save (with wrapper function or commerce_order_save) tries to save the order but with the same order_id.

In the database the order is created with its line item

I've tried to clear all the caches, same result.

A thing which i find strange to me, is its revision id, in the database even tought order_id is 160, for example, its revision id is 552.

Another strange behaviour i found is that the commerce_order_total is not set at all, the row in the table is created but with 0 amount.

Same result for both saving functions, tried both but it is always in the second call of the order save, I comment that line and it works.

Commenting that line works, but of course no line items, but the rows are created for both entities, commerce_order and commerce_line_item. I mean, i see them in the data base but in the edit page of that created order, there is no line items

Here is the content of $order_wrapper->value():

Basically the TransactionOutOfOrderException exception is triggered by transaction being rolled-back (see: rollback()) called by Commerce module which was triggered by inability to save your entity (such as validation errors like saving empty values for required fields). Check commerce_line_item.controller.inc or commerce_order.controller.inc files for more details when exactly rollback is triggered.

Since you're using entity metadata wrappers, it is strongly recommended that you should implement try...catch section to catch exceptions and add debugging errors into watchdog. Here is the sample syntax of saving node wrapper:

try {
  $node_wrapper = entity_metadata_wrapper('node', $node);
  $price = $node_wrapper->field_product->field_price->value();
}
catch (EntityMetadataWrapperException $exc) {
  watchdog(
    'MODULE_NAME',
    'EntityMetadataWrapper exception in %function() <pre>@trace</pre>',
    array('%function' => __FUNCTION__, '@trace' => $exc->getTraceAsString()),
    WATCHDOG_ERROR
  );
}

So adequately your code should look like:

if (empty($form_state['values']['product'])) {
  drupal_set_message(t('Missing product on the submit form! Form values: @values',
    array('@values' => print_r($form_state['values'], TRUE)), 'error');
  return;
}
// @todo: Do above condition for other parameters as well.
$selected_month = $form_state['values']['month'];
$selected_year = $form_state['values']['year'];
$order = commerce_order_new($form_state['values']['user'], 'checkout_checkout');
commerce_order_save($order);

try {
  $order_wrapper = entity_metadata_wrapper('commerce_order', $order);
  $product = commerce_product_load($form_state['values']['product']);
  $line_item = commerce_product_line_item_new($product, 1, $order->order_id);
  commerce_line_item_save($line_item);
}
catch (Exception $e) {
  drupal_set_message(t('Error saving line item: @item, message: @error.',
    array('@item' => print_r($line_item, TRUE), '@error' => $e->getMessage())), 'error');
  watchdog_exception('mymodule', $e);
}

try {
  $order_wrapper->commerce_line_items[] = $line_item;
  $order_wrapper->save();
catch (Exception $e) {
  drupal_set_message(t('Error saving order: @order, message: @error.',
    array('@order' => print_r($order_wrapper, TRUE), '@error' => $e->getMessage())), 'error');
  watchdog_exception('mymodule', $e);
}

Note: Test the above code first on your testing environment.

So basically by implementing more logging into your code, you can see further what's missing and why it's failing.

For further debugging, ideally you should setup your local environment with copy of the database and reproduce the problem on your development machine.

Since you're dealing with submit handler, for easier debugging, you can use DevTools (in the supported browser) where you can repeat XHR requests, so you can see results after code changes without filling out the complex forms. If your form will require different token on each submit, ideally you should add die()/exit(); to prevent the form being completely submitted, this way you can test your form using quick and repeatable method.

For more sophisticated debugging, you should use step-by-step debugger by using some IDE editors which can support that, by enabling XDebug PHP extension. Or generate the trace file which can help you to find out more about your issue.


Display members with same taxonomy using Views Users have a "school" term reference field. When user visits his own user page, I want him to see his classmates listed.
For example, imagine that I have 3 students from the same school. When student A id:4 visits user/4, I want all student B and student C listed.
I can do this on term's page, term/10, but I could not figure out how to do it on user's page.
I believe it would have to be configured through contextual filter but I could not find a way yet.
Any help will be greatly appreciated!!

Create a view block of users and show all the required fields.

Add a contextual filter for school.

Now here ideally we need some way to dynamically get the school id
of the current logged in user. But we only get these kinds of values:

So in order to dynamically get the term id of the user's field. we can either write a custom hook hook_views_pre_view See its documentation and modify the correct $arg by loading the current user and getting the user's selected term for school.
or

Create a custom views argument plugin, or use this module : https://www.drupal.org/project/user_field_value


How to fetch the field data in computed field In  my content type i have range field which have two value from and to. i would like to print the from value only through the computed field.The object array looks like this

[object array]
  [field_range]
     [und]
      [0]
       [from]
       [to]

I tried to fetch the form value by using below piece of code but i am not able to get result. Please anyone guide me to achieve this.

$field_items = field_get_items($entity_type, $entity, 'field_range');
$drilldata = $field_items['und']['0']['value'];
$entity_field[0]['value'] = $drilldata->from;

field_get_items() takes care of language negotiation for you, so the field value is one level up. e.g.

$field_items = field_get_items($entity_type, $entity, 'field_range');
if (!empty($field_items[0])) {
  $data = $field_items[0]['value']->from;
}


How to make https links available to anonymous when new article is published? When content/article is created the content is accessible first on the http link and then later the httpS link. There is usually a delay of at least 5mns for anonymous  to access it.

http://example.com/item-just-published
vs
https://example.com/item-just-published

The cache settings have been modified for the content type to refresh cache on update and insert but it seems to affect the http links only not httpS. This is a problem as some time sensitive items don't get to the audience in a timely matter using httpS links.

example.com/admin/config/development/performance

example.com/admin/config/system/expire

How to make httpS links available as soon as it is published to anonymous?

Assuming both secure and non-secure websites are in fact the same Drupal instance, there are a few possibilities which may cause the issue you are experiencing:

Web server; configuration differences in secure non-secure sites.
Compare both website settings. Only difference should be SSL specific settings, rest should be same or inheriting settings from other's. if necessary, refer to web server's official documentation.
Web server; misconfiguration in redirect rules
From your comments it's clear that both websites are actually available. Still there could be redirect rules needs correcting.
HTTP or HTTPS version of the site has an external caching system
Check if there is caching system or proxy enabled for either of the sites. i.e. Varnish, Redis, CloudFlare.

Please provide some more details about the webserver (Apache, nginx, IIS, etc), and currently installed caching and performance related modules.

Also, you can consider serving the site only on HTTPS, to avoid penalties from search engines for duplicate content.


Custom filter disabled after approximatively 45 minutes I am developping a filter to render equations in nodes as images from LaTeX code using mathtex library ( http://www.forkosh.com/mathtex.html ).

The filter works quite well, my filter is active, the content is filtered, the node is cached using Boost and the HTML file is containing teh filtered HTML code.

BUT : after several minutes (arround 45 minutes) my filter is disabled (not visible in the input format adminpage, see below) despite that the module is still activated in the module page and the content is not filtered anymore.
BUT : when I desactivate/reactivate the modules, OR when I delete all caches, the filter is reactivated, the content is filtered again. And approximatively 45 minutes after it's not filtered anymore.

I try to do the same filter but using the Custom Filters module and I had the same behavior.

I supposed that the cron job had an influence, but content become not filtered BEFORE cron is executed (every hours).

Someone has an idea from where does the problem can come from ?

I'm running :
Drupal 7.23 using lots of modules : http://sites.uclouvain.be/selt/files/selt-modules.txt

Some captures to illustrate :

Content not filtered, as after approximately 45 minutes :

Content filtered, as after cache flushing or de/reactivation of module :

Administrative page for format "Full HTML" showing activated mathtex filter :

Administrative page for format "Full HTML" not showing filter :

After several tests and investigations, the culprit was the distant MySQL server which had a too short wait_timout. During cache refreshing operations the server used to go away before filters beeing applyed, leading to caching unfiltered pages. Using a MySQL server with no wait_timeout has solved this problem, without changing any setting elsewhere.


Migration with ID already exists My migration is not showing up in drush migrate-status. When I try to reimport them with drush config-import --partial --source="modules/custom/complinetmigration/config/install" I get the following error message.

  The import failed due for the following reasons:
  Unexpected error during import with operation create for
  migrate_plus.migration.complinet_xml_to_node2: migration entity with ID market_center_to_D8 already exists.

Try deleting the existing migration by doing drush cdel migrate_plus.migration.MIGRATION_ID
I think the id in your YML file is not the same as the MIGRATION_ID part of your YML file name.


Can I use Rules Transform to remove text from a returned value? I notice that Drupal Rules Data Transforms has the "trim text" action option. Is it possible to trim the returned value by a specific number of characters, or remove a specific word from the returned string?

E.g. I grab an entity field value with my first action, and I want to remove the word "grams" from the returned value.

You can try applying this Rules Data Transforms replace text patch which adds the ability to replace text. Flush cache after applying patch.

So now simply replace grams with nothing (empty).


How to theming and deploy custom blocks which created in admin UI? I've created some custom blocks in my development environment and export them with Features + FE Block with given machine names. And then deploy and enable them in my staging environment.

Just like the sample below, the blocks with same machine name have different block ids in different environments, but I want the guide block has a special layout than other blocks.

development
    block-block-1 (guide)
    block-block-2 (case_links)

staging
    block-block-1 (case_links)
    block-block-2 (guide)

Because in different environments the guide block has different block_id, I can't just use the block id as the identifier to apply these css rules.

What should I do to solve this problem?

You can add custom classes or id's to your blocks. If you don't feel to code it yourself your best bet would be to use the Block class module, and perhaps also along with the Block Class Styles module which provides custom templates for your blocks.

--update--

The new version (7.x-2.0) of Block Class module has just changed it database structure, removed the block_class table and add a field css_class into block table. The current version of Block Class Styles module work well with Block Class 7.x-1.2.


How do you programmatically create a webform with a managed_file type? I haven't been able to find a single example of how to create a webform with a managed_file type.

The webform initially had the type 'file', but needs to be changed to accept multiple attachments. When the type is changed to 'managed_file', the field for uploading attachments does not render.

Here is my code snippet for the attachment field:

7 => array(
    'name' => t('Attachment'),
    'form_key' => 'attachment',
    'type' => 'managed_file',
    'upload_location' => NULL,
    'pid' => 1,
    'weight' => 6,
    'value' => '',
    'required' => '0',
    'extra' => array(
      'directory' => 'story',
      'title_display' => 'before',
      'private' => 0,
      'wrapper_classes' => '',
      'css_classes' => '',
      'filtering' => array(
        'size' => '2 MB',
        'types' => array(
          'gif',
          'jpg',
          'jpeg',
          'png',
          'txt',
          'rtf',
          'html',
          'pdf',
          'doc',
          'docx',
          'ppt',
          'pptx',
          'xls',
          'xlsx',
          'zip',
        ),
        'addextensions' => '',
      ),
      'rename' => '',
      'scheme' => 'public',
      'progress_indicator' => 'throbber',
      'description' => '',
      'attributes' => array(),
      'analysis' => FALSE,
    ),
  ),
);

Thanks much!

Making a couple of leaps here:

I couldn't find a D8 release for Webform so assuming D7
I'm assuming by managed_file (which is a FAPI element type) you mean a field API file field, as you mentioned making it accept multiple files (which the managed_file element doesn't have any support for).

So with those in mind...

Webform implements its own set of components, of which file is one type; it doesn't use the field API, so unfortunately you can't attach field API fields of any type to it.

The out-of-the-box file component doesn't support multiple uploads, but there's a contributed module, Webform Multiple File, which does:

  Module Webform Multiple File provides new Webform component for multiple file uploading. The module based on principles of file field widget and has similar design.


How to get the selected items (with VBO) in the buildConfigurationForm of a custom Action I have made a custom action which have a configuration form:

class MyAction extends ConfigurableActionBase

Thus, I have the opportunity to create a form that allows the user to set some options. This form is created inside

public function buildConfigurationForm(array $form, FormStateInterface $form_state)

I need to get the list of the selected items that will be processed at this stage in order for me to exclude some option in the configuration form. In my use case, I need to exclude some option depending of the bundle of the selected entities (by my VBO view)

Provided you use the Views Bulk Operations contrib module, you can use code similar to the following, inside the buildConfigurationForm() method. Most importantly, you need to extend ViewsBulkOperationsActionBase instead of ConfigurableActionBase.

class YourAction extends ViewsBulkOperationsActionBase

...
  public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
    ...
    $selectedItems = array_map(function ($listItem) {
      return reset($listItem);
    }, $this->context['list']);
    ...
  }
...

This will give you an array whose values are the entity ids of the selected items in your view. The keys of the array are the bulkFormKey for each selected entity.

See ViewsBulkOperationsFormTrait::calculateEntityBulkFormKey() and ViewsBulkOperationsFormTrait::getListItem() for more information about bulkFormKeys.

Hope this helps, good luck!

P.S.: And for anyone else landing here, the related VBO's documentation page is over at https://www.drupal.org/docs/8/modules/views-bulk-operations-vbo/configuring-an-action


Will I be able to run my site on PHP 7.0? I've started reading about some performance benchmarks with PHP 7.0 which suggest that it is spectacularly much faster. I've searched all over for information on Drupal support for PHP 7.0, but all that I can find concerns Drupal 8 whereas I am still working for the moment on Drupal 7.

I have found this article that concerns Drupal on Windows, which suggests that D7 on PHP7 works, however since I am running on Centos or Ubuntu I would welcome any information anyone might have on this.

My concern is particularly strong because I am just getting started on a project with massive data inputs, which will thus be very performance sensitive.

The canonical Drupal 8 issue is tagged "Needs backport to D7", which indicates the community intends to support Drupal 7 on PHP 7 but it may take a little time.


how to grant a user to only access the performance area of the configuration screen drupal 7 I would like to give my content editors the ability to flush the website Drupal cache. I can't seem to give them this privilege without also giving them the privilege to do everything in the configuration tab. Can I only give them permissions to clear the cache? (Obviously this in addition to editing content) I am using Drupal 7.

Thanks!

you can write a simple custom module to do this for you.
as you can see.with hook_menu_alter you can alter all menu in drupal. And by overriding it's access callback you can have your custom function to grant access to your users. Here is a sample code that check if user has an 'editor' role.then it return true and user can access performance.

function MYMODULE_menu_alter(&$items) {
  $items['admin/config/development/performance']['access callback'] = '_accesscheck';
}

function _accesscheck(){
  global $user;
  if(in_array('editor', $user->roles)){
     return TRUE;
  }
  return FALSE;
}


Help with adding GMap on contact page I'm trying to add a GMap to my contact page, I don't have the need for Location / GMap modules. I'm following the tutorial here but following it I have to add everything to the head in my html.tpl file:

<script>
  function initialize() {
    var map_canvas = document.getElementById('map_canvas');
    var map_options = {
      center: new google.maps.LatLng(44.5403, -78.5463),
      zoom: 8,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    }
    var map = new google.maps.Map(map_canvas, map_options)
  }
  google.maps.event.addDomListener(window, 'load', initialize);
</script>

Where else can I place this script? I've tried to add it in a separate JS file and call it through my info file but it doesn't work that way.

May be you have miss something.

For Gmap on Drupal site there are many ways to implement.

You can try this approch:

Put whole the code in any block with full text format.
Place that block in a specific region.
Set visiblity of that bock as per your requirment.

Implementation code be like this


Add more than 2 profile in Civicrm contribution page I'm using civicrm contribution page to create a membership renewal page. But in the "Profile" tab, I'm only able to add  two profile, one in top of the page, one in bottom of the page.

Is there any way I can add in more than two profiles in the page? Just like in event page, I can add 7 profile.

Thank you.

There's no way of doing this through the user interface.

An alternative approach would be to use a Drupal webform integrated with CiviCRM. You'll need the Webform module, the webform_civicrm integration module, and various dependencies.

Depending on the payment processor you are using to process the membership payment, if indeed you are using any, you can then build a form that will include all the CiviCRM fields you need without needing to create profiles.

If you are using a payment processor and accepting online payments for you memberships, IPN-based processors, such as Paypal standard, aren't supported by this approach, but you can get around that by having the user taken from the webform through to a basic CiviCRM contribution page and they can make their payment there.


Are the parameters of saved exposed Views filters saved in the database, and if so, how can I access it? So in a View (using Views 3) we can expose filters and these filters are "saveable" by particular users, where is this saved, and can I access it?

I want to be able to "save" the parameters and then be able to email the user later with updated search results periodically...

I'm assuming that if no filters have been applied, the view will display all of the content...

Use Saved Searches

  Saved Searches provides a simple workflow for saving search queries
  from Drupal core search. It will take advantage of Apache Solr facets,
  if the Apache Solr Search Integration module is installed.

  Saved Searches gives users with permission access to a "save this
  search" form in a block, which appears on search result pages, and
  lists the user's saved searches in another block. Depending on a
  user's permissions, Saved Searches will provide a simple "Save this
  search" button, a text field for entering a short URL slug, and/or a
  dropdown to "Re-use an existing saved search name". Clicking the "Save
  this search" button without entering a URL slug will generate a short
  URL for the search, like "http://example.com/s/cwmc". A link to the
  search will appear in the savedsearches_user block.

  Saved Searches is useful for sites with complex search options, or
  sites where users may want to revisit or share dynamic sets of search
  results.


flexslider keeps crashing when i try to change settings I have used all the latest Flex Slider modules and library, I have created a View, with format of slideshow, the Slideshow Type is defaulting to Flexslider, and I'm using the default Optionset.

I have the title of the slide and the image being displayed. everything works as expected in terms of it being responsive, however, if I edit the View, then click Settings under Format, and then either click Save or Cancel, I get a few pages of rubbish displayed (see below) can anyone help?

  [{"command":"settings","settings":{"basePath":"/rltc/","pathPrefix":"","ajaxPageState":{"theme":"seven","theme_token":"l_FB7jWDCmNamBi4J7kqnOrggLfAI3b3oWvjYgjabko"},"states":{"#edit-style-options-flexslider-views-slideshow":{"visible":{":input[name=\u0022style_options[slideshow_type]\u0022]":{"value":"flexslider_views_slideshow"}}},"#edit-style-options-views-slideshow-cycle-timeout":{"visible":{":input[name=\u0022style_options[views_slideshow_cycle][transition_advanced]\u0022]":{"checked":true}}},"#edit-style-options-views-slideshow-cycle-speed":{"visible":{":input[name=\u0022style_options[views_slideshow_cycle][transition_advanced]\u0022]":{"checked":true}}},"#edit-style-options-views-slideshow-cycle-delay":{"visible":{":input[name=\u0022style_options[views_slideshow_cycle][transition_advanced]\u0022]":{"checked":true}}},"#edit-style-options-views-slideshow-cycle-sync":{"visible":{":input[name=\u0022style_options[views_slideshow_cycle][transition_advanced]\u0022]":{"checked":true}}},"#edit-style-options-views-slideshow-cycle-random":{"visible":{":input[name=\u0022style_options[views_slideshow_cycle][transition_advanced]\u0022]":{"checked":true}}},"#edit-style-options-views-slideshow-cycle-start-paused":{"visible":{":input[name=\u0022style_options[views_slideshow_cycle][action_advanced]\u0022]":{"checked":true}}},"#edit-style-options-views-slideshow-cycle-remember-slide":{"visible":{":input[name=\u0022style_options[views_slideshow_cycle][action_advanced]\u0022]":{"checked":true}}},"#edit-style-options-views-slideshow-cycle-remember-slide-days":{"visible":{":input[name=\u0022style_options[views_slideshow_cycle][action_advanced]\u0022]":{"checked":true},":input[name=\u0022style_options[views_slideshow_cycle][remember_slide]\u0022]":{"checked":true}}},"#edit-style-options-views-slideshow-cycle-pause-in-middle":{"visible":{":input[name=\u0022style_options[views_slideshow_cycle][transition_advanced]\u0022]":{"checked":true}}},"#edit-style-options-views-slideshow-cycle-pause-when-hidden":{"visible":{":input[name=\u0022style_options[views_slideshow_cycle][action_advanced]\u0022]":{"checked":true}}},"#edit-style-options-views-slideshow-cycle-pause-when-hidden-type":{"visible":{":input[name=\u0022style_options[views_slideshow_cycle][action_advanced]\u0022]":{"checked":true},":input[name=\u0022style_options[views_slideshow_cycle][pause_when_hidden]\u0022]":{"checked":true}}},"#edit-style-options-views-slideshow-cycle-nowrap":{"visible":{":input[name=\u0022style_options[views_slideshow_cycle][action_advanced]\u0022]":{"checked":true}}},"#edit-style-options-views-slideshow-cycle-fixed-height":{"vis

I have managed to resolve this, I managed to find it on google here : JQuery Update breaks Views UI  .

Basically if you go into your jquery Update module, click configure, then change it from 1.8 to 1.7 it works


Create a Display Suite Custom Block Field Programatically Can anyone provide sample code for a custom module and/or provide a reference for hook_ds_fields_info that utilizes 'field_type' => DS_FIELD_TYPE_BLOCK, that will actually render in admin/structure/ds/fields.  I'm working in 7.2-2.14 of display suite.

The API documentation appears to be incomplete as listed here:
http://www.drupalcontrib.org/api/drupal/contributions%21ds%21ds.api.php/function/hook_ds_fields_info/7.

I'm thinking I may be missing some sort of related render function for the block to appear (https://ohthehugemanatee.org/blog/2014/04/02/how-to-create-a-custom-display-suite-field/) however even using this example barebones in a standalone module I don't necessarily get my custom block to show.  I am referencing a custom block initially built out in a custom module.

function module_ds_fields_info($entity_type) {
  $fields = array();

  $fields['title'] = array(
    'title' => t('My Custom Module'),
    'field_type' => DS_FIELD_TYPE_BLOCK,
    'ui_limit' => array('article|*', 'audience_page|*', 'overview_page|*', 'page|*', 'product|*', 'product_overview|*'),
    'properties' => array(
      'block' => 'my_custom_module',
      'block_render' => DS_BLOCK_CONTENT,
    ),
  );

  return array('node' => $fields);

}

As already reported in this DS issue, you need to alter DS_BLOCK_CONTENT to DS_BLOCK_TEMPLATE.

We had a similar issue where from a certain point in time, the block was no longer rendered.
That point in time was a security update on the DS module, we applied somewhere a month ago :
https://www.drupal.org/sa-contrib-2018-019


What happens when multiple context conditions match? I have a multi-site setup using multiple contexts:

Context A
  Conditions:
    - Path:  <front>
  Reactions:
    - Block: sidebar-left

Context B
  Conditions:
    - Domain:  Domain1.com
    - Path:  <front>
  Reactions:
    - Block: sidebar-left

Context C
  Conditions:
    - Domain:  Domain2.com
    - Path:  <front>
  Reactions:
    - Block: sidebar-right

My goal is for the more specific contexts to match first (B,C), and for the general context (A) to match all other domains.

My problem is that Context A is always being matched first for Domain2.  Is there a way to define the "weight" of each context, and force Context C to evaluate before Context A?

Context starts from top and moves downward on all your created contexts and will stop on the first one to trigger it. This is why your context A is being displayed.

You have a few options...

Set a required condition to your context A as "Default Context" this way it will only trigger if no other contexts were found.
Make a few MAIN contexts that apply to many different cases for example, cache 1day, cache 5 days, cache 2hours, etc. The tag you can start with z_caches or something like that and put no conditions to these cache contexts, only the reactions. Note this will move them all the way down and you may think they will never apply... wait... now go to a main context for example, article_type and there you add a condition of "context (any or all)" and add the cache context you already created to that list. That way all article content types will automagically first add the context cache you want applied within this context. This way the page will stop on only one context, yet that one context contains multiple contexts within it. This is perhaps the best solution in most cases that need to apply multiple contexts or share conditions. Seeing your example, you can also create a "Domain" context like we did cache and apply it to whatever contexts you want and easily edit any of the included contexts without having to create so many different contexts since you are sharing some contexts that you know will be common. Cache, Http headers, delta (for theme layouts), domains, language, etc. These are all possible conditions that people may see themselves repeating on multiple contexts, but if you ever need to edit any of these, you have to go one by one to every context you added them and edit that field. However, if you use this method of sharing or including/excluding other contexts within your context, you only have to edit that one particular context that was included and will apply to all contexts referencing it.
Reorder your contexts in the order you want them triggered from top to bottom. The easy way to do this is by using the "clone" link when viewing all your contexts. Simply clone it and change the "tag" field (second field above the description) and you can start all your tags with numbers (like weights) and that will get the contexts in the order you need.

*NOTE: For point #2, you can use the "context all" or "context any" conditions to display or not display (not display using ~) any other contexts or the "context_disable_context" module which will allow you to select which contexts to omit.

In summary, using context is similar to using Path Breadcrumbs for example, in the sense that you have to plan ahead the hierarchy of importance from top to bottom of anything you create and know it will stop on the first item if true.

See your example, and you will see that in fact domain B and C when seeing context A, are in fact true, that is why it stops there (both domain B and C have a  page). If however, you follow my option #3 and reorder A to the bottom (B,C,A) and make all conditions of B & C required, any pages that do not specify the domain B or C will in fact trigger A.

The main difference between path breadcrumbs and context is that with path breadcrumbs you can drag and drop their weight order making things much easier. Here, you must find a way around that by altering your orders based on any of the methods i mention above. Not all will work in every case so i guess you just have to see which one works in your situation. I for example always have my path contexts above my content type contexts to ensure that the path if triggered has precedence over the content types and i use any conditions that are shared across multiple contexts by using method #2 i explain above.

I hope i made sense since i have not slept in over a day. At least it may be a good starting point :)


How do I grant permissions for translating block content? I used the Block Image module to create some content; now I want to give the site's editor the permission to translate the blocks, but I can't seem to find how I can do that. There's no permission to let a role be able to translate a block content.

How do I grant permissions for translating block content?

Block level permissions for administration is not provided in core. There is a module Block Access which provides block level permissions for admin interface.

  This module adds a set of global permissions for creating, viewing, moving, enabling, disabling and configuring blocks as well as permissions at the individual block level. These permissions only affect the admin interface, front-end view access is handled in core.

UPDATE:

Blocks are not content, so the permission to translate content won't help here. To be able to translate blocks you need to download Internationalization and Variable modules and enable the module Block languages [i18n_block] which ships with Internationalization module.


create link to download file I'm adapting a drupal module to my need. It permit to upload a pdf to insert it into a node add form in an iframe to display the file.
I've need also to insert a link to download the previous uploaded file.

I've read and try thousand of guide and documentation but nothing that work or adapt to my scope.

Is possible to find an easy way to create by code a download link?

It sounds like you're looking for the PDF Reader module.

  PDF Reader will render your entity file fields with the selected PDF
  renderer.

  The implemented PDF renderers are:

  Google Docs Viewer
  pdf.js - PDF Reader in JavaScript
  Direct PDF embed
  Microsoft Office Web Viewer(7.x-2.x-dev)

This module lets you specify any file field to render as a PDF embedded in a node. It also has an option to display download link for the embedded PDF.


Two step user approval after registration I'm new to Drupal, and need help on user registration.

A user registers on the site by filling in fields which include: name , DOB, users email(user1), password and official contact email address(ocea).
Once the form is submitted, an email goes to official contact email address(ocea). The user is approved once the administrator will give his consent.

How I can I achieve this? A module? Rules?

You don't need any third-party modules. Drupal core has the option to verify the email the user enters, and the option for the administrator user to approve the accounts users create. In Drupal 7, those settings are on /admin/config/people/accounts.

As for name, and date of birth, those are fields you can add to user accounts. In Drupal 7, those settings are on /admin/config/people/accounts/fields.


Redirect after submit form I use this code in my form ( buildForm(array $form, FormStateInterface $form_state) ) :

<?php

namespace Drupal\test\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\user\PrivateTempStoreFactory;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Session\SessionManager;
use Symfony\Component\HttpFoundation\Response;

class TestForm extends FormBase {

    public function getFormId() {
        return 'TESTOLDTONEW';
    }

    public function buildForm(array $form, FormStateInterface $form_state) {
        \Drupal::service('page_cache_kill_switch')->trigger();

    $a['ad_mail'] = [
        '#type' => 'email',
        '#title' => t('Email ID:'),
        '#required' => TRUE,
    ];
    $b['total'] = [
        '#type' => 'hidden',
        '#attributes' => [
            'id' => 'actionsubmitid',
        ],
        '#value' => '0',
    ];
    $c['actions']['submit'] = [
        '#type' => 'submit',
        '#value' => $this->t('Finalize the purchase'),
        '#button_type' => 'primary',
    ];
    $test= [
        '#theme' => 'test',
        '#a' => $a,
        '#b' => $b,
        '#c' => $c,
    ];

    return $test;
    }

    public function validateForm(array &$form, FormStateInterface $form_state) {

    }

    public function submitForm(array &$form, FormStateInterface $form_state) {
        $form_state->setRedirect('test.new');
    }

}

Now I want redirect to a machin name ( for example "test.new" ) that create in routing.yml file . I use $form_state->setRedirect('test.new'); in "submitForm(array &$form, FormStateInterface $form_state)" but not work .

EDITED :

.routing.yml

test.old:
  path: '/test/old'
  defaults:
    _form: '\Drupal\bpay\Form\TestoldForm'
  requirements:
    _permission: 'access content'

test.new:
  path: '/test/new'
  defaults:
    _controller: '\Drupal\bpay\Controller\TestnewController::new'
  requirements:
    _permission: 'access content'

The buildForm method needs to return $form. Not $test. You're missing key items by ignoring the $form variable. Properly set the form items (not as their own variable) and remove the custom theme hook you're trying to do. Cut this down to its simplest pieces first just to get it working and go from there.

Get rid of $a $b $c variables as that doesn't make any sense, just use $form. Your submit info is not making it into the form itself, which is why it isn't working.


Send Email upon Registration to Author of node I have searched and can not find anything similar.

I have a Rule, Event = send email after someone registers for an event.
I have the rule sending to the user just fine. However, I am trying to also email the Author of the page and I can find the correct replacement pattern.

I have an action Fetch Entity by ID Value=registration - DATA-Selector=registration:author:uid

I have tried many patterns:

[node:author:mail] mail - Nothing happens
[registration:author:uid] uid - give me the logged in user id
[registration:author:uid] reg-a-uid  (this give mne the id of the logged in user- not the author on the page.)
[node:author:uid] node-a-uid
[site:author:uid] site-a-uid
[registration:author] reg-author - show logged in user
[registration:author:mail] reg-author-mail - show logged in user

I am at a loss when trying to figure out how to pull the author of the node/page to email them.
Any ideas???
Thanks

[EDIT]

I was able to get the Author to print out.

author: [registration:entity:author]

Any ideas to pull the author first name, email and phone number???

Please any little thought would help.
Thanks

So after getting the base set I needed to connect to the table for the users profile information.

So for first name it would be:

[registration:entity:author:profile-main:field_first_name]

So for phone number it would be:(field_office is what they called the Office Phone field.)

[registration:entity:author:profile-main:field_office]

Hope it helps someone else.


Multistep Registration Form while googling and reading documentation and API, I've seen multiple solutions for "combining" 2 forms into one, and thus creating a multistep form.

What I want though, not even sure if it's doable, is to "split" my (huge) user registration form into 2 steps, where the value of one field (the only one in step 1) would determine which fields should show up in step 2.

I wouldn't like to drop the entire registration form and re-create it in code or in another way and somehow re-implement the whole user registration process. Is that possible?

EDIT: to avoid misunderstandings, what I need to do is an "actual" multistep form, with submitions between steps, and not some front-end handling. That is, I want the whole thing to be javascript independant.

EDIT2: to clarify even further, the task is figure out how/if possible to pretty much split any "edit" form to 2 parts. The current question does ask about the user/edit and/or user/register form specifically, but in order to come up with a more generalized solution, one might also want to split a node/edit form in to 2 parts. That's what I am really asking about. Splitting an entity/edit form in to 2 (or more) steps.

One way to do this would be to use the Conditional Fields module (disclaimer: noted as not ready for production for D7).  The way to do it with your own code would be to use the States API (the Conditional Fields module is just a GUI to States API, basically).

Using Conditional Fields, you can set it so that, for example, based on the value selected for Field A, a number of fields would be shown or not shown as per your requirements.

EDIT: To split the form into two steps, you can use the Field Group module, which provides a "multipage steps" feature.  To configure this, you will need to create a fieldgroup of type multipage for each page you want to have on the user registration form, and then place the appropriate fields under each page (on the user account manage fields screen).

Note: The Conditional Fields and Field Group module will display everything as one giant page if Javascript is disabled.  I don't know any way around this.


Is it possible for an administrator to delete pending user relationship requests (between users)? I am using the User Relationships module on Drupal 7.  I have a relationship, let's call it "Best friends," which requires the mutual approval of both users involved.  However, sometimes users send way too many requests, and I would like to delete these manually from an admin account.

I tried creating a view that shows all pending relationships of type Best friends and adding Status link as a field-- however, the Status link returns empty.  I also couldn't find any option to list user relationships on the admin screen.

Is there any way to quickly manually delete pending user relationship requests from an admin account?

No, there is no special administrative pages for managing other people's relationships, but this would be a useful feature.

Have a look at user_relationships_load in user_relationships.module. You could use that to create a list of all of the pending relationships site wide by passing in user_relationships_load(array('approved' => FALSE));. You can further filter that by passing in additional information such as the relationship type. UR's views integration doesn't really take an administrators needs into account but you could build this list with views as well.

Once you have that list you can generate delete links that call user_relationships_delete_relationship. Calling that function with the proper RID (relationship ID) will delete those pending relationships for you.

If you don't want to build an admin page to come back to, there is nothing wrong with doing a little clean up directly in the database as long as you're careful and back up everything first.