texts:
The issue is about page loading like the following ones:

Front page
Taxonomy pages (for instance, https://talash.by/taxonomy/term/33)
Any view pages in edit mode /admin/structure/views/view/block_content
Content list page /admin/content
User list page /admin/people

I have a message "The website encountered an unexpected error. Please try again later."

Apache log shows:

  Uncaught PHP Exception Drupal\Component\Plugin\Exception\PluginNotFoundException: "The "tag" plugin does not exist." at /var/www/site/public_html/core/lib/Drupal/Component/Plugin/Discovery/DiscoveryTrait.php line 52,

The issue happens even if I make a site copy (files and database) on the same physical server, but as different virtual server. Internal pages can be loaded (for example, https://talash.by/terms-of-use)

I am using Drupal 8.2.4 (standard) on Ubuntu 16.04, with PHP 7.0.8-0ubuntu0.16.04.3 (cli).

These are the non-core modules:

Media                Colorbox (colorbox)                               Module  Not installed  8.x-1.2

Other                Backup and Migrate (backup_migrate)               Module  Not installed  8.x-4.0-alpha1
Other                Colorbox Inline (colorbox_inline)                 Module  Not installed  8.x-1.0-rc2
Other                Disqus (disqus)                                   Module  Enabled        8.x-1.0-rc3
Other                Exclude node title (exclude_node_title)           Module  Not installed  8.x-1.0-beta1+7-dev
Other                Ultimate Cron (ultimate_cron)                     Module  Not installed  8.x-2.0-alpha1
Web services         HAL (hal)
Bootstrap            Bootstrap (bootstrap)
Theme   Enabled        8.x-3.1
Bootstrap            Bootstrap Clean Blog (bootstrap_clean_blog)
Theme   Enabled        8.x-1.0-rc2


texts: How to specify a Rules event like "Content is 'going to be' viewed"?

texts:
To answer the question about "How to restrict access to a node via node/12 and allow access via a path like content/sometitle?", I thought it should be possible to use the Rules module to do so.

I was thinking about a rule as in this exported rule (which has "Content is viewed" as event):

{ "rules_disallow_using_urls_like_node_123" : {
    "LABEL" : "Disallow using URLs like node\/123",
    "PLUGIN" : "reaction rule",
    "ACTIVE" : false,
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_view" : [] },
    "IF" : [
      { "data_is" : { "data" : [ "site:current-page:path" ], "value" : "node\/[node:nid]" } }
    ],
    "DO" : [
      { "redirect" : { "url" : "no_access" } },
      { "drupal_message" : { "message" : "Sorry, URLs like node\/[node:nid] are not allowed around here ..." } }
    ]
  }
}

Here is the challenge (and my actual question): for any node you visit, and even when visiting nodes using the path of such nodes, the rules action always gets executed. That makes me wonder how I can rework that "Content is viewed" event into something like "Content is 'going to be' viewed", so before Drupal is actually going to display the requested node? And this without writing a custom module.

To better explain the 'going to be'-part of it: compare it to the Content Access" module: if you try to visit a page for which content access is set so that you do NOT have permission to (e.g.) view it, then Drupal will FIRST check via content access if you do have access to it, then decides you have no permission, and then you will NOT actually be able to "view" that page (even though you asked for it). So that "will FIRST check" is similar to "going to be" ...

I also looked at the (unasnwered) question about "I cannot see the Rules event "Page is going to be viewed"", in which one of its comments points to issue nr 514824 (which is for D6). And in that issue there is Fago's comment #8 like so:

  Use the "Content is being viewed" event when you need the node.

Assuming that was available (and working as such) in D6, what is the D7 equivalent of this event, if any? Because, obviously, my sample above seems to indicate that in D7 it doesn't work like that anymore.

Note: The exported source above is intentionally DISABLED, because if you'd want to import it and enable it, then it is always going to get triggered for ANY node you view. Only URLs starting with (eg) /user or /admin will not satisfy the Event in this rule (so that at least you can disable this rule again to be able to view /node paths also again).


texts: Adding specific node field content in panels

texts:
For a better understanding, I will try to explain my problem with a concrete example. I know that I probably should achieve this a different way but I've been working like this for a lot of websites I've made and it's the cleanest and effective way (at least for me) to do this.

I have a content type which contains a few fields.
I'm using a few mini-panels as a block to place contents from nodes of the content type mentioned above
In those mini-panels, I often have to display only a specific field from a specific node

The problem is that when I click to add content in my pane and select "existing node", I'm only allowed to show the entire node content with a specific build mode.

All I want is to add a field content of a specific node I've created. Not the whole node.

At the moment, I have to use display suite and add a new display and then, only display the specific field in this newly created display and then finally add "existing node" / select the specific node / select the template I've created with display suite which contains only the one field...

It's very tedious ! Is there a way to only select one field ? Or do you have advice on how to achieve this ?

Thank you.


texts: Content Strategy: Similar but unique content

texts:
I am building a Drupal 7 site and need some help with my content strategy.  One type of content I regularly work with are workshop/conference pages.  Each workshop/conference may have one or more of the following (proposed content type in parens)

The workshop/conference (book page)

About (basic page)
Registration (webform)
Schedule (basic page)
Lodging information (basic page)
Transportation information (basic page)

The main benefit of this approach: we'll use a Book Navigation Block to have a menu for each workshop/conference sub-page.

However, I see several disadvantages:

Two different workshops/conferences may require unique "Lodging Information" pages.  Drupal won't let me title two different pages "Lodging Information" even though each belongs to a separate book.  I could name each specifically, like

"Lodging Information Conference FOO 2013"
"Lodging Information Conference BAR 2013"
"Lodging information Conference BAZ 2013"

Thinking long-term. . . Let's say in the future our site documents dozens/hundreds of workshops/conferences.  The drop-down to select Book parent pages could get excessively long.  If we don't stick with a good naming convention, this could be a bit overwhelming for content contributors.
I don't like the Book navigation helpers near the footer of every parent/child page (table of contents on parent, previous/up/next buttons on all children pages).  Editing the core Book module seems like overkill to remove this functionality.  Perhaps there's a better way?

Using the Book Module brings up more questions than answers.  Is a the Book Module the best approach to implementing a workshop/conference page?


texts: How to get nodes with term programmatically

texts:
I have Vocabulary and Custom Content Type which has field Term reference.

How can I get all nodes of particular term in my module?

Something like this? This doesn't work.

$field = field_info_field('field_game');
$results = new EntityFieldQuery;
$results->fieldCondition($field, 'field_game_tid', '5')
  ->execute();

$nids = array();
foreach($results as $result) {
  $nids[] = $result->nid;
}

$nodes = node_load_multiple($nids);


texts: Drupal.settings.basePath is not giving the base_url in js

texts:
When I alerted the Drupal.settings.basePath it's just giving me a /. I have a full $base_url in settings.php. which I'm expecting to see instead of /.

How can I get the correct value of the base URL in javascript?


texts: Language Manager getCurrentLanguage returns default language instead

texts:
I am creating a multilingual D8 site, which 3 languages enabled.

In trying to display the currently active language, the snippet

$lang = \Drupal::languageManager()->getCurrentLanguage()->getName();

always returns the default language ( English ) even though the UI has switched to one of the alternative languages. The above line is called from the mytheme.theme file in hook_preprocess_page.

In the language switcher block, the correct language is getting the session-active is-active classes.

When referencing the documentation for D8.5 in the above method, in the code shown it very much shows like this is what the function does:

public function getCurrentLanguage($type = LanguageInterface::TYPE_INTERFACE)
{
  return $this
    ->getDefaultLanguage();
}

Am I missing something obvious here? Is there another way to get the current active language?


texts: schema_fields_sql empty on entity_get_info

texts:
I'm trying to debug why Drupal Commerce License Billing isn't working on existing install but works fine on fresh install.

The difference I can see between the two when adding a new billing type is after entity_get_info is ran (after saving a new type) the clean install has two array elements complete the existing install does not.

Those two elements are "base table field types" and "schema_fields_sql".

So for some reason those elements aren't set in the existing install.

Any ideas why those elements wouldn't be populated or where they are set so I can further debug?

Thanks


texts: Why Form Api behaves differently in route and in custom block?

texts:
I’ve encountered this issue several time and I don’t know why. I know this not so easy to reproduce but maybe someone has an explanation.

I’ve built several custom modules which return datas from Rest APIs (I use controller, not Form). These modules are in custom block (define in src/Plugin/Block/HelloBlock.php) They all work well.

When I made a custom module with Form API that allow user to select a range of date and return a pdf file, I had a weird  bug : pdf file is downloaded but it is always empty (0 ko).

If I display  the form with a route (defined in module.routing.yml), then it works.

Do you know why Form Api behaves differently in route and in custom block ?

Code for block:

class WebservicesTestBlock extends BlockBase {

    public function build() {

        $form = \Drupal::formBuilder()->getForm('Drupal\webservices_test\Form\WebservicesTestForm');
        return $form;

    }

}

And in form :

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

        // here is the code that returns pdf datas from rest api
        // I've omitted this part because it is working
        // The PDF datas is in $test->body

        header("Content-Type: application/pdf");
        header("Content-Disposition: attachment; filename=test.pdf");
        header('Content-Transfer-Encoding: binary');
        //header("Cache-Control", "max-age=0");
        header('Accept-Ranges: bytes');
        ob_clean();
        flush();
        echo ($test->body);
        exit;

    }


texts:
Is there a way to render a node with view mode via token? Like:

[node:5:teaser]


texts: Do not want  HTML tag when using footer region

texts:
After running W3 Markup Validator on a site of mine, I received the following error:

Line 219, Column 57: element "footer" undefined
<footer id="footer" class="region region-footer">

Whether or not this is actually an issue, bad style, or what, I've decided that I don't want Drupal using the HTML footer tag. Is there a way that I can change this and have it just create yet another div?


texts: What causes menu to stop querying for children half way through menu

texts:
I have a 'primary menu', rendered in one case using the 'bartik' theme (site preview)  and rendered in the other using the 'Bootstrap' theme. (site preview)

With the bootstrap theme, working from left to right the children are presented until 'Publications'. Then there are no children. The same menu presents all the children in Bartik all the way across. Looking through it, the children are not in the php data ($element[#below]) and are not printed out to the HTML.

What is causing this?


texts: Access image field URL in a custom block

texts:
I need to have an easily exposed to user background image in an aera (header).
So i made a custom block with an image field and i want to use this picture in a classical <div style="background....
So I need the URL of the file and of course not the rendered file.

Since two days i'm searching a way to do that without success. And twig debug activated do not help.
I'v tried the image_url_formatter module (doesn't work with twig debug active)
I've found this:

{{ file_url(content.field_header_background['#items'].entity.uri.getValue()) }}

But it only giving me the root folder (by de file_url function i think) the part:

content.field_header_background['#items'].entity.uri.getValue()

is empty.

I have heard about preprocess function (on block, filed ?) but i don't know how to do it.

Is anyone can help me ?


texts: Is there a way to for a site builder to make sure context-teaser is used in "Teaser" mode when an atom is in rich text?

texts:
In Scald, when an atom reference field is inserted into a node, the site builder can specify the context per view mode (i.e. the "Full page" context as "default" and a "Teaser" context for the "teaser" view mode). So far, so good.

However, when not using atom reference fields, but instead using WYSIWYG where the author "drag'n'drop" the atom into rich text, the context and alignment are chosen by the author. E.g. the author may pick context-full and atom-align-center. These choices are made part of the SAS and in appears various places in the render array for the body/node.  If you inspect the render array, you find that the SAS may look like this (where "XXXX" is the atom's sid):

[scald=XXXX:full {"link":""}]

Now, I think it is just fine that Scald empowers the author to set the context and alignement for the default view mode for the atom.

However, out of the box, the default context set by the author is used in all view modes, including "teaser".  I have not yet found a simple way for the site builder to indicate that a different context (e.g. context-teaser) and alignment (e.g. atom-align-right) shall be used in the "teaser" view mode.

I have been able to think of some workarounds:

the author is required to create a "Summary" by hand and to select the "teaser" context for the summary.
A preprocess function is set up to rewrite the SAS to use context-teaser, etc. if the view_mode is "teaser".
Don't use WYSIWYG for atoms (instead, use a unlimited field to hold Atom references).

However, I don't like these workarounds.  I don't want to burden the author with creating a summary for every node. Such a massive rewrites of the render array is hackish and fragile. Not having atoms is WYSIWYG is just not acceptable for some of my users.  The way I see it, these workarounds is not really usable.

Can anyone think of a usable way to for site builders using Scald for media management to control the context of all aggregate renderings of nodes, while still having context and alignment under the author's control (i.e. in WYSIWYG)  for the full page view mode?


texts: How to trigger/run/execute scheduled task manually?

texts:
Is there a way to run a scheduled task manually without any programming?

If not, this way seems not to work properly Manual execution of scheduled rule.
After executing a rule, having another one on the list, clearing caches and running the cron, this feature automatically disappears somehow. There is something wrong in the code.


texts: Creating a view with a dynamic link from taxonomy term

texts:
Trying to create a view block with a list of five links

Event Details (dynamic)
Cause (dyanmic)
Sponsors (statis)
Volunteer (static)
Register (static)

Dynamic url will look like this:

/events/golf-tournament/[year]/[taxonomy-term]/event-details

/events/golf-tournament/[year]/[taxonomy-term]/cause

I am not able to format the taxonomy term to use it in the url

Taxonomy term prints as: The William Dennis Memorial Golf Tournament (with capitals and spaces)

View looks like this:

** Solution **
*  Not sure if this is the 'right' way *

Added contextual filter for: Content: has taxonomy term ID

But it doesn't appear to use the taxonomy term....so really I providing a value from the url

Then I messed around with tokens, first trying [token_taxonomy_term] <--- not actual token; %1 and !1 <---- all of these exist in the available Replacement Patterns

Here is the rewrite I used to rewrite the url for 'cause'

Cause


texts: Sort a view by price using commerce price?

texts:
I have a custom view (created with Views) that is working fine. But when I add a price field to it and sort the view with same field in descending or ascending order, it is not working.

Any suggestions to get this to work?


texts:
I have a content type teaser with an image field and display these teaser in a panel layout. This works perfect if I choose the Build Mode "Full Content" in the Panel Settings for the content.

I themed the content type with a node template (node--xyz.tpl.php) and have no checks about the view_mode in it. I print out the image with the function render():

<?php print render($content['field_teaser_image']); ?>

I'm very confused, as I wrote above, with the Build Mode "Full Content" it works fine. I've checked the Manage Displays Settings and they are the same for both View Modes. The Variable in the render() function is filled in both cases, but in View Mode "Teaser", the output is empty.


texts: How to define the site to be used in BrowserTestBase on a multisite?

texts:
I am working on a multi site where there is no database defined in the default directory, so whenever I run a Functional test extending BrowserTestBase I get the following error:

copy(/var/www/drupal-int/docroot/sites/default/default.settings.php): failed to open stream: No such file or directory

I'm not really sure why the files were removed in the first place and I don't want to add them back in there in case there was a good reason for removing them. Is there a way to define the site to use for the test?

My simple test:

<?php

namespace Drupal\Tests\my_module\Functional;

use Drupal\Core\Url;
use Drupal\Tests\BrowserTestBase;

/**
 * Simple test to ensure that main page loads with module enabled.
 *
 * @group dnsw_scheduler_workbench_integration
 */
class LoadTest extends BrowserTestBase {

  /**
   * Modules to enable.
   *
   * @var array
   */
  public static $modules = ['my_module'];

  /**
   * A user with permission to administer site configuration.
   *
   * @var \Drupal\user\UserInterface
   */
  protected $user;

  /**
   * {@inheritdoc}
   */
  protected function setUp() {
    parent::setUp();
    $this->user = $this->drupalCreateUser(['administer site configuration']);
    $this->drupalLogin($this->user);
  }

  /**
   * Tests that the home page loads with a 200 response.
   */
  public function testLoad() {
    $this->drupalGet(Url::fromRoute('<front>'));
    $this->assertResponse(200);
  }

}


texts: How to debug / log comments when developing a custom module to fire when cron is run

texts:
I am about to develop a custom module that will hook into a hook that is triggered when cron runs. Since the module will be activated during a cron run, i am not sure how to go about giving myself feedback as I develop. If I was working with javascript I could use console.log(myvar) to log information about variables etc.

If I was developing a module that ran on a page I could use the devel module and use dpm() in my module code.

However since this module will run with cron, dpm() doesn't seem like the best way of doing this.

From searching around I see that watchdog('error title', 'error message'); could have been a good way of doing this in Drupal 6.

What is the Drupal 7 way of logging messages during custom module development?


texts: How to access same name table fields in table join using db_fetch_object

texts:
I've SNO in both A and B tables.

I do

db_query('SELECT * from A JOIN B on A.SNO=B.SNO')

Now how do I access both SNO fields of A and B using db_fetch_object?


texts: Programmatically set property based on other properties in a custom entity

texts:
I created a custom entity and want to programmatically set the title based on 2 other properties.

For example, the entity has year and state properties. When the entity is created, I want to populate the title property with year state.

How can I achieve this?


texts: How to select author/creator field of CRM-Core Contact and Activity in views?

texts:
I'm building a view for CRM-Core Contact, but I can't find the author/creator field from the Add Fields list.

I have checked the database table, there IS a column uid:

  The users.uid that owns this contact; initially, this is the user that created it.

Any idea about this?

And there are no permissions like Edit own Contacts, only permissions like Edit any Contact. Is it designed on purpose?


texts: Displaying content based on the field value

texts: I have a view that displays my content of a specific content type that has a image field. I also have a check box field for that content type. My requirement is that i need the content that has the checkbox checked to be displayed at the top of the list in the view. Could someone tell me how to achieve it?


texts:
Possible Duplicate:
  Listing entity fields

Is there a function or technique anywhere in the Drupal API to list fields for a particular content type?


texts: How can I send an email using the Rules module to a user specified via Entity Reference in a Content Type?

texts:
This question is similar to others posed, but all the answers I can find appear to refer to Drupal 6, with CCK fields.

I am using Drupal 7 with the Rules module enabled.

I have created a custom Content Type and one of the fields is an Entity Reference, which allows a registered user to be selected as the Content Type is added. Essentially an administrator can associate a registered website user with the content item being added.

I need to email the referenced user when another field value within the Content Type is changed. I'm sure this is possible via the Rules module, but I cannot get the mail to send.

It must be a fairly common situation, emailing a referenced user when a field value is updated, but I have looked at the online notes for the Rules module and cannot find an example of this particular use case.

Has anybody managed to achieve the same outcome as I am seeking?

Thank you.


texts: How can I create a Views field template per display?

texts:
I successfully could create a template file for views field after reading this page.

https://api.drupal.org/api/views/theme!theme.inc/group/views_templates/6

However views-view-fields--myviewsname.tpl.php override all the displays in "myviewsname"

Is there any way I can make a template that overrides just one display in a View?

For example, a template that overrides just "display-1" in "myviewsname"


texts: Use "date_views_filter_handler" filter handler for custom table field

texts: How can I use "date_views_filter_handler" defined in date module as filter handler for a column of integer type on custom table while exposing it to views.


texts:
I am creating a form and I would like to create an unordered list of links. My problem is that I don't know how to go about this. I didn't see anything in the forms API about accomplishing this. What is the correct procedure to produce an unordered list?

Thanks.


texts: Am working with drupal search api solr module am trying to get it to work with the OR Operator so if i do a search for "David Smith" it should show results for both "David" and "Smith" does anyone have ideas on how to achieve this


texts: hook_form_alter to limit user select list to those referenced in a node

texts:
I have a content type called Project. I am linking users to this content type through several user reference fields.

I am also creating related Events (another content type) related to the Project content type pages through the Node Reference URL Widget.

So far so good, but...

In the Event content type I would like to add Attendees, through another user reference field, and limit the list of users to only those referenced in the original Project page. First I tried using a view, but I couldn't find the proper arguments / filters / relationships. Now I am trying through a custom module with hook_form_alter.

Could I get some advice on an efficient way to do this? Any ideas would be greatly appreciated.

EDIT:
I have been working on this, and it seems I am almost there, but not quite. Bare with me as this is my first custom module and my php skills are quite basic. My structure (content type > fields) is as follows:

Project:

field_users (entity reference)

Event

field_project (entity reference, prepopulated from Project on event
creation)
field_attendees (entity reference)

Then, in a custom module, I added the following code to modify the Event content type form:

<?php
function mymodule_form_alter(&$form, $form_state, $form_id) {
  if ($form_id == 'project_event_node_form') {
    $id_project=var_export( $form['field_project']['und']['#default_value'][0], TRUE );
    $project = node_load($id_project);
    $user_ref = array();
    foreach($project->field_users as $u){
      $user_ref[] = $u;
    }
    $form['field_attendees']['#options'] = $user_ref;
  }
}

But I still see all users, not just those referenced in the Project. Strangely enough, if I do:
dpm($user_ref);
I get this array, which contains the ids of the users I want to be able to choose from:

array (
  0 =>
  array (
    0 =>
    array (
      'target_id' => '7',
    ),
    1 =>
    array (
      'target_id' => '8',
    ),
    2 =>
    array (
      'target_id' => '9',
    ),
    3 =>
    array (
      'target_id' => '10',
    ),
  ),
)

But somehow I fail to pass that as the options for field_attendees. Any ideas?


texts: PreExistingConfigException: Configuration objects provided by progweb_migration already exist in active

texts:
I'm playing with migrations from D7 to D8 and I've found that, when you register a module with a migration, if you disable it, next time you enable the module gets stuck on this:

[vagrant@devbox] /[...]/default $ drush en progweb_migration -y
PHP Warning:  Module 'imagick' already loaded in Unknown on line 0
PHP Warning:  Module 'imagick' already loaded in Unknown on line 0
The following extensions will be enabled: progweb_migration
Do you really want to continue? (y/n): y
exception 'Drupal\Core\Config\PreExistingConfigException' with message 'Configuration objects[error]
(migrate.migration.custom_user) provided by progweb_migration already exist in active
configuration' in /www/drupal8/core/lib/Drupal/Core/Config/PreExistingConfigException.php:70
Stack trace:
#0 /www/drupal8/core/lib/Drupal/Core/Extension/ModuleInstaller.php(162):
Drupal\Core\Config\PreExistingConfigException::create('progweb_migrati...', Array)
#1 /opt/drush7/vendor/drush/drush/commands/core/drupal/environment.inc(129):
Drupal\Core\Extension\ModuleInstaller->install(Array, true)
#2 /opt/drush7/vendor/drush/drush/commands/core/drupal/environment.inc(196):
drush_module_install(Array)
#3 /opt/drush7/vendor/drush/drush/commands/pm/pm.drush.inc(1120): drush_module_enable(Array)
#4 [internal function]: drush_pm_enable('progweb_migrati...')
#5 /opt/drush7/vendor/drush/drush/includes/command.inc(359):
call_user_func_array('drush_pm_enable', Array)
#6 /opt/drush7/vendor/drush/drush/includes/command.inc(210): _drush_invoke_hooks(Array,
Array)
#7 [internal function]: drush_command('progweb_migrati...')
#8 /opt/drush7/vendor/drush/drush/includes/command.inc(178):
call_user_func_array('drush_command', Array)
#9 /opt/drush7/vendor/drush/drush/lib/Drush/Boot/DrupalBoot.php(46): drush_dispatch(Array)
#10 /opt/drush7/vendor/drush/drush/drush.php(76):
Drush\Boot\DrupalBoot->bootstrap_and_dispatch()
#11 /opt/drush7/vendor/drush/drush/drush.php(16): drush_main()
#12 {main}

It's like the migration is being registered but not de-registered. In D7 there is a method for that, but no luck so far trying in D8:

function progweb_migration_enable() {
  Migration::registerMigration('custom_user');
  Migration::registerMigration('custom_blog');

  Migration::registerMigration('ProgwebBlog');
  Migration::registerMigration('ProgwebUser');
}

function progweb_migration_disable() {
  Migration::deregisterMigration('custom_user');
  Migration::registerMigration('custom_blog');

  Migration::deregisterMigration('ProgwebBlog');
  Migration::registerMigration('ProgwebUser');

}

Any ideas?


texts:
I can't add a form to a node. Using the following code, the generated HTML show only the node. If I return $form, the form is rendered correctly. What is my mistake ?

function hook_menu() {

$items['presse/rss'] = array(

'title' => 'RSS',
'access callback' => TRUE,
'page callback' => 'press_rss_page',
'page arguments' => array('fr'),
'menu_name' => 'nav-fast-links-fr',
'file' => 'press.rss.inc',
'type' => MENU_NORMAL_ITEM,

);

FILE: press.rss.inc

function press_rss_page($lang) {

     $nid = variable_get('press_rss_nid_' . $lang, 0);
     $page = array();
     if ($nid) {
        $page = node_view(node_load($nid));
     }

     $path = $_SERVER['HTTP_HOST'];
     $path .= $lang == 'fr' ? '/presse/rss/' : '/press/rss/';
     $form['#weight'] = 1000;
     $form['container'] = array(
        '#prefix' => '
',
        '#suffix' => '
',
     );

     $form['container']['all']['title'] = array(
        '#markup' => '
' . 'All the press room content' . '
',
         );
     $form['container']['all']['text'] = array(
        '#type' => 'textfield',
        '#title' => t('All the feeds', array(), array('context' => 'frontend')),
        '#value' => $path . 'all',
        '#disabled' => TRUE,
        '#id' => 'rss-1',
        '#attributes' => array(
        'onClick' => "this.select();",
        'readonly' => 'readonly',
),

);

  $page['form'] = $form;

   return $page;

}


texts: How to redirect all 404s to the same path on a different server

texts:
I want to redirect all 404 errors on my site to the same path on a different server.

For example:

http://drupal.example.com/url/not/in/drupal should be redirected to http://othersite.example.com/url/not/in/drupal

The sites are not on the same server and the other site is not running Drupal.

I know I can use the redirect module to redirect specific URLs but I don't have a complete list of the URLs on the other site so building the list is not practical.

Suggestions for modules or pointers to the appropriate hooks if I want to write my own module would be appreciated.


texts: Does node_delete() delete node_revision and comment as well?

texts:
I want to delete the node_revisions and comments with node_delete().
Is this possible, or do I need to write custom code?


texts: Add a jQuery hover effect to images in a View

texts:
I would like to add a jQuery hover effect to a view of thumbnail images (the content type consists of an image field). The effect that I would like to add can be seen here:

  Code: http://www.freshdesignweb.com/responsive-portfolio-gallery-with-jquery-tutorial.html
  Example: http://elegantthemes.com/preview/Evolution/

It consists of an overlay that appears when the user hovers on an image. I would like the overlay to have links to the image itself (so the user can comment) and to open a larger version of the image in a lightbox.

I just cannot find an easy tutorial to add this. Anyone with good suggestions? Or with some time to show me the steps to implementing such an effect?

Thanks!


texts: How to create a Custom Drupal 8 Content Entitiy? - Baby steps edition

texts:
There are already some resources describing how to write a custom content entity for Drupal 8. Perhaps the most useful one is the one included in the Examples module.

However I'd like a super-basic example that introduces Drupal 8 and PHP5 OOP concepts step-by-step,  without throwing me in the deep end.


texts:
I've been following instructions on the web on creating a new service, but I can't seem to get it to work.

In my controller:

namespace Drupal\mymodule\Controller;

use Drupal\Core\Controller\ControllerBase;

class MyController extends ControllerBase {
  public function myroute() {
      $db = \Drupal::service('mymodule.db');
      return array('DEBUG');
  }
}

In my mymodule.services.yml:

services:
  mymodule.db:
    class: Drupal\mymodule\mymoduleDB

In my service class:

namespace Drupal\mymodule;

class mymoduleDB {
  public function dosomething() {
    return 'data...';
  }
}

In my controller, when I comment out the line that calls \Drupal::service, then the controller works, so it's an issue with calling the service.

I'm getting a HTTP 500 error.


texts:
I have a page in Drupal from which I want to be able to read the $_SESSION data to determine the userid and their assigned role. As an exploration I attempted to print to the page the contents of $_SESSION so that I could see what was being stored and what the keys were to retrieve these values.

When I attempt to print to the page using echo print_r($_SESSION);, instead of a set of reasonable session data, I instead get only this:

Array ( [batches] => Array ( [1] => 1 ) )

I had a bit of a Google around to see if I was doing something wrong, and I came across the documentation for session.inc, which says:

  These functions should not be called directly. Session data should instead be accessed via the $_SESSION superglobal.

So it seems that, while Drupal wants me to use $_SESSION to retrieve the session data, I can't do this because my $_SESSION data has only this odd pair of nested one-element arrays that store only the number 1.

I also came across some reports that not having the uid 0 in your users table can cause similar issues, so I have checked the users table and I do indeed have user 0.

Any ideas what is going wrong here?

Thanks.


texts: Add a Canvas Form Control in Drupal Custom Module

texts:
Im currently developing a module and I have this code in html:

<canvas id="cnv" name="cnv" width="500" height="100"></canvas>

I want it to add in my page using form controls but when I scan through Form API Reference, there's no canvas form control available. How to make it possible in Drupal? Any idea?


texts: Javascript "once is not a function" errors after library include

texts:
I have a small module which contains the javascript library JSmol. This library renders molecular structures onscreen.
The main module is called jmol. It contains an element, a twig template, a small javascript file, and the official JSmol library.

When I create an element on the page the element renders correctly, but the admin toolbar does not. Javascript console highlights 4 places that the "once" function is used, all in the code after the vendor library was included. One example is this:

TypeError: $(...).once is not a function

  Drupal.behaviors.escapeAdmin = {
    attach: function () {
      var $toolbarEscape = $('[data-toolbar-escape-admin]').once('escapeAdmin');

my javascript file is quite simple:

(function ($, Drupal, drupalSettings, Jmol) {
  'use strict';
  Drupal.behaviors.jmol = {
    attach: function () {
      var Info = drupalSettings.jmol.mydiv.info;
      $('#mydiv').html(Jmol.getAppletHtml("jmolApplet0", Info))
    }
  };
}(jQuery, Drupal, drupalSettings, Jmol));

Is it possible that the vendor code breaks this, or is it something that I have done?

Edit: here's my jmol.libraries.yml file:

jmol:
  version: 1.x
  js:
    lib/JSmol.min.js: {}
    js/jmol.js: {}
  dependencies:
    - core/drupalSettings
    - core/jquery
    - [I've tried adding core/jquery.once here to no avail]


texts: How do I submit a user registration form in code?

texts:
I have tried to save registration data in a controller.

$values = \Drupal::request()->request->all();

     $formBuilder = \Drupal::service('entity.form_builder');
     $form = $formBuilder->getForm(User::create(array()), 'register', array());
    $formObject = new RegisterForm(\Drupal::entityManager(),
                    \Drupal::languageManager(), \Drupal::service('entity.query'));

     $form_state = (new FormState())->setValues($values);
                //$formObject->form($form,$form_state);
     $entity = $formObject->buildEntity($form,$form_state);
     $formObject->setEntity($entity);
     $formObject->form($form,$form_state);
     $formObject->submitForm($form,$form_state);
     $formObject->save($form,$form_state);

Above code produces this error:

  Fatal error: __clone method called on non-object in /home/vagrant/www/drupal8/drupal-8.0.1/core/lib/Drupal/Core/Entity/EntityForm.php on line

It seems I need to inject an "entity" before buildEntity().

How did Drupal 8 manage to create a new user? Maybe the container injected that entity some where, but I am unable to find it.


texts: Update user profile after form submitted

texts:
I'm trying to compute a user profile field using values submitted in a custom user profile edit form.  I know that the callback is firing, but it won't set the new value in the field.  I've tried every incantation I could think of to set it (right now I'm just trying to flat out set it, never mind the calculation).  To debug it, I've tried putting a print_r statement in the callback for both $form and $form_state, but it doesn't print anything.

What's the right syntax?  Or is it a bigger problem because it's the user profile, or because I'm mixing a module and a .tpl, or something entirely different?  The other form fields are all being set as expected.

This is Drupal 7, btw.

My code, way simplified:

In template.php:

function my_theme_theme() {
    return array(
        'user_profile_form' => array(
        'arguments' => array('form' => NULL),
        'render element' => 'form',
        'template' => 'templates/user-profile-edit'
    ),
  );
}

In my_module.module:

function my_module_form_alter(&$form, &$form_state, $form_id) {
    if ($form_id == 'user_profile_form') {
    $form['#submit'][] = 'my_module_compute_values';
}
}
function my_module_compute_values (&$form, &$form_state) {
$form_state['field_age']=300;
}


texts: Locating the source of Forbidden message

texts:
When I login I see these "Forbidden" messages. How to track the source of this message?

Also I've enabled these settings:

error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);


texts: Drupal Commerce - Line Item 'display path' from views

texts:
How is the 'display path' is built when the Cart view is rendered?
Why would it not be rendering some display path URLs?

I'm using a modified version commerce_add_to_cart_extras module whereby I'm trying to link the line item to the product display node by customizing the display path. I can see it being added correctly when I inspect the $line_item object in save function of CommerceLineItemEntityController. But the line items in my cart still aren't linked and when I output the display path as a field in the view, it's empty.

If it would help, I can add the debug print I captured via devel's dd() function of the $line_item or my code but they will make the post rather long so I've left them out for now.


texts: Unable to create a view of type solr search

texts:
I have installed the apachesolr , views and apachesolr_views modules but I am unable to create a view of type solr search.
Is there something i am missing? Because the apachesolr_views provides views integration of apachesolr.

Any Help?


texts: how to implement Ajax callback on form_alter for entity field?

texts:
EDITED: I am able to display image for a field dropdown which have entity reference values to another content type. That is when a node content is edited or created.

Note: I'm not creating form elements I'm using them.

For a content type I have a field_select dropdown list (entity reference to another content type). I am trying to alter my form, to display the images of the selected entity from dropdown.

I'm new to the ajax callback functions, and need a little help here. I have a searched a lot and succeeded a bit.

output of my dsm($form):

$form => array (
['field_select'] => array (
  ['und'] => array (
    ['#options'] => array (
      [_none] => -None-
        [1] => content1 //1 is key
        [2] => content2 //2 is key
        [3] => content3 //3 is key
      )
    )
  )
)

Present ISSUE: When the below drop down is selected to a value of above, Image is being displayed in the dummy field below, but only once. For example if I select 1 (content1) the it renders image from node 1 according to the ajax callback function [success]. But now if I select 2 its not loading image from node2, instead it shows only node1 image which was rendered first.

function custom_form_alter(&$form, &$form_state, $form_id){

 if ($form_id == "article_node_form"){
   $form['field_select']['und']['#ajax'] = array(
     'callback' => 'field_select_ajax_callback',
     'wrapper' => 'another-field-select-image',
   );
   $form['field_select']['und']['#prefix'] = '
';
   $form['field_select']['und']['#suffix'] = '
';

}

function field_select_ajax_callback($form, $form_state) {
  $id = $form_state['values']['field_select']['und'][0]['target_id']; //node id
  $node_id = node_load($id);

  if(is_object($node_id)) {
    $image_uri = $node_id->field_image['und'][0]['uri'];
    $image_url = file_create_url($image_uri);
    $image = '';
  }
  return $image;
}

I want to display respective selected dropdown image near to field-select


texts: How to add css class to individual  list items of field list output from a View? (looking for base template code to customise)

texts:
How do I style list items of a field output from a View.

By this I don't mean styling the overall list items that a view outputs but I mean the items of a list field in each of the content output.

To try to explain my question further:

I have a content type which has a list as one of the fields
content has being created using this content type
a view has been created to list each instance of the content
each content shows its list field, I have set this to output as an unordered list
I want to apply a CSS class to each of the list field of each of the content

In the Views 'configurator' ( admin/structure/views/(myview) ) pages, it allows adding CSS classes to wrapper markup and the fields of the output. However, it doesn't allow for applying classes the individual items of fields which are list items, i.e. the li html of each item of the list for a field which is a list.

I'm happy to do this in a template file for my theme, but have already attempted to create a .tpl file using information from "Theme: Information" in the View 'configurator' page (under the OTHER heading). There are many suggestions shown here but not all the base code .tpl files (for copying into your own theme and customising) are provided in the theme folder of the views module.


texts: hide field based on its value or value of another hidden field

texts:
I need to hide a radio button field of a content type (not a form) only on the edit view based either on its own value or based on the value of another field that is already hidden.

Dependencies does not work,  I think because the other field is already hidden and because it does not allow the dependent and dependee field to be the same field.

Any ideas?


texts: how to call/using geofield in a custom module

texts:
I`m trying to use the geofield module, and load it with google maps widget in one my custom forms.

Yet i can't find any way to use the form api to display this field.

$form['geofield'] = array(
'#title' => 'geofield',
'#type' => 'geofield',
);

Any suggestion is welcome, i don't mind reading some docs.


texts: I am making a custom module on Drupal 7 and I am into to use templates for showing the info. How can I pass values from the module to the template?


texts: Alter all Webform's form with hook_form_BASE_FORM_ID_alter

texts:
What is the base form_id for Webform's forms to use in hook_form_BASE_FORM_ID_alter()?

My website will have lots of Webforms and I'm looking the proper way to alter this huge amount of forms.


texts:
Creating a module with Drupal Composer asks me:

  Define module as feature (yes/no)

What does it mean?


texts: Search module is not working with all content types

texts:
In my drupal, i have a search module. This module is not working with all content. For example i have a view. This view's show us announcement.
When i was trying to search this content type, there is no result.

I'd tried reindex (/admin/config/search/settings)

So can someone give me an idea?


texts:
I'm working on a form that allows users to submit several files.  I have a form created that includes several managed files.  I need a way to process the file after it's been uploaded to ensure that it contains the data I need.  Is there a way to do this?  All the code I've seen on the internet talks about processing files but doesn't show to call the code in the first place.

My form element looks like this:

$form['commlink_fid'] = array(
  '#type' => 'managed_file',
  '#title' => 'The file to upload',
  '#default_value' => variable_get('commlink_fid',''),
  '#upload_location' => 'private://uploaded_files/',
  '#upload_validators' => array(
    'file_validate_extensions' => array('zip'),
  ),
);


texts: Modifying the properties and output of a select list when adding content with the admin Drupal 7

texts: I have a type of content. Depending on the domain (I use Domain Access), I want to show a different content in a field which is a select list with reference to term. By several reasons, I do need to do this programmaticaly, to have full control. Also need to change the property: "required" of the field on-the-fly. What hook should I use, is there some example where I can look at? Thanks.


texts: How would you migrate a large list of (taxonomy) vocabulary list?

texts: I'm moving a large series of vocabulary lists to a new D7 install. I used features to copy over taxonomy groups. However, I only copied over the taxonomy not the vocabulary lists. Is there an extension to features to handle this?


texts: Unable to set date field programmatically

texts:
Somehow my custom fields ('datum' and 'high') are not set in the following script. Could someone tell me what I am doing wrong?

    function erstelle_kursenodes() {

$content = file_get_contents('http://www.xmlcharts.com/cache/precious-metals.php?format=json');

if(empty($content)){
    echo 'KEINE API-VERBINDUNG';
} else {
$cuobj = json_decode($content);
  // add node properties
  $newNode = (object) NULL;
  $newNode->type = 'kurs';
  $newNode->title = 'XAUUSD';
  $newNode->uid = 0;
  $newNode->created = strtotime("now");
  $newNode->changed = strtotime("now");
  $newNode->status = 1;
  $newNode->comment = 0;
  $newNode->promote = 0;
  $newNode->moderate = 0;
  $newNode->sticky = 0;
  // add fields
  $newNode->field_datum[$node->language][0]['value'] = date('Y-m-d h:i:s', strtotime("now"));
  $newNode->field_high[$node->language][0]['value'] = number_format($cuobj->usd->gold * 31.1034768, 2, '.', '');
  // save node
  node_save($newNode);
}}

'datum' is a regular date field

'high' is decimal integer with two digits after a point


texts: How can I get the value of the field_percentage field?

texts:
I'm trying to create a custom template for the paragraph-progress-bar component.
The component I created has 2 fields: title (field_title) and percentage (field_percentage, integer field limited from 0 to 100).
How can I get the value of the field_percentage field to pass it in the width of the progress bar code?
I'm trying with style="width: {{ content.field_percentuale ~ '%'}};" but it returns Array.
{%
  set classes = [
    'paragraph',
    'paragraph--type--' ~ paragraph.bundle|clean_class,
    view_mode ? 'paragraph--view-mode--' ~ view_mode|clean_class,
    not paragraph.isPublished() ? 'paragraph--unpublished'
  ]
%}
{% block paragraph %}

    {% block content %}

{{ content.field_titolo }}

    {% endblock %}

{% endblock paragraph %}


texts: Forgot to do config ignore before building webform. How to correct it and ignore the webform from the export?

texts:
Complete newbie to Drupal here. I forgot to configure my config ignore before I built a webform.
I have now managed to do add webform.webform* to the config ignore but that doesn't solve my problem since the webform has already been exported.
How do I fix the import/export settings in order to remove the webform?


texts:
I created a view block and a content type "slideshow image" with "title" and "image" specially for slideshow.
In this block only images of "slidshow image" content will appear.

And i added up five elements and i see effects on the slide show.

And even i created a directory named "jquery.cycle" in libraries
 \sites\all\sites\all\modules\libraries. Added the jquery.cycle.all.js file into that directory and but i didnt got any sliding of images...

Only the latest image is displaying but no effects.


texts:
I have a module where hook_menu() was already used to process ajax calls, like this:

function bizaudit_menu() {
  return [
    'bizaudit/ajax' => [
      'page callback'     => '_bizaudit_ajax_handle',
      'access arguments'  => ['access content'],
      'type'              => MENU_CALLBACK,
    ],
    'bizaudit/autoexec' => [
      'page callback'     => '_bizaudit_autoexec_handle',
      'access arguments'  => ['access content'],
      'type'              => MENU_CALLBACK,
    ],
  ];
}

That works pretty well from times, then I just added another item, now to handle some precise route, like this:

function bizaudit_menu() {
  return [
    'bizaudit/ajax' => [
      'page callback'     => '_bizaudit_ajax_handle',
      'access arguments'  => ['access content'],
      'type'              => MENU_CALLBACK,
    ],
    'bizaudit/autoexec' => [
      'page callback'     => '_bizaudit_autoexec_handle',
      'access arguments'  => ['access content'],
      'type'              => MENU_CALLBACK,
    ],
    'navigate' => [
      'page callback'     => '_bizaudit_navigate_handle',
      'access arguments'  => ['access content'],
      'type'              => MENU_CALLBACK,
    ],
  ];
}

But this route seems to be never recognized!
To be sure I changed the callback function like this:

function _bizaudit_navigate_handle() {
  $query_params = drupal_get_query_parameters();
  echo implode('<br>', print_r($query_params, true));
  exit;
}

Using this url 127.0.0.1/apim/navigate should cause the query params to be printed (here empty, but no matter), and nothing else to happen.
Instead I get the normal content of the involved page displayed!
(I didn't omit to clear the cache)

Maybe I'm missing someting obvious?


texts: How to trigger a rule when clicking on a link?

texts: I am looking for a way to trigger a rule when clicking on a link. What I am actually trying to do, is fireing a VBO with a Button, instead of the Dropdown solution. For this, I created a Rules-Component that does the job, but I don't know how to fire that rule, as it should start from within a view.


texts: Where is the "Generate automatic URL alias" setting stored?

texts: I have about a 100 nodes where I need to manually change the url alias in the url_alias table. I want to make sure the "Generate automatic URL alias" setting is disabled for those nodes so the url doesn't change when a user changes the title.


texts: How to pass parameters by reference to a batch?

texts:
I need to process a parameter in a batch function where the result will be kept after the function ends and it should be then passed in the finished function of the same batch.
Is there a way to pass the parameters by a reference, so that any changes to that parameter are saved?

Example:

$params = [$a, $b];
$finishedParams = [$a, $b];
$batch = ['title' => 'Sample processing batch',
          'operations' => ['someFunction', $params],
          'finished' => ['finishedFunction', $finishedParams]
         ];
...
public static function someFunction(&$a, $b){
    $a = 'somethingChanged';
}
public static function finishedFunction($success, $results, $operations){
   // Use $a variable when somethingChanged after the batch process.
}


texts: Entity Reference auto complete user name with different field

texts:
I'm using the entity reference module to associate users with a particular content type.  I'm using the auto-complete widget (tag-style).  By default, it uses the user name when auto-completing users.  However, I want to change the field it's searching on.  I have a field, field_complete_name that I want to use instead of the name field.

My question is, is the Entity Reference module capable of doing this?  If so, how do I do it?


texts:
I am attempting to modify the way the language negotiation is done on a site.

I've implemented a new language negotiation method:

/**
 * Implements hook_language_negotiation_info()
 */
function MODULE_language_negotiation_info() {
  return array(
    'MODULE_provider' => array(
      'file'        => drupal_get_path('module', 'MODULE') . '/MODULE.module',
      'weight'      => -4,
      'name'        => t('URL (Combined)'),
      'description' => t('Determine the language from the URL (Path prefix and domain).'),
      'cache'       => 0,
      'callbacks'   => array(
        'language'    => 'MODULE_language_provider_callback',
        'url_rewrite' => 'MODULE_language_url_rewrite_callback',
      ),
    ),
  );
}

In the case of a single language, the $language is being detected properly, the $language_content is being detected properly, but the $language_url is not being detected properly.

After some digging into this, I found that in the locale.module there are three language types defined - language, language_content and language_url:

/**
 * Implements hook_language_types_info().
 *
 * Defines the three core language types:
 * - Interface language is the only configurable language type in core. It is
 *   used by t() as the default language if none is specified.
 * - Content language is by default non-configurable and inherits the interface
 *   language negotiated value. It is used by the Field API to determine the
 *   display language for fields if no explicit value is specified.
 * - URL language is by default non-configurable and is determined through the
 *   URL language provider or the URL fallback provider if no language can be
 *   detected. It is used by l() as the default language if none is specified.
 */
function locale_language_types_info() {
  require_once DRUPAL_ROOT . '/includes/locale.inc';
  return array(
    LANGUAGE_TYPE_INTERFACE => array(
      'name' => t('User interface text'),
      'description' => t('Order of language detection methods for user interface text. If a translation of user interface text is available in the detected language, it will be displayed.'),
    ),
    LANGUAGE_TYPE_CONTENT => array(
      'name' => t('Content'),
      'description' => t('Order of language detection methods for content. If a version of content is available in the detected language, it will be displayed.'),
      'fixed' => array(LOCALE_LANGUAGE_NEGOTIATION_INTERFACE),
    ),
    LANGUAGE_TYPE_URL => array(
      'fixed' => array(LOCALE_LANGUAGE_NEGOTIATION_URL, LOCALE_LANGUAGE_NEGOTIATION_URL_FALLBACK),
    ),
  );
}

So, pressing onward, I implement hook_language_types_info_alter and add my callback function to the list of callbacks for the language_url language type:

function MODULE_language_types_info_alter(array &$language_types) {
  $language_types[LANGUAGE_TYPE_URL]['fixed'][] = 'MODULE_language_provider_callback';
}

The issue I am facing is that the hook_language_types_info_alter is called after drupal_language_initialize, so all of the language types have already been determined before the hook alters the language types.

Also, all of these language types are stored as variables. I could in theory modify the variable, but I would rather do this the correct way using hooks.

How do I modify the language_url language type before drupal_language_initialize?


texts: Delete a feature but keep the content created by it

texts:
Is it possible to keep the data created by a feature after deleting feature itself?
I created a migration feature that is really just a one off; I would want to delete it without losing the nodes created from it.


texts: google g+ button not working in authenticated user

texts:
g+(google plus) button is not working in authenticated users page, when i click the g+ button  the error image will appear instead of g+ button ,when i click the error button a popup will appear for error suggestions.

But it working in anonymous page .. any one know how let it to be work in logged in page. reply ASAP


texts:
I have a phpBB 3.0.10 site i want to migrate all the contents of the site to drupal 7.

I want all my users to import from phpBB 3.0.10 to users of drupal 7.

All the forums should be migrated to drupal forums along with their groups and access rules in the phpBB forum.

The users groups should be mentioned.

All the posts and comments should also be imported.

I have tried modules phpbb2drupal and phpbbforum but i was not able to completely migrate it to drupal.

After the migration i will be leaving phpBB 3.0.10 and only be working on drupal 7.

Is there a solution, i have been searching but couldn't find the right solutions.

Thanks for the help...


texts: How to set individual fields permission on content type fields based on roles using field permssion

texts:
I am using field permission module. I want some fields to be editable for other roles which I set using field permission module, but when I login as that user role I don't get the edit option on the node.

What I am actually trying to achieve is this:

I have created a content type with fields.
I want editor role users to submit pictures for that post.
They should not be able to edit other fields but just this.


texts: How do I avoid checking for updates for a specific module?

texts:
In a current project I have had to patch the life out of a few modules (node hierarchy, workbench access and a few more). These modules are now absolutely perfect for the project's needs and are very unlikely to break with future updates to core.

That being said, when the app is handed over the clients will have full (user 1) access to the system and will therefore be warned when these modules have available updates. And they will update them, no matter how many times I beg them not to (oh how easy life would be without clients!).

Is there a way (perhaps in the modules' .info files) to persuade the update manager not to check for updates for these modules?

EDIT

I'm aware of the project status url key that's available for the .info file so I guess I could set that to a non-existent URL but I'd much rather do this in a clean way if possible.


texts: How do I programmatically check if a context is active?

texts:
How do I see which contexts are active on the page?

I can't find any ContextManager object in hook_preprocess_page().


texts: How to bulk update text filter format on fields in drupal 7

texts:
I have multiple fields across my site, and multiple text filters. I need to delete one of the filters, but I know that it will result in users getting that whacky permission denied error when they try to edit the field.

Is there a way to bulk update all fields input filters? I started looking at field_update_field in the field CRUD api, but I'm at a loss.


texts: I have created form using Drupal 8 Webform.I have created fieldset and fields.But i couldn't add or alter fields inside fieldset using hook_form_alter.I can add fields outside of fieldset using form alter.How can i alter fields inside fieldset?


texts:
How does one get the actual value for an exposed filter?

I can get the 'id' for a filter value using the following code and pulling the data out of the array, but this just returns integer values of 1,2,3,etc.:

$view = views_get_current_view();
$view->exposed_input['filter_name'];

using $view->get_exposed_input() results in the exact same issue.

How do I get the actual text string that is applied for the filter?

Specifically I'm trying to do this with a Global PHP field.


texts: Filter taxonomy terms in common to nodes related to the viewed node

texts:
I want to filter taxonomy terms in common to nodes related to the viewed node, but I cannot figure out how. What I am getting are all the terms that the related nodes have (with repeated terms too). Please take a look at this recipe page, side block STAG RICETTA

I am filtering seasonality terms (months) in common to ingredients nodes (the ones related to the node being viewed) used in a recipe node (the viewed one).

How can I achieve this?


texts: I am working on existing Drupal project. I am begineer at Drupal and I need a help with something. In one node I've got title with title_suffix. This node is a view. I want to edit this title_suffix, but I don't know how and where to look at it. Could anyone help me please? Where do I have to looking for? UI or template files or where? Thanks.


texts: Save a user field without calling hook_user_update

texts: I'm building a module that has to sync users with another, non-drupal, db. When the hook_user_update is run I check to see if the user has an account in the other db. If they don't then it creates a record there and returns their id from that system. The problem I have is now I need to store that new id in a custom drupal field as well. I don't want to assign it and call user_save inside of hook_user_update because I don't want to run another instance of hook_user_update before the other has finished running. So, is it possible to just save a single user field without having to call user_save thus triggering hook_user_update?


texts: XHR2 upload using Drupal 7's ajax framework

texts:
I'm trying to implement XHR level 2 (file API upload) using Drupal 7's JQuery $.ajax implementation. I've got the feeling I'm almost there.

First of all, I got XHR.send() working according to orginal example on HTML5 demos. But now, I want to use Drupal 7's built in ajax framework.

I found some examples how do this with JQuery but I can't get it working for Drupal 7 with a custom ajax responce. I also found a related (D8) discussion about this on drupal.org.

Here's the code, which returns a ajax error "Illegal invocation". Probably because formData is not in a proper format?

    // 'files' below is a correct object with at least one file

    var file = files[0];
    var formData = new FormData();

    formData.append('file', files[0]);

    // element_settings: see ajax.js in drupal
    var element_settings = {};

    element_settings.progress = { 'type': 'none' };
    element_settings.url = '/mymodule/save/ajax';
    element_settings.data = file;
    element_settings.cache = false;
    element_settings.contentType = file.type;
    element_settings.processData = false;
    element_settings.submit = {
      'savedata': formData
    };

    element_settings.xhr = function() {
      myXhr = $.ajaxSettings.xhr();
      if (myXhr.upload) {
        myXhr.upload.addEventListener('progress', progressHandlerFunction, false);
      } else {
        console.log("Upload progress is not supported.");
      }
      return myXhr;
    };

    var base = '#myelement';
    ajax = new Drupal.ajax(base, $('#myelement'), element_settings);
    ajax.eventResponse($(ajax.element));

On the server site, I'm using a menu hook with ajax_deliver as delivery callback.
This works, but I can't access $_FILES in the same way which is possible if you use xhr.send().

By, the way, I'm aware this only works in modern browsers. I'm using Chrome.


texts:
Anyone help me how to set the id for a div class dynamically in code. Let suppose class name by group_left

      <div class-"group_left article_left">

I have to add a id attribute for this class "group_left article left"

I have used the java script to set the id but I can't.This is my code.

   var thediv = document.getElementByClassName(".group-left ");
    thediv.setAttribute("id", "pad_id");

There is any way API to add attribute id for a class in drupal.please help me.


texts: Programatically untick generate automatic URL alias for new node

texts:
I am creating a new node and then adding a new menu link. I have the code to correctly add the new node and menu link (below).

$node = Node::create([
              'type' => 'standard_page',
              'langcode' => 'en',
              'created' => REQUEST_TIME,
              'changed' => REQUEST_TIME,
              'uid' => 1,
              'title' => 'new_node',
              'body' => [
                'summary' => 'new_node',
                'value' => 'new_node',
                'format' => 'full_html',
              ]
          ]);

  $node->save();

$source = '/node/' . $node->get('nid')->value;  \Drupal::service('path.alias_storage')->save($source, '/new_node', 'en');

$link = MenuLinkContent::create([
      'title'      => $title,
      'link'       => ['uri' => 'internal:/new_node'],
      'menu_name'  => 'main',
      'weight'     => 10,
    ]);

The problem is that when I go to edit the node, "generate automatic url alias" is always ticked. So whenever I go to update the node, it destroys the alias that I have already created.

I have tried the following code.

$node->path['pathauto'] = FALSE;
$node->save();

This doesn't seem to work in Drupal 8 as I get the following error:

  InvalidArgumentException: Unable to set a value with a non-numeric delta in a list. in Drupal\Core\TypedData\Plugin\DataType\ItemList->set() (line 112 of core\lib\Drupal\Core\TypedData\Plugin\DataType\ItemList.php).

Hoe do I programatically untick the "Generate automatic URL alias" option in Drupal 8?


texts: Is it possible to add custom stylesheets while using a core theme?

texts:
I'm trying to add a custom stylesheet although I'm using the Garland theme but so far I wasn't able to do it.

I've tried the following:

function mymodule_init(){
    $path = drupal_get_path('module', 'mymodule');
    drupal_add_js ( $path . '/extra/script.js' ); // script is loaded and works
    drupal_add_css( $path . '/extra/style.css' ); // css isn't.
}

I also have a form that I will display when accessing /myform, so I tried to add the CSS there:

function mymodule_formname($form_state){
    drupal_add_css( drupal_get_path('module', 'mymodule') . '/extra/style.css' );
    // $form definition here
    return $form;
}

No success. Finally also tried to include the CSS using the #attached form parameter but still no results. I flush the cache for each of the attempts just to be sure...

Am I missing something? Shouldn't this be possible?


texts:
I've been trying to insert a placeholder for my search-bar, so in my page.preprocess.inc I call hook_form_search_block_form_alter(), then specify the form's array, and create the placeholder array, but it doesn't work. I've tried multiple things but none of them seem to affect the form in any way. I use devel themer, as both the devel page array and <?php dpm() ?> don't seem to work on my frontpage. My alternative would be to use jquery but I'd rather have this work then having to resort to the longer method.

Here's what I'm working with:

theme name - hitech_wolf

EDIT: I'm using omega4

PAGE.PREPROCESS.INC

    <?php
        // Can Ignore, left in here just in case it influences the alter statement
        /**
         * Implements hook_preprocess_page().
         */
        function hitech_wolf_preprocess_page(&$variables) {
            $path = drupal_get_path('theme','hitech_wolf');
            drupal_add_js($path . '/js/iframe_colorbox_support.js');
        }

        /**
         * Implements hook_form_alter().
         */
    // Separate Attempts - present for example
    function hitech_wolf_form_search_block_form_alter(&$form, &$form_state) {
      $form['search_block_form']['#placeholder'] = array(
        t('Search...'),
      );
    }
    function hitech_wolf_form_search_block_form_alter(&$form, &$form_state) {
      $form['search_block_form']['#attributes'] = array(
        'placeholder' => t('Search...'),
      );
    }
    function hitech_wolf_form_alter(&$form, &$form_state) {
      if ($form_id == 'search_block_form') {
        $form['search_block_form']['#attributes']['#placeholder'] = t('Request your username');
      }
      if ($form_id == 'search_block_form') {
        $form['search_block_form']['#attributes'] = array('placeholder' => t('Request your username')
    );
  }
}
        // Check if anything works at all - doesn't
        function hitech_wolf_form_alter(&$form, &$form_state, $form_id) {
          hide($form);
        }
        function hitech_wolf_form_alter(&$form, &$form_state, $form_id) {
          unset($form);
        }

PICTURES - form id/location


texts: Override where taxonomy menu links (created by Drupal Commerce) point to (new custom taxonomy views instead of default D.C. taxonomy views)

texts:
I do like how the default Drupal Commerce menu auto-updates with the # of items under that taxonomy like 'Furniture (9)'.
I'd like to keep that nice feature, but I'd like to change the actual url of those Drupal Commerce main-menu links (point to my Views instead of D.C. default views /products and /product_category/%).

So I manually created 2 new views, one with a conceptional taxonomy filter that looks like /my-products/% and one without the conceptional filter /my-products. They work great.

Now I'd like to repoint the current Taxonomy main-menu to those values ('All Products' would goto my new /my-products 'all products' view, while the rest would goto the new /my-products/% taxonomy-based view based on the taxonomy's term-id).

So how can i do this, is this a template.php override of some sort or GUI based change I can't find yet? I tried here but the Path is hardcoded and not editable:

/admin/structure/menu/manage/main-menu

P.S. using Drupal Commerce Kickstart 2

NOTE: i guess i could remove their menu and just replace with my menu... But I'd lose that ability where D.C. updates the menu text with the # of items in the store, so hence why'd like to keep that :).


texts: New path creation through hook menu problem

texts:
I have installed Drupal 7. I created new module (.module file and .info file), enabled the module, and gave the permission to menu item also. If I go to localhost/siva/shop/catalog/products, it redirects to the home page.

function displayproducts_menu() {
  $items = array();

  $items['shop/catalog/products'] = array(
    'title' => 'Products',
    'description' => 'Configure the cart page display and settings.',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('displayproducts_show_form'),
    'access arguments' => array('view displayproducts'),
    'file' => 'uc_cart.admin.inc',
  );
  return $items;
}

function displayproducts_permission() {
  $perms = array(
    'view displayproducts' => array(
      'title' => t('view displayproducts'),
    ),
  );

  return $perms;
}

function displayproducts_show_form(){
    echo "hello world";
}

Why does this happens?


texts: How to allow multiple email addresses on webform module?

texts:
The version of webform module im running doesn't support sending to multiple email addresses. Ideal users should be able to add all the different emails they what to send to in one box. Dose anyone have a workaround for this. Even if that means adding the emails in a "cc" form or separating the emails with a semicolon or comma.

-Thanks


texts: How to migrate core profile fields into the new profile fields in D7?

texts:
Premises:

I´m trying to upgrade a big D6 site to D7.

I have the content profile module installed.

I have a few core profile fields that I need to keep.

The "profile" node that was created by the content profile module, has no fields in it. I just used in order to manage in a better way the theming and presentation of profiles.

I´ve installed Profile2 module. I´ve installed the profile page submodule that comes bundled with it.

My 2 problems:

1. I would like to export or convert all those core profile fields into the new entity fields in D7. How may I do that?

2. In the meanwhile (in case number 1 is just not possible at all), I´ve tried theming the profile2.tpl.php file, trying to print into it my old core profile fields.

I´ve followed the instructions to print those core profile fields, so I´ve harcoded this print check_plain($account->profile_nombre); into the template, but it doesn´t print the name of the user that´s inserted into the nombre field (core profile field). So, how may I theme the profile page?

I´ve watched this video tutorial also, about the profile2 module, but I´m still absolutely clueless on how to manage profiles in D7 when you already have a couple thousand users with core profile fields in it.

Please note that I´ve tried using the "migrate" module, and the "drupal 2 drupal" migration module, with no luck.

Thanks for your help and insight!


texts:
I'm reviewing a spec. that calls for all files uploaded via a file field to be automatically converted to PDF format.  I have two questions:

Is this wise?  Files would be uploaded by anonymous customers.  Allowed file extensions (.doc, .xls, .png, .jpg, etc) would be provided as per normal file field use.

(Edited to clarify my main concern is security)

Are there any conversion tools you would recommend?  Paid or free is fine.  Remote service is fine, local server-based is preferable.  I can't find anything in the Drupal-verse, but have uncovered tools such as unoconv and JODConverter that look promising.


texts: How to inject postal address into user entity via custom registration form

texts:
I'm using the postal address module to obtain a user's postal address when they register on the site. The registration form is created by a custom module I made.

I'm able to get the form to display the postal address fields correctly (they modify based on your country, etc.), but when I go to process the form in HOOK_submit(), I hit a problem.

The submit function adds the user entity and puts the correct information in for the user. It also creates a new line in the field_data_field_postal_address table in the db as it should. But the address fields are all empty.

I think it is very close to working, but I suspect that something is wrong with the structure of the array I'm passing in to the 'field_postal_address' custom entity field.

function user_registration_form_submit($form, &$form_state){
drupal_set_message("User registration submitted");
dsm($form_state);

$edit = array(
    'name' => $form_state['values']['name'],
    'pass' => $form_state['values']['password'],
    'mail' => $form_state['values']['mail'],
    'init' => $form_state['values']['mail'],
    'field_postal_address' => array(LANGUAGE_NONE => array(array('value' => $form_state['values']['address']))),
    'status' => 1,
    'access' => REQUEST_TIME,
);
$newUser = user_save(drupal_anonymous_user(), $edit);
}

So, the question is, why is this function injecting an empty row of data into the field_postal_address field?


texts: Creating linkable images using Flexslider and Slideshow View

texts:
I am looking to create the ability to have my slider images link to link specified in my field_link. I have tried to put the node [field_link], but it is reading as plain text. I have tried a few suggestions, but I must not be doing them right.

Below you will find the current configuration I am using.

This is how I have set up my Slideshow View:

This is how I have set up my Image Field:

This is how I have set up my Link Field:


texts: How to add constraints to custom data arrays?

texts:
I am validating csv files. I am thinking of using constraints and constraint validator framework available in Drupal to validate the data in the files. However, these seem to be designed to be attached to entity fields. For example.
/**
 Implements hook_entity_base_field_info_alter().
 */
 function projectname_commerce_entity_base_field_info_alter(&$fields, EntityTypeInterface $entity_type) {
   if ($entity_type->id() === 'commerce_order_item') {
     if (!empty($fields['unit_price'])) {
       $fields['unit_price']->addConstraint('PriceBelowMax');
     }
   }
 }

where PriceBelowmax is a custom constraint. I would like to attach this constraint to a custom data array. For example
myCustomValidatemethod($data_array, $constraints)

where constraints would be the list of constraints defined in Drupal both core and custom. Is there some reference for the above method.


texts: Get ID name from form input field and reuse

texts:
I'm trying to figure the best way to get a form id from the search block form for example. I want grab the id that's in the input field and insert that name in my label tag. For example

<input id="edit-search-block-form--4"...

would go into

<label for="edit-search-block-form--4"...

I know you can call the for attributes beginning with

$form['name_of_form_field'] '

but how do I place that id into a variable then place that variable into my label and output it?


texts: Problem with Unorganized content on page

texts:
So I am not familiar with Drupal at all and need help. I am a graphic designer and trying to change the order of the layout on one of my pages. We had a developer design and organize our site but she screwed up the organization somehow.

How can I reorganize image on a page again? I tried going through Administrator > content > then I re-published the content in order but it did not work.

I've added an image so you can see my problem. Basically I'm having to manually drag the items in order but row weights but wanted to know if I can somehow organize them by title name and refresh the page to fix the problem. Any help is appreciated!


texts:
I am having problems with a porjectr of mine. Seems the taxes are not showing up until AFTER the order is put through. Here is a screenshot of what I mean.

I would like to have taxes show up at the button right before total. Can anyone point me in the right direction? Thank you.

i.stack.imgur.com/3hMWC.png


texts: Form API Select List will not show empty option

texts:
I am trying to add a form that forces you to select an option from a dropdown. The documentation says:

  If #required is TRUE and there is no #default_value, an empty option
  is added to the select control to force the user to make an active
  choice.

http://api.drupal.org/api/drupal/developer%21topics%21forms_api_reference.html/7#empty_value

OK that sounds great. That is what I want. So I have the following code to add the select list to my form.

$form['test'] = array(
    '#type' => 'select',
    '#options' => array (
      1 => 'Very poor',
      2 => 'Not that bad',
      3 => 'Average',
      4 => 'Good',
      5 => 'Perfect',
    ),
    '#required' => TRUE,
    '#title' => 'Rating',
  );

It is a select list, it is required and there is no default value. I however do not see a empty option...

What am I doing wrong?

Updated

The element above is now the only thing going into my array. When I dpm() the $form I get the following back:

Update 2

Below is what theme developer is seeing:

Update 3

I have set up a clean instance of drupal 7.22 and installed my custom code and the same thing is happening. I used the minimal profile. Must be something I am doing wrong else where...

Update 4

I have tested the full code on a different environment (7.19) and the same thing is happening. So it looks like there is something fundamentally wrong with the modules themselves. Will try and anonymize the problem so I can post here.

Update 5

I have the following two files in my module.

stack_test.module

<?php

function stack_test_menu(){
  $items['stacktest'] = array(
    'title' => 'Stack Test',
    'page callback' => 'stack_test_form',
    'access callback' => TRUE,
    'type' => MENU_NORMAL_ITEM,
    'menu_name' => 'main-menu',
  );
  return $items;
}

function  stack_test_form(){
  $countryList = array (
    1 => t('Very poor'),
    2 => t('Not that bad'),
    3 => t('Average'),
    4 => t('Good'),
    5 => t('Perfect'),
  );
  $form['test'] = array(
    '#type' => 'select',
    '#options' => $countryList,
    '#required' => TRUE,
    '#title' => 'Rating',
  );
  return $form;
}

Then I have my stack_test.info file:

name = Stack Test
description = Test Module
package = Stack Exchange
core = 7.x

files[] = stack_test.module

Update 6

Creating a select list in a content type with validation required works as expected and '- Select a value -' is displayed at the top of the list.

Update 7

The code in Update 5 should work now. I have created a mini module just with that in and I get the same results.


texts: Upgrading drush under Windows using self-update

texts:
I installed Drush on a W/XP workstation using MSI and want to upgrade it.
I've tried using drush self-update but the suggestions it gives all seem to pertain more to Unix installations than Windows.
The best suggestion looks like drush dl /path/to/drush but I'm not 100% sure what the /path/to/drush would be on a W/XP system.


texts:
I've been toying around with Drupal 7 for a couple of weeks now, and I think I understand how the theming system works, but I have a question.

I'm looking at Zen's default theme right now, and I understand that you're supposed to tweak the CSS files in the starterkit to begin building a more substantial sub-theme, but what if I wanted to change the layout of the page altogether?

Currently the Zen theme has the regions laid out something like this (please pardon the massively crude drawing, I just wanted to illustrate something):

And if I wanted it to be laid out like this instead:

Which of the theme files am I supposed to edit/hack? I'm assuming it's either page.tpl.php or html.tpl.php. Or is this something that's supposed to be done with CSS?


texts: Getting User Entered Form Data within a hook function

texts:
Problem

I need to use the following hook function to edit a similarly-named function in a contributed module (PayPal WPP), but I don't understand how to use it.

hook_commerce_paypal_api_request_alter(&$nvp, $order, $payment_method) { }

When this function is called I need to pass some variables to PayPal, based off user-supplied input in a form. By the time this function is called the user has already supplied their input in the form and clicked 'submit'. The form is now ready to send it's data to PayPal and this hook alters what is being sent.

So I need to figure out how to add additional data. Specifically I want to alter a variable $nvp['custom']. The main problem is I don't know how to get the values the user entered in the form into this function so I can pass them on.

I'm told I need to get the user-supplied values using $form_state['values'] but I have no idea how to get those inside this function, which isn't passed $form_state as a parameter. I was hoping to do something like this:

$name = $form_state['values']['field_name'];
$organization = $form_state['values']['field_organization'];
$arr = array($name, $organization);
$allthedata = implode('+', $arr);
$nvp['CUSTOM'] = $allthedata;

As it may be obvious I don't even know how to refer correctly to the passed $form_state values, which is probably a large part of my problem.

Question

How do i get my user-supplied form values into this function so I can use them (and then pass them on to PayPal as part of the $nvp['custom'] variable?


texts:
Drupal 7 has drupal_goto() that would allow redirecting to an external url.

The change record indicated that ControllerBase::redirect is the method to be called in D8.
https://www.drupal.org/node/2023537

This seems to work with internal drupal URLs but throws an error with external http urls -

[12-Nov-2014 21:00:22 Asia/Kolkata] Uncaught PHP Exception Symfony\Component\Routing\Exception\RouteNotFoundException: "Route "https://www.facebook.com/dialog/oaut....." does not exist." at /Applications/MAMP/htdocs/d8/core/lib/Drupal/Core/Routing/RouteProvider.php line 147

What would be the ideal equivalent of drupal_goto in D8 to redirect to an external URL?


texts: Form element with dynamic autocomplete route parameter

texts:
I have a simple form with two fields and a button. A field for the text to search and a field to select a type of node. The search text field has a autocomplete route that shows a list of nodes, but I need to send the selected option on the other field to the autocomplete callback function. Here is my code:
...
class MyFormClass extends FormBase {

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

 public function buildForm(array $form, FormStateInterface $form_state) {

  $form['searchtxt'] = array(
      '#type' => 'textfield',
      '#id' => 'txtSearch',
      '#autocomplete_route_name' => 'mymodule.autocomplete.search',
      '#autocomplete_route_parameters' => [
        'option' => $value,  // <-- here I want this value depends on the other field

      ],
  );

  $form['options'] = array(
      '#type' => 'radios',
      '#id' => 'optType',
      '#options' => array(
        0 => $this->t('Type 0'),
        1 => $this->t('Type 1'),
        2 => $this->t('Type 2'),
      '#ajax'          => [
          'callback'      => [$this, 'selectorCallback'],
          'wrapper'       => 'columns-wrapper',
        ],
      ),
  );

  ...
  return $form;
}

public function selectorCallback(array &$form, FormStateInterface $form_state) {
    return $form['searchtxt'];
}
..

I don't know how to do it.


texts:
How should I implement a callback to a single Drupal class (in my case it's Transliteration). I don't need a full Drupal load/bootstrap, but one independent class.

The purpose of the AJAX code would be the following:

User inputs 'áéíóű'
The input is sent via AJAX
The Transliteration class changes the input to 'aeiou'
The result is returned to the client

I've found this related issue, but it would be nice to have a simple example (and documentation) for it.


texts: Customizing the comment form with custom user profile fields

texts:
I've just started using Drupal 7 and cannot find an answer to this question so I'm hoping for some help here. I've added custom fields to the user profile on the /admin/config/people/accounts/fields page. For example, I've defined a School field which is text type and a Specialty field which is a list text type.

I'd like logged in users to be able to update their user profile information when submitting a comment to an article. How do I customize the comment form to allow a user to update the custom user profile fields. I've looked in the form and there is an author field, however this only contains the basics like name and email, not the custom fields.

Edit: I want this to be one form submission, both adding a comment and updating user profile information. It seems the way to customize the comment form is through the method function THEMENAME_form_comment_form_alter(&$form, &$form_state), however the $form object doesn't contain the custom user account fields that I've defined.


texts: String overrides doesn't override certain Commerce components

texts:
It actually overrides everything except 'Order total', I do not understand how that component doesn't get overwritten by String overrides.  Order total is in Checkout page.

Order total
$5,100.00

I cleared my caches.


texts: How to views-filter attached field value by calculated values?

texts:
I just want to create a simple "IN" filter for my taxonomy field with values that I calculate in the views_handler_filter subclass.

My subclass of views_handler_filter implements the function views_handler_filter->query(). I need to require that the tid of a taxonomy_term_reference field is in an array that I build there. How can I build the query to filter by field value?

views_plugin_query_default::add_where($group, $field, $value = NULL, $operator = NULL)

When calling $query->add_where(), the $field argument is simply described as "The name of the field to check." How can I join the filter query to the field data table and build my $field argument correctly for the taxonomy_term_reference field I need to filter by?


texts: How to handle session for anonymous users for CSRF tokens?

texts:
I need to provide list of CSRF tokens in drupalSettings for every anonymous user so JS can make safe requests to api endpoints.

The CSRF service mentions the need for session to exist for the seed but I am not clear about how to create the session correctly. I tried various approaches but none seem to work correctly.

So far I have tried:

if (session_status() === PHP_SESSION_NONE) {
  session_start();
}
// or
\Drupal::service('session_manager')->start();
// or
\Drupal::service('session_manager')->save();
// or
\Drupal::service('session_manager')->regenerate();
// or
\Drupal::service('session')->start();
// or
\Drupal::service('session')->migrate();

I am trying this in my route controller hook_page_attachments_alter.

This is my code:

/**
 * Implements hook_page_attachments_alter().
 */
function foo_page_attachments_alter(array &$attachments) {
  // Needed for persistent, per-user, csrf tokens.
  $session = \Drupal::request()->getSession();
  if ($session->isStarted() === FALSE) {
    $session->start();
  }
  // or
  \Drupal::service('session_manager')->start();

  /** @var Drupal\Core\Access\CsrfTokenGenerator $csrf */
  $csrf = \Drupal::service('csrf_token');

  $attachments['#attached']['drupalSettings']['foo']['tokens'] = [
    'pathA' => $csrf->get('/pathA'),
    'pathB' => $csrf->get('/pathB')
  ];

  $session->save();
  // or
  \Drupal::service('session_manager')->save();
}


texts: Taxonomy path to a view instead to the taxonomy page?

texts:
I have a Vocabulary taxonomy with some terms (alfa, beta,). This vocabulary is se to be sync with a menu (myMenu) using the taxonomy_menu module.

I need the path of the terms (the path of the menu items) to be products/[term:name] instead of taxonomy/[term:name].

'products' is the path of a view page and the term name will be taken as a argument.

How can I accomplish this?


texts: How to import images and body from external source via rss feed?

texts:
I am have some difficulty importing content from an rss feed provided by an external Drupal site call Parent Info. Subject to registration, the rss content is free to use under Creative Commons. I want to import the content for re-publication on a school website.

I've been using the news aggregator which is bundled with Feeds and I have tried creating my own feed importer. This creating nodes as it should and importing the description, but I can't get it to to import the node body or images.

I guess this is about field mapping, but I can't see how to add a field for the images (for example)

The feed url is http://feed.parentinfo.org/articles/primary/rss/8118

I have tried most of the various options provided by the feed importer and have a working demo based on the Drupal Planet rss feed.

What am I doing wrong? And what is the best way to achieve this?


texts: How do I programmatically create a simple 'page' node?

texts:
I have already found Drupal 6 documentation on how to programmatically create a page node.
How is it possible to achieve that in Drupal 7?

I've changed my strategy, and I'm using another approach, but I'm getting the following error:

  Fatal error: Cannot access empty property in C:\...\...\...\...\modules\field\field.attach.inc on line 198

I'm using the following code:

$form_state = array();
module_load_include('inc', 'node', 'node.pages');

$node = array('type' => 'page');
$form_state['values']['uid'] = 1;
$form_state['values']['name'] = 'admin';

$form_state['values']['title'] = 'Programatic Page';
$form_state['values']['language'] = 'en';

$form_state['values']['body']['en'][0]['value'] = 'My own value';
$form_state['values']['body']['en'][0]['summary'] = 'My own summary';
$form_state['values']['body']['en'][0]['format'] = 'filtered_html';

$form_state['values']['menu']['enabled'] = 1;
$form_state['values']['menu']['link_title'] = 'Auto-page';
$form_state['values']['menu']['description'] = 'Own Programatic Page';
$form_state['values']['menu']['parent'] = 'main-menu:0';
$form_state['values']['menu']['weight'] = 5;

$form_state['values']['path']['alias'] = 'auto-page';
$form_state['values']['comment'] = 1;

$form_state['values']['status'] = 1;
$form_state['values']['promote'] = 0;
$form_state['values']['revision'] = 0;

$form_state['values']['op'] = t('Save');

drupal_form_submit('page_node_form', $form_state, $node);

Is there anything wrong?

Using Firebug (Mozilla Firefox plugin), I figured out the name of the elements and then fill it with the proper values.
Creating a 'page' node programmatically, in Drupal 7, is done using the following code:

global $user;

$customNode = new stdClass();

$customNode->type = 'page';
node_object_prepare($customNode);
$customNode->uid = $user->uid;
$customNode->name = $user->name;

$customNode->title = 'Your page title';
$customNode->language = 'en';
$customNode->body[$customNode->language][0]['value'] = 'Your value';
$customNode->body[$customNode->language][0]['summary'] = 'Your summary';
$customNode->body[$customNode->language][0]['format'] = 'filtered_html';

$customNode->menu['enabled'] = 1;       // 1 to enable providing a link in main menu
$customNode->menu['link_title'] = 'Your page link title';
$customNode->menu['description'] = 'Your page description';
$customNode->menu['parent'] = 'main-menu:0';
$customNode->menu['weight'] = 2;

$customNode->path['alias'] = 'Your Alias';
$customNode->comment = 1;

$customNode->status = 1;        // 1 means published
$customNode->promote = 0;
$customNode->revision = 0;

$customNode->changed = $_SERVER['REQUEST_TIME'];
$customNode->created = $_SERVER['REQUEST_TIME'];

node_submit($customNode);
node_save($customNode);

This not completely functioning.
The page is being created successfully with all the values, but the link is not shown in the main menu navigation (I mean in the main menu tabs near the Home tab).
I checked it out in the created content and it's there, accessed it via "edit" button, pressed "save" (without editing anything), and it appears in the main menu.

I want it to automatically show when it is created. Do you have any idea?


texts: Is it possible to use an image style with a path rather than a URI?

texts:
I want to be able to send an image included in a custom module to the image_style theme like:

  $render_image = [
    '#theme' => 'image_style',
    '#style_name' => $imagecache_template,
    '#uri' => '/modules/custom/MYMODULE/default.png',
    ...
  ];

But '#uri' is expecting something in the format public:// . Is it possible to marshall a relative path somehow?


texts: Is there a way to provide the login provision for anonymous user when anonymous commenting is enabled?

texts:
I have enabled provision for Anonymous commenting. But it provides the only option of

Your Name
Email Address
Homepage

What I would like is, above this, there should be a provision of Login. Hence this way user can see that, So he/she will have two options, either he/she can login OR he/she can comment anonymously.

What happen with current system is, Anonymous user keep on commenting as anonymous only, If there is a option of Login, then he may think about that.

So, I would like to make the system in commenting like,

  Add Comment

**Login/create account**

OR

**Comment Anonymously**

Your-name*  |  Email*  |  Homepage

Comment field

Update:

I just need a Link, like what appears above the comments title on every drupal site, as shown in following image, Log in or register to post comment

Image


texts:
I created a custom module which contains a Class Form. When I submit my form, I redirect the user to the form page. During the submission, I need to save a form_state variable to re-use it after the user is redirected to the form.

So, from my submit method, I save my variable (with "$form_state->set(...)" ) and I add "$form_state->setRebuild()".

All works perfectly. Now, I want preserve my variable AND empty some field's form. I don't want to preserve values of all fields of my form after the user has been redirected.

I tried this :

// From my buildForm
// ...
$form['test'] = [
  '#type' => 'textfield',
  '#title' => "test",
];
$form['submit'] = [
  '#type' => 'submit',
  '#value' => t('Submit'),
];
//...
// I check if my var exist, if yes, that means the user has submited the form and has been redirected to the form
if($form_state->has('results') && $form_state->get('results')) {
  $form_state->setValueForElement($form['test'],"0");
}
return $form;

But I have this error when I use the setValueForElement method :

  The website encountered an unexpected error. Please try again later.
  TypeError: Argument 1 passed to
  Drupal\Component\Utility\NestedArray::keyExists() must be of the type
  array, string given, called in
  /(...)/core/lib/Drupal/Core/Form/FormBuilder.php on line 1296 in
  Drupal\Component\Utility\NestedArray::keyExists() (line 259 of
  core/lib/Drupal/Component/Utility/NestedArray.php).

I don't understand where my mistake is, use the setValueForElement maybe not the better way?

Edit (after Ismail Cherri's answer)

This is my new code : ("$form['#parents'] = array();" added)

// From my buildForm
// ...
$form['test'] = [
  '#parents' => [],
  '#type' => 'textfield',
  '#title' => "test",
];
$form['submit'] = [
  '#type' => 'submit',
  '#value' => t('Submit'),
];
//...
// I check if my var exist, if yes, that means the user has submited the form and has been redirected to the form
if($form_state->has('results') && $form_state->get('results')) {
  $form_state->setValueForElement($form['test'],"0");
}
return $form;

I keep the same error when I submit my form...

  The website encountered an unexpected error. Please try again later.
  TypeError: Argument 1 passed to
  Drupal\Component\Utility\NestedArray::keyExists() must be of the type
  array, string given, called in
  /(...)/core/lib/Drupal/Core/Form/FormBuilder.php on line 1296 in
  Drupal\Component\Utility\NestedArray::keyExists() (line 259 of
  core/lib/Drupal/Component/Utility/NestedArray.php).


texts: What is the use of "Add view from template"?

texts:
As when we select the view options three links appears but I don't understand what is the use of "Add view from template"

because when we click on this link we get this one...

and after further proceeding normal view is created. so what is the use of that link?