texts:
I’ve built a Drupal 8 Form example using code found here:
http://www.drupalcontrib.org/api/drupal/contributions%21examples%21ajax_example%21ajax_example.module/function/ajax_example_dependent_dropdown/8

The code, when run, dispalys 2 selects.  When a change is made to the first Select an Ajax call is made and is supposed to set a new set of options in the second Select.  However when changed I get a “Uncaught PHP Exception” - "The specified #ajax callback is empty or not callable."  I’ve tried multiple adjustment but am unable to get the code to run as desired.

Any answers or ideas would be greatly appreciated.

<?php
namespace Drupal\dependent_selects\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\CssCommand;
use Drupal\Core\Ajax\HtmlCommand;

include 'dependent_selects.config';

class DependentSelectsForm extends FormBase
{
public function getFormId()
{
    return 'dependent_selects';
}

public function buildForm(array $form, FormStateInterface $form_state)
{
    $options_first = $this->_ajax_example_get_first_dropdown_options();
    $formValues = $form_state->getValues();
    $selected = (isset($formValues['dropdown_first'])) ? $formValues['dropdown_first'] : key($options_first);

    $form['dropdown_first'] = array(
      '#type' => 'select',
      '#title' => 'Instrument Type',
      '#options' => $options_first,
      '#default_value' => $selected,
      '#ajax' => array(
        'callback' => 'ajax_example_dependent_dropdown_callback',
        'wrapper' => 'dropdown-second-replace',
      ),
    );

    $form['dropdown_second'] = array(
      '#type' => 'select',
      '#title' => $options_first[$selected] . ' ' . t('Instruments'),
      '#prefix' => '
',
      '#suffix' => '
',
      '#options' => $this->_ajax_example_get_second_dropdown_options($selected),
      '#default_value' => isset($formValues['dropdown_second']) ? $formValues['dropdown_second'] : '',
    );
    return $form;
}

public function ajax_example_dependent_dropdown_callback($form,  &$form_state)
{
    return $form['dropdown_second'];
}

public function _ajax_example_get_first_dropdown_options()
{
    $instType = array(
      'String' => 'String',
      'Woodwind' => 'Woodwind',
    );
    return $instType;
}

function _ajax_example_get_second_dropdown_options($key = '')
{
    $options = array(
      'String' =>
      array(
        'Violin' => 'Violin',
        'Viola' => 'Viola',
      ),
      'Woodwind' =>
      array(
        'Flute' => 'Flute',
        'Clarinet' => 'Clarinet',
      ),
    );
    if (isset($options[$key])) {
        return $options[$key];
    }
    else {
        return array();
    }
}

public function validateForm(array &$form, FormStateInterface $form_state)
{
    $a = 1;
}
public function submitForm(array &$form, FormStateInterface $form_state)
{
    $a = 1;
}

}


texts: How to make a facet search on a taxonomy term contained in a paragraph contained in a content type?

texts:
On Drupal 8, I try to make a facet on a taxonomy term contained in a paragraph entity contained in a content type. Is it possible?
My stack : Druapl 8.9.0 + Search API 8.x-1.17 + Facets 8.x-1.5
In Search API, I have indexed the taxonomy from the paragraph. In database I have a new table with 2 columns entity and taxonomy. It seems OK to link node with paragraph with taxonomy id.

I have created the facet without problem but it does not display on my search page.
Is someone has realized this before? Or maybe a advise to resolve this problem.


texts:
I'm trying to create a custom FieldType which provides the fields for a complete address (street, house_number, post_code and city).

I created a FieldWidget, FieldFormatter and FieldType class and a "field"-template. (followed the guide at http://www.computerminds.co.uk/drupal-code/drupal-8-creating-custom-field-part-1-field-type and "seeing" Drupal core FieldTypes)

The widget does not get rendered unless I add an element_info()-Hook and a address_preprocess-Hook where I have to define the same stuff like in the FildWidget::formElement() method. But this is the Drupal7 way. Am I missing something?

FieldWidget class

public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state)
{
  $element             = $element + array(
    'street'    => array(
      '#title'            => $this->t('Street'),
      '#type'             => 'textfield',
      '#default_value'    => isset($items[$delta]->street) ? $items[$delta]->street : null,
      '#required'         => false,

    ),
    'street_nr' => array(
      ...
    ),
    'zip'       => array(
      ...
    ),
    'city'      => array(
      ...
    ),
  );
  $form['#validate'][] = array($this, 'validateCompleteAddress');

  return $element;
}

FieldFormater class

public function viewElements(FieldItemListInterface $items)
{
  $elements = array();

  $elements['addresses'] = array(
    '#type' => 'fieldset',
    '#tree' => true,
  );

  foreach ($items as $delta => $item)
  {
    $elements['addresses'][$delta] = array(
      '#theme'     => 'fields_address',
      'elements' => $item,

      //'street'    => String::checkPlain($item->street),
      //'street_nr' => String::checkPlain($item->street_nr),
      //'zip'       => String::checkPlain($item->zip),
      //'city'      => String::checkPlain($item->city),
    );
  }

FieldType class

public static function propertyDefinitions(FieldStorageDefinitionInterface $field_definition)
{
  $properties = array(
    'street' => DataDefinition::create('string')->setLabel(t('Street'))->addConstraint('Length', array('max' => 255)),
    'street_nr' => DataDefinition::create('string')->setLabel(t('Street number'))->addConstraint('Length', array('max' => 100)),
    'zip' => DataDefinition::create('string')->setLabel(t('Zip'))->addConstraint('Length', array('max' => 5)),
    'city' => DataDefinition::create('string')->setLabel(t('City'))->addConstraint('Length', array('max' => 255)),
  );

  return $properties;
}

public static function schema(FieldStorageDefinitionInterface $field_definition)
{
  return array(
    'columns' => array(
      'street'    => array(
        ...
      ),
      'street_nr' => array(
        ...
      ),
      'zip'       => array(
        ...
      ),
      'city'      => array(
        ...
    ),

  ),
  'indexes' => array(),
  'foreign keys' => array(),
);

}


texts: How to get RAW Html code from my module?

texts:
I looked around for a few hours but wasn't able to find any available hooks to get pure raw html code. If you right-click on any webpage and do "get source", it will give you the raw html output.

However, there doesn't seem to be a function or hook available that I can find in Drupal that does this.

Does anyone know if this is possible? Thank you.


texts: Is there a way for me to create a direct link to a Quick Tab? I have a taxonony term page with two tabs one contains some view result and the other is specific page of site like quiz take url(node/23/take).


texts: Print the node author's full name on a custom node template

texts:
I have a content type "Blog entry" which I have overridden the template. (node--blog_entry.tpl.php)

The target is to display the node author's full name (as a link) which will take the user to a page (produced by a view) which shows all the other articles they have written.

In my template file, I have the following code:

 function bootstrap_mysite_preprocess_node(&$vars) {
   $vars['author_name'] = $vars['name'];
   $vars['submitted_dt'] = format_date($vars['node']->created, 'custom', 'jS F Y');
 }

The view that I have created which shows the author's other articles takes the UserID as an argument, so what I need is to display a link which which shows the author's full name, but passes their UserID.

the code I have in my custom content template is:

    WRITTEN BY <a href="/user-posts/<?php print $uid; ?>"> <?php print $author_name; ?>

But author name is not only the author's username (not their full name) but it is output as a link which is no good for me.  I simply want to output the author's full name as plain text.

So, to summarise -
What can I use instead of $vars['name']; (which producesa username that links to a profile)
that will instead produce some plain text of the user's full name ?


texts: How do I add DISQUS comment count in Views' sort criteria?

texts:
I am using DISQUS comments platform in my Drupal 7 site. My goal is to show the 10 most commented posts using views. For this I need to add 'DISQUS comment count' in 'SORT CRITERIA'. How do I do this.

The field 'DISQUS comment count' is not listed in 'Add sort criteria'.


texts:
In Drupal 7, I have an multistep form with ajax calls.
I would like to retrieve the form_build_id upon first viewing the multistep form.
Currently I'm using a workaround by retrieving the form_build_id in the hook:
function mymodule_multistep_form
....
          if (isset($form_state['values']['form_build_id'])){
//I do what I need to to

Which means that I get the form_build_id upon the second step in the multistep form, which is normal I guess since upon the first rendering, the first time is viewed and before the user would interact with my multistep rendered form,  the form_build_id is not yet set in the function mymodule_multistep_form
My question is, which hook can I use to get the form_build_id of my multistep form upon the first rendering in the page, and not upon the second step in the form?
I tried with the form_alter,
function mymodule_form_alter(&$form, &$form_state, $form_id) {
    dd($form_state['values']['form_build_id']);
}

however the form_build_id value seems to be empty.
I also need to retrieve the form_build_id only once, thus I do not need to have the code retrieving it with every ajax call of the multistepform, this is also inneficient.
Many thanks


texts: I'm trying to use views to show two random nodes for voting on.  I would use something like: filter: Node:terms(with depth), fields:Node body/ title, Sort criteria:GLOBAL:random.  Now, how can I render two random nodes for voting?  Would I have to render them on a custom page-"newpage".tpl.php?  I'm thinking if I used a custom template I would make two 50% regions, have them float left/right, have one height:150px region footer for the voting(below the nodes), then maybe use "popups" so it looks cleaner?  Any ideas on this?  For starters, I'm not sure how I would generate "2" random nodes and have them render in the appropriate "left/right region".  Thank you.


texts: "The value in Date is not a valid date" error

texts:
I am editing an existing node of content type event, and am trying to update the Date using the date pop up. However, no matter what date I select I get the The value in

  "Date is not a valid date"

error.

The same issue appears when I try and add a new node with the same content type...

Any suggestions?


texts:
I installed Drupal 8 on MAMP Pro with PHP 7. I am getting this warning in my Drupal reports page:

  PHP OPcode caching Not enabled
      PHP OPcode caching can improve your site's performance considerably.
      It is highly recommended to have OPcache installed on your server.

I looked in MAMP's PHP 7 ini file and I see this code which seems to be related to OPcode caching.

[OPcache]
MAMP_OPcache_MAMP
  opcache.memory_consumption=128
  opcache.interned_strings_buffer=8
  opcache.max_accelerated_files=4000
  opcache.revalidate_freq=60
  opcache.fast_shutdown=1
  opcache.enable_cli=1

So I am not sure if I need to do anything else to enable it, it seems to be enabled based on the code above. I googled around and could not find any specific documentation with regard to MAMP and PHP OPcode caching.


texts: CKEditor toolbar does not appear as configured

texts:
under /admin/config/content/ckeditor/edit/Full I have configured the CKEditor toolbar to appear in Full. However, when I edit my content in Full HTML, the toobar looks incomplete (see screenshot).

EDIT 1

The toolbar configured in /admin/config/development/performance


texts:
I themed page to create custom type node and named it page--node--add--book.tpl.php
It works well, but when I tried to theme content edit page and named it page--node--edit--book.tpl.php
nothing happening. Help to fix this.

Tried suggestions:

function bookhive_theme() {
  return array(
    'book_node_form' => array(
        'arguments' => array('form' => NULL),
        'template' => 'book-node-form',
        'render element' => 'form',
    ),
  );
}

and
suggestion from here

http://www.wdtutorials.com/how-to-override-forms-using-custom-template-drupal-tutorial/7


texts:
I have a form I want to fill in based upon some large amorphous external data. User starts typing in some text and AJAX offers suggestions. Now in the Drupal world I could do some AHAH which send the user entered data back to the server and some PHP could supply replacement bits of the form to return.
(as per http://drupal.org/node/348475 and http://drupal.org/node/331941 )
But what if my code is not in PHP but in some other web enabled language like python, perl or Java.

Is there a standard way of doing this with Drupal, or should I use jQuery and avoid Drupal entirely for this.


texts:
Is there any way to get this? I can get the node ID and link to a node using node/nid, but then I have to mix pretty links that pathauto gives me with ugly ones.

Is there any way to get the url alias as a field value when building a view?

Edited: My question was wrong.


texts: How to Trigger Existing, Non-Form Ajax from JavaScript Event

texts:
I'm trying to figure out AJAX in Drupal 8.

I have a custom module that works, using AJAX to change the content of a div when a link is clicked.

The API says:

  Many different events can trigger Ajax responses, including:

  Clicking a button
  Pressing a key
  Moving the mouse

How do I trigger the same process that Drupal's AJAX does when a function is called from a JavaScript object's event firing instead?

JavaScript Object

function calledOnSomeEvent(e) {
  String data = e.target.data;
  // do something to call AJAX with the data
}

The AJAX backend works with this route:

myModule.routing.yml

myModule.myRoute:
  path: '/nojs/myFunction/{myParameter}'
  defaults:
    _controller: '\Drupal\myModule\MyController::myFunctionCallback'
    _title: 'myFunction'
  requirements:
    _permission: 'access content'

HTML

Click for testData!

My understanding is that Drupal injects some sort of event when that link is clicked, or the URL is just changed, and the controller is only activated when that URL is changed.

JavaScript

(function($, Drupal) {

  Drupal.AjaxCommands.prototype.myFunction = function(ajax, response, status){

    $('#targetDiv').html(response.data);
  }

})(jQuery, Drupal);

I omitted PHP code for the controller, which creates a command. The command renders the output to Drupal.AjaxCommands.prototype.myFunction, which updates the div.

Is an XMLHttpRequest the only way to make JavaScript interact with the route/PHP? If so, what path should be used?

I think there might be a way for JavaScript interact with Drupal's AJAX handler to call the same function that clicking the link changed with "use-ajax" does, since that's being handled in some way...

Any insight would be appreciated.

Thanks!


texts:
I'm trying to do a redirect on my node.html.twig template based on the content type because I'm using views for my content.

I tried this:

{% do redirect('/example') %}

or this:

{% redirect '/example' %}

but nothing works. Any idea?


texts: Is it possible when uploading a file to a node for it to upload as a background process? Ideally what I would like to do is to be able to upload files in the background while being able to continue navigating through the website. When the uploaded files are complete a notification appears on the website to say that the upload is complete or an email is sent.


texts: Is it possible to use a Display Suite Code Field in Views?

texts:
I've created a code field in Display Suite to to manage the display of a file (the file entity has a few fields per file).

Is it possible to use this same Display Suite code field in Views when creating a list of nodes for display?  I know I can do the same thing in a php field, but I'd rather not have to manage different code in different places to get to the same end result.


texts: How to know node/entity ID from a submit handler?

texts:
How to know node/entity ID from a submit handler of a form created with hook_form()?

I need to make db_update() query on a single row from submit handler called by admin/structure/video/manage/% form created with Forms API.


texts: commerce-email-order-items as a view doesn't show up when it's sent by anonymous

texts:
When I use this,

<?php function bobr_commerce_email_order_items($variables) {
  // Get order wrapper
  .$order_wrapper = $variables['commerce_order_wrapper'];
  // Get rendered view
  .returnviews_embed_view('clone_of_shopping_cart_summary', 'default', $order_wrapper->getIdentifier());
}?>

I can have email table as a view, so I can theme it. It works great, but only when I'm logged in as an Administrator.

When I do an order as an anonymous, the view table doesn't show up in email. How can I fix it?


texts:
I am using D7 + Hearbeat module

Previously my heartbeat setting was when cron runs delete activities older than a month. So a cron run removed the activities.

Is there any way of retrieving the deleted heartbeat activities?


texts: Assigning a badge to a user using Flag, Badges and Rules

texts:
I am interested in assigning to user a Badge after he favourites 3 nodes. I want to do this with Flag, User badges and Rules.

How can I do that?


texts: I have implemented an Algolia search in my drupal instance and would like to use the node url alias (/some-example-path) rather than node id (/node/{nodeId}). Is there a quick and easy way to do this using the Search API?


texts: Is there a way to link a menu item to the edit page of the last article?

texts:
I want to create a menu item linked to the edit page of the last article.

I created a view and added filters to get the last article. I added only the field node path to the view.

But how can I get the value of that path field and put it in the URL of my menu item?


texts: Ajax on submit button not working second time

texts:
i am using ajax on my custom module (via example module)
the issue is ajax dependable select menu working correctly  and the submit button also giving result properly but submit button becomes not click able on 2nd time
this snippet from my form

    $form['submit'] = array(
   '#type' => 'submit',
   '#value' => 'Search',
   '#ajax' => array(
      'callback' => 'ajax_country_submit_driven_callback',
      'wrapper' => 'box',
    ),
 );

and here is the handler for submit button

function ajax_country_submit_driven_callback($form, $form_state) {

 $city = $form_state['values']['city'];

 if($city == -9){
   $parent_id = $form_state['values']['country'];
   $child_terms = taxonomy_get_children($parent_id);
   $city_data = array();
   $i=0;
   foreach ($child_terms as $term) {
    //$city_term =  $term->tid;
    $city_data[$i] = get_node($form ,$term->tid);
    $i++;
   }
   return $city_data;
 }else{

   $element = get_node($form, $city);
   return $element;
  }

}

get_node function

function get_node ($form, $city_tid){

$nodes[] = taxonomy_select_nodes($city_tid);

 foreach($nodes as $nid) {
   $nodeid = $nid;
 }
 $i=0;
 foreach ($nodeid as $nid ) {
    $nodedata [$i]['nid']  =

 $nid;
    $nodedata [$i]['title'] = get_node_title($nid);
    $nodedata[$i]['body'] = get_node_body($nid);
    $i++;
 }

 $element = $form['box'];

foreach ($nodedata as $node) {

$title = $node['title'];
$nid = $node['nid'];
$body = $node['body'];
$element['#markup'] .="
";
$element['#markup'] .=l(t('@title' , array('@title' => $title)) ,
'node/'.$nid , array('html' => TRUE));
$element['#markup'] .="

";
$element['#markup'] .="
". t('@body' , array('@body' => $body) );
$element['#markup'] .= "

";
 }

  return $element;
}

Where its going wrong ?


texts: How to rename a field with hook_ds_fields_info()

texts:
In a contrib module I maintain, I define a DS field via hook_ds_fields_info().

Now it happens that I want to rename this field (the machine name).
(actually it is not about renaming but splitting the one field into multiple fields, but that's a detail)

The first step is trivial: Rename the machine key in hook_ds_fields_info().

Next step, in hook_update_N():
Every entity view mode that uses the field with the old name, should be updated to use the field with the new name instead.

How would I implement this second step?

It seems that the ds_field_settings and ds_layout_settings db tables are what I need to look at. But is this enough? Which API functions could I use?


texts: "Page Not Found" error when a google search form is submitted

texts:
I am using Google Site Search on a web site, and the search form submits to a page containing the appropriate code. I can access this page directly just fine, but whenever I test out the search form, I get a "page not found" error.

I believe this is because both Drupal and Google search use the parameter 'q', has anyone run into this problem and found a workaround?


texts:
This is a not-so-targeted question but I can't find any good information on this.

When is it considered correct practice to put code inside your template.php file and when to implement it in a module?

I mean in my current example I need to call hook_preprocess_node and inside perform a drupal_get_form and render that form. I've put my logic inside template.php.

Is that correct? If not, can you give me a short list of DOS and DONTS regarding the issue?


texts: anonymous voting using poll module invalidates cache

texts: I am not sure if this is a common problem. I use drupal 7 site with caching enabled. One of my pages is a simple poll. After anonymous voting, all cached pages are invalidated for current user. The cached pages remain in database so after clearing browser cache, current user sees cached pages again. Does poll use some sort of cookie that invalidates cache? How can I avoid such behavior? Thank you


texts: How to get the parent fieldgroup group_name for a field_collection_table?

texts:
My case is the following:

I have a custom node with some field collections and all of these are shown on a htab group, each one in it's own tab.

Now, what I want/need to do is: return to the page and focus on the htab group, opening the respective tab, after adding/editing any item on these collections.

What I managed to so far:

I could do the return-to-node thing, changing a little the field_collection.module code, merely adding the "destination" parameter to the links.
I can do the focus and select tab thing on whatever page, if I manually point it to the tab anchor for example.

The actual tab (it's outermost wrapper) is a fieldset with an id with the following pattern: #<entity_type>_<type_name>_<view_mode>_<group_name> (#node_mytype_full_groupxyz)

I already changed the links to use a hardcoded anchor and it works, but I'm trying now to do it dinamically, and that's where I'm stalled. In the field_colletion_table.module, the link is set in a hook implementation (field_collection_table_field_formatter_view), where I found most of what I needed:

$entity_type //'node'
$entity->type //'mytype'
$content['#view_mode'] //'full'

What I need to know: is there a way (query?) to get the group_name of the fieldgroup (tab) which contains the field_collection(_table)?


texts:
I want to programmatically load the user profile form for a specific user and submit it ( in order to trigger hook_form_submit() in another module ).  So far I have :

module_load_include('inc', 'user', 'user.pages');
$account = user_load($uid);
$form = drupal_get_form('user_profile_form', $account);

but how do I submit the form ?

Thanks


texts: How to insert values into Global custom text field of views programmatically?

texts:
How can I programmatically insert values into Global custom text field from the views. I have tried using the $views variable from the hook_views_pre_render(&$views) and my_theme_name_process_function(&$vars) but was unsucessful in getting the value ?
When I try for a simple field I can insert html into the markup programmatically.

$view = view Object
(
    [db_table] => views_view
    [base_table] => node
    [base_field] => nid
    [name] =>view_name
    [vid] => 3
    [description] =>
    [tag] => default
    [human_name] => view_name
    [core] => 7
    [api_version] =>
    [disabled] =>
    [editing] =>
    [args] => Array
    (
        )

    [use_ajax] =>
    [result] => Array

  [result] => Array
        (
            [0] => stdClass Object
                   [field_field_final_ort] => Array
                            (
                                [0] => Array
                                    (
                                        [rendered] => Array
                                            (
                                                     ['#markup'] => YES

I want to similarly change the value of GLOBAL custom text field using views object but there is not such array for global custom text field.
What is the way for changing it?

My code was

function my_themename_process_views_view_field(&$vars) {

  if ($vars['view']->name == 'view_name') {
foreach( $vars['view']->result as $key => $value) {
$value->field_name[0]['rendered']['#markup'] = '';
}

}

I want to apply this similar code for global custom text field but there is no suxh available inside result array

How can I alter values for each row of global custom text field value ?
The answer given below gives same values for each row .


texts: how can i remove the filters from the printer display generated by the printer friendly version for views drupal 7

texts:
Hope you all are fine. I am facing a difficulty in the drupal 7 module named printer friendly version. it is mainly made for the node print version. but I want to attach it with the views. so I created a view with page as a display. and attach the module with it by assigning the view name to its Show link in system (non-content) pages. It is working fine. but when it shows the print view it shows the filter textboxes and etc with it too. please guide me how to resolve this issue.

Kind regards.


texts: Create a block with information regarding the number of comments and contents created in a specific group

texts:
I am using Drupal commons 3.31.
I would like to know how many contents and how many messages are written within a group and  make a block out of it. Also be able to see how many comment,page a specific user has created.

Thank you


texts: View contextual filters to work as needed

texts:
I have content type A with some vocabulary for it and content type B with same vocabulary.
On the node page of type A I want to show block with some content of type B wich has any same terms as node page we're viewing. Is it possible?

Thank you!


texts:
I am working on an existing site where it has exposed api's via a custom module.

There's a new requirement where an api should only be accessed by authenticated user. For that theres a login api provided.

How can I make sure to add login information such that drupal recognises which user is making the call.

Does keeping SESSIONID in header will make drupal identify the user.

Note the API calls are made from android/ios app.


texts: Programmatically get field values of fields added to custom entity

texts:
I created a custom entity in Drupal 8, and I added base fields.

I add the getter/setter functions to my entity definition file.
They return NULL when called from a preprocess function. (I'm trying to add some variables for the Twig template.)

Why would this be?  I'm using the following code.

public function getProjectId() {
    return $this->get('project_id')->value;
}

project_id is en entity reference field.


texts: How to include external libraries placed outside the webroot in a custom module?

texts:
I'd like to use an external library in my custom module. So, I added it as a dependency in the composer.json of my custom module.

Since the drupal/recommended-project template places the vendor/ directory outside the webroot, we can't access it directly from the .libraries.yml file like this:

chosen:
  js:
    /vendor/harvesthq/chosen/chosen.jquery.min.js: {}

According to this Jaypan's post, the solution for this issue is to use the Vendor Stream Wrapper module.
So, I added this module as a dependency, both in .info.yml and composer.json files of my module, following the example in the Jaypan's post.
Then I updated my .libraries.yml file:

chosen:
  js:
    vendor://harvesthq/chosen/chosen.jquery.min.js: {}

However, the Chosen library is still not loaded (I mention that I cleared the Drupal cache) from what I see in my browser:

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

Here is the dependencies declaration in the composer.json of my module:

"require": {
  "harvesthq/chosen": "^1.8",
  "drupal/vendor_stream_wrapper": "^1.3"
}

The dependency declaration in my .info.yml file:

dependencies:
  - vendor_stream_wrapper:vendor_stream_wrapper

The hook_form_alter() method in my .module file:

function my_module_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  $form_object = $form_state->getFormObject();
  if ($form_object instanceof EntityFormInterface) {
    $entity = $form_object->getEntity();
    if (in_array($entity->getEntityTypeId(), ['node', 'user'])) {
      $form['#attached']['library'][] = 'my_module/chosen';
    }
  }
}

I mention that PHP goes well through the line $form['#attached']['library'][] = 'my_module/chosen';.


texts: Facets: How to create user specific facets in Search API?

texts: If I index user specific fields, like an Entity Reference field called Favorites. How could I add that as a facet that is specific to the logged in user, so only his favorites are filtered?


texts: How does routing order / matches effect performance?

texts:
I have all the following GET routes defined in my_module.routing.yml:

my_module.members_uid:
  path: 'users/{user}'

my_module.members_uid_gid:
  path: 'users/{user}/group/{group}'

my_module.user.content.view:
  path: 'users/{uid}/{bundle}/{gid}'

All of these have the same requirements and options except they upcast different data types, and each has it's own controller.

All of my controllers execute correctly, however is there any benefit to a particular order? Or is there any extra overhead from two matching except one dynamic parameter?


texts: How to keep a specific module on -dev version (with patches) on a Drupal8 site managed by composer?

texts:
I'm trying to manage a Drupal 8 site entirely with composer. However, I need a -dev version of one module (search_api_solr) with a patch. How do I tell composer to just leave this module on the dev version for the time being and not touch it during update ?

Relevant part of my composer.json looks like this

"require": {
        "composer/installers": "^1.0.21",
        "drupal-composer/drupal-scaffold": "dev-master",
        "drupal/admin_toolbar": "^1.18",
        "drupal/bootstrap": "^3.2",
        "drupal/coffee": "^1.0@beta",
        "drupal/config_tools": "^1.0@alpha",
        "drupal/console": "~1.0",
        "drupal/core": "~8.2",
        "drupal/delete_all": "^1.0@alpha",
        "drupal/devel": "^1.0@RC",
        "drupal/facets": "^1.0@alpha",
        "drupal/imce": "^1.5",
        "drupal/masquerade": "^2.0@beta",
        "drupal/migrate_manifest": "^1.4",
        "drupal/migrate_plus": "^3.0@beta",
        "drupal/migrate_tools": "^3.0@beta",
        "drupal/migrate_upgrade": "^2.0",
        "drupal/pathauto": "^1.0@RC",
        "drupal/search_api": "1.0@beta",
        "drupal/search_api_sorts": "^1.0@alpha",
        "wikimedia/composer-merge-plugin": "~1.3",
        "drupal/search_api_solr": "8.x-1.x-dev"
    },
    "minimum-stability": "dev",
    "prefer-stable": true,

I've specified the search_api_solr version according to this advice. However, when I run composer update I get:

Your requirements could not be resolved to an installable set of packages.
The requested package drupal/search_api_solr 8.x-1.x-dev exists as drupal/search_api_solr[...] but these are rejected by your constraint.

EDIT:
Meanwhile I have worked around this by removing the drupal/search_api_solr requirement completely from the composer.json, explicitly listing solarium/solarium instead and installing the patched version of search_api_solr-8.x-1.x-dev manually into the modules/unstable directory. Now composer update works as it shold without overwriting the patch.


texts: How to fix my String Translation error in my selection list value?

texts:
I am using the String Translation module (part of i18n) and I have added new string in Italian language.

Example:
Data d'inizio

Output:

So instead of translated text Data d'inizio its shows me the drop-down text.

How to fix this issue?


texts:
I want to display ctools modal. I tried the following code.

/**
 * Implements hook_menu().
 */
function my_module_menu() {
  $items['my_module/%ctools_js/test-page'] = array(
    'title' => 'Demo CTools Page',
    'page callback' => 'my_module_modal',
    'page arguments' => array(1),
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  );

  return $items;
}

function my_module_modal($js) {
  $output = '
' . t('Test content?') . '
';
  dsm($js);
  if ($js) {
  ctools_include('ajax');
    ctools_include('modal');

  ctools_modal_add_js();
    return ctools_modal_render('Define as start matrix', $output);
  }

  return $output;
}

The link where I click is

Open modal

But it returns me only the content of the page with no modal.
When I printed the $js variable, it is displaying 0. While the javascript is enabled in the browser. I have checked it with multiple browsers .

What can be the issue?


texts:
I am quite new to translation of Drupal and cant figure to translate a the page content on the homepage.

The entire site is translate with the normal translation methods offered by Drupal.

I have translated the blocks on the homepage but the home page content always shows in English. I have already changed the homepage alias to 'home' and both translations aswel.


texts:
I am building a module which already has the function Mymodule_menu() at the beginning of the code. I was wondering if it is possible to use hook_menu_alter() to add new menu items (i.e. building new pages) somewhere down the code.

What I'm trying to do is build a form module whereas when the user presses "Submit", the code inside the form_submit() function will build a new page using the form values the user entered, and then redirects the user to that page.

Is that even possible. Appreciate the help from anyone. Thank you all in advance!


texts: Error installing Theme on GoDaddy Drupal 8.4.5

texts:
I have goDaddy and installed Drupal 8.4.5, the newest version they have on their Installation. Trying to install the theme Nexus, when I upload the theme from archive (zip file) and click install I get the following error.

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

I have tried clearing the cache. I was running Drupal 8.3.2 and it would just go to a blank screen; updating to Drupal 8.4.5 now got me to this error. I have downloaded and tried about 20 different themes. I either get this error or I get that the file is over 2 megabyte and is too big. What am I doing wrong or how do I fix this error?


texts: Routing for controller with multilingual enabled

texts:
On my Drupal 8 multilingual project, I have made a custom controller which create a basic page, but I can't figure out which parameter I must use in the routing. Is this _locale?

This is the definition of the route.

custom.route:
path: '{_locale}/portail'
defaults:
  _content: '\Drupal\my_module\Controller\DisplayController::display'
requirements:
_access: 'TRUE

This is the code I am using in the controller class.

public function display(Request $request, $locale) {
    var_dump($locale);die;
}


texts: Custom block build function to display wysiwyg body text

texts:
I am learning to build custom blocks through a module. I am trying to get the build() function to work. I have the code and it works. However, if I edit the configuration of the block as a user it does not print the text in the text formatter.
'#markup' =>
    '<div>' . $this->t('Body: @body', ['@body' => $this->configuration['body']]) . '</div>',

In the rendered block on the page it prints... Body:
But not the text in the wysiwyg.
Any ideas how to get that to work. The tutorials and links I am finding are not relavant.


texts:
I have a module that returns a redirect response in hook_node_insert().

$url = 'announcements';
$response = new Symfony\Component\HttpFoundation\RedirectResponse(\Drupal::url($url, [], ['absolute' => TRUE]));
$response->send();

I have another module that implements hook_node_insert() for the same content type. Since I have written redirectResponse in the first module, the hook_node_insert() implementation in the second module is not getting called.

Is there any other way to do it? Drupal 7 has $_GET['destination'] and it works for Drupal 7.


texts:
I believe this is related to another problem, but not sure about how to go about checking what that problem is exactly.

As you can see below in the screenshot, I have created an effect to scale and crop to 200 by 235. But what you'll notice in the example image is it is only scaled, and it squishes the image rather than cropping it to fit with proportion. Has anyone ever come across this before?

As a sidenote, the other problem I referred to is that when I go to edit a node with an image field, I click upload of an image and the actual image doesn't appear but a link to it in the defaul/files folder does. I know they're related but not sure what next steps might be.

Thank you - Matt

--------------------UPDATE

After testing a few items out, I also found out that any style changes to images no longer work. For example, I upload a image and it does show up in the default/files folder. But it doesn't generate any of the styles that I try out for it. For example, one style is "generated" with this url: http://www.egyptianstudysociety.com/sites/default/files/styles/200-235_past_events/public/1270px-02_meidum_pyramid_0.jpg?itok=9Lx0wrCV

But when I go to that image through a browser I am given: Access denied
You are not authorized to access this page.

And if I go through my FTP, I cannot see the file at all.

---------------------UPDATE

Going through the logs, here is an example the drupal error log:

Type    access denied
Date    Thursday, February 23, 2017 - 2:11pm
User    Anonymous (not verified)
Location    http://www.egyptianstudysociety.com/sites/default/files/styles/media_thumbnail/public/9313765823_ba4cc244e6_b.jpg
Referrer    http://www.egyptianstudysociety.com/node/125/edit?render=overlay
Message sites/default/files/styles/media_thumbnail/public/9313765823_ba4cc244e6_b.jpg
Severity    warning

---------------------UPDATE

I got things fixed by following a fix, I've added the following code to my settings.php file:

$conf['image_suppress_itok_output'] = TRUE;
$conf['image_allow_insecure_derivatives'] = TRUE;

I got it from here http://www.drupal.org/node/1934498#comment-11679983

So my question is, why is this necessary?


texts:
I'm trying to create a test twig template in drupal 8, I followed "Create custom twig templates for custom module" from their website but it's not working for me for some reason. This is what I have:

Contents of folder test_twig_template:

test_twig_template.info.yml:

name: Test Twig Theme
type: module
description: Module to test if twig theme is working as intended
package: Custom
version: 1.0.0
core: 8.x

test_twig_template.module:

<?php
function test_twig_template_theme($existing, $type, $theme, $path) {
  return [
    'my_template' => [
      'variables' => ['test_var' => NULL],
    ],
  ];
}

test_twig_template.routing.yml:

test_twig_template.theme:
      path: /twig
      defaults:
        _controller: Drupal\test_twig_template\Controller\TestTwigTemplateController::content
        _title: 'Twig title'
      requirements:
        _permission: 'access content'

Code inside test_twig_template/src/Controller/TestTwigTemplateController.php:

<?php
namespace Drupal\test_twig_template\Controller;
use Drupal\Core\Controller\ControllerBase;

class TestTwigTemplateController extends ControllerBase {
  public function content() {
    return array(
      '#title' => 'Test Twig title',
      '#theme' => 'my_template',
      '#test_var' => $this->t('Test Value'),
    );
  }
}

And finally inside test_twig_template/templates/my-template.html.twig I have:

Test twig template!

test_var: {{ test_var }}

Thing is if I remove this "'#title' => 'Test Twig title'," from my controller nothing gets displayed on my custom page. Otherwise it just displays this title "Test Twig title".
Am I missing a call for twig somewhere or are my hooks_theme() not properly set up?


texts:
I am creating a site that increments a "day" session at midnight. Is there a way to update the timezone set for that user when they travel between time zones?

Would using javascript to pull the value from the calendar on their computer be an option? Right now we are storing timezone values in the DB so this would be a major code change, but would it work? Is there any Drupal module that could help with this?


texts: Autoplay embed video added from core Media module

texts:
Is it possible to, somehow, enable embed video autoplay for a field added form Media module?
For example media type "Video" has this option, but type "Remote video" doesn't.

Embed video field is rendered as iframe in iframe, so javascript access to second iframe is limited, if I'm correct.


texts: How to create a block with CCK dropdown lists and some values in it?

texts: As the question is clear, I want to create a block in the left sidebar and which contains sample values in it. How to do this? I am very new to Drupal


texts:
I simply want to display Product Details twice on my page.

I use Display Suite for displaying all my fields on the node (Product Display) and for displaying the field twice, I would like to use a Dynamic Field. It lets me select the field but when I view my node I get a 500 Error.

Can someone help me please?
Thank you very much in advance for your help!


texts:
I've used the FAPI #states system before to show/hide conditional fields. It's great.

However, when I am trying to show a field based on another field's value, I'm running into a problem. The documentation for this only explains how to show/hide a field based on whether my independent field has a particular value. In my case, I don't care what the exact value is, but if it has multiple values selected from a select list, I'd like to show my dependent field, and hide it otherwise.

Does the FAPI #states system support this? If so, where can I find the syntax for how to use it?


texts: How do I change position of a "fixed" element/header to go below Admin toolbar when in Admin view?

texts:
New to JS / CSS

How do I change / control the position of a sticky navigation bar to go below Admin toolbar when in Admin mode?

Site uses:

Subtheme of Omega / Commerce Kickstart
Through subtheming, I have two sticky "zones": (1) user (contains login/checkout); (2) menu-super (main menu)
User zone is sticky and came as part of the Commerce Kickstart theme and works in both regular user and admin mode.
My new "Menu-Super" works in regular user mode, but disappears behind the admin toolbar when viewing as an admin. (less than ideal.)

In the js file, I found the following:

// Handle user toolbar when user is admin and have admin toolbar enabled.
  Drupal.behaviors.commerce_kickstart_theme_custom_toolbar = {
    attach: function(context, settings) {
      if ($('body').hasClass('toolbar')) {
        $(window, context).resize(function() {
          var toolbarHeight = $('div#toolbar').height();
          $('.zone-user-wrapper').css('top', toolbarHeight + 'px');
        });
      }
    }
  }

I tried repurposing this code to handle my new zone, but no dice. When I clear cache, I can see the zone built and then pop up under the admin bar. What am I missing here?

Drupal.behaviors.commerce_kickstart_theme_custom_toolbar = {
    attach: function(context, settings) {
      if ($('body').hasClass('toolbar')) {
        $(window, context).resize(function() {
          var toolbarHeight = $('div#toolbar').height();
          var zoneuserHeight = $('div#toolbar').height()+ $('div#zone-user').height();
          $('.zone-menu-super-wrapper').css('top', zoneuserHeight + 'px');
        });
      }
    }
  }

where the css file specifies

User Zone (Working)

.zone-user-wrapper {
  background-color: #666666;
  height: 32px;
  width: 100%; }

Super Menu Zone (Not working)

.zone-menu-super-wrapper {
  background-color: #9E4934; /*Monkey brown*/
  height: 36px;
  width: 100%;
  position: fixed;
  top: 32px;
  z-index: 99;}


texts:
I would like to search for words that contains the keyword when a user executes a search. I have tried to hook into hook_query_alter():

function MYMODULE_query_alter(&$query) {
  // Check if this is a search query
  if (!$query->hasTag('search_node')) {
    return;
  }

  $conditions = &$query->conditions();
  $conditions = &$conditions[1]['field']->conditions();
  // Change the condition to '%<keyword>%'
  // and add LIKE as operator
  $conditions[0]['value'] = "%" . $conditions[0]['value'] . "%";
  $conditions[0]['operator'] = 'LIKE';
}

I can alter the search query, but I'm not getting any results.

The modified query that gets executed looks like this:

SELECT FROM {search_index} i
  INNER JOIN {node} n ON n.nid = i.sid
  INNER JOIN {search_total} t ON i.word = t.word
  WHERE (n.status = :db_condition_placeholder_0)
    AND ((i.word LIKE :db_condition_placeholder_1 ESCAPE '\\'))
    AND (i.type = :db_condition_placeholder_2)
  GROUP BY i.type, i.sid
  HAVING  (COUNT(*) >= :matches)

And the placeholders in the SelectQuery object are set to:

[:db_condition_placeholder_0] => 1
[:db_condition_placeholder_1] => %liv%
[:db_condition_placeholder_2] => node

I can verify that the tables search_index and search_total both contain a couple of words that contain liv, so this should return some results.

I have also tried Fuzzy Search module, but I don't know how I can connect the provided search to the ordinary search form.

Notice that I have tried db_like(), but without any success.

I don't understand why it should be so hard to change the default search to search through the index using a LIKE rather than = condition?

Something like this should work if I only knew how to implement it:

$keyword = $_GET['s'];
$status = 1;
$types = array('article', 'contact');

db_query("SELECT node.nid FROM {node} n
  INNER JOIN {search_index} si
    ON si.sid = n.nid
    AND si.word LIKE :keyword
  INNER JOIN {search_dataset} sd ON sd.sid = n.nid
  WHERE n.status = :status AND n.type IN (:types)
  GROUP BY n.nid", array(
    ':keyword' => '%' . db_like($keyword) . '%',
    ':status' => $status,
    ':types' => $types
  )
);


texts: Use the full name instead of the user name as author of articles

texts:
I'm coming to Drupal from Joomla.  To be honest, Drupal is a little more daunting.

I simply wish to have the author's name appear in the articles (ie, written by RealName) instead of the default (written by username).

I already have the real name field created, and can display the real name if I click on user info.

Any idea how I can have "written by realname" on articles?


texts: Grant users of role the ability to edit users that have specific role

texts: Is there a way to make it so users of role A can edit/create users with role B, but not users of role A?


texts:
Haven't been on Drupal for a while and now I seem to be lost at some points. Please help me get on the right track ;-)

I decided to build a theme based on the Stark theme and found out that the contextual menu gear widget does not appear. It's definitely a theme issue, because the widget comes up for the very same block when I switch the theme to, say, Garland.

What could be the reasone?


texts: feeds not update exist node and only add them

texts:
I am using feeds module in order to import node from csv file,
The mapping equation is

and the updating criteria set to

and my csv file contain this

guid,field_type,field_model,field_cost,
1,type1,model1,cost300,
2,type1,model2,cost300,
3,type1,model3,cost300,
4,type1,model4,cost400,
5,type1,model5,cost5,
6,type6,model6,cost6,
7,type7,model7,cost7,
8,type8,model8,cost8,
9,type9,model9,cost9,
10,type10,model10,cost10,

my problem is every time i import csv file the recorded added to my node (not update or replace), where is the problem?


texts:
I am trying to create a website. For this website, Ι am using the bootstrap business theme (Bootstrap Business Demo) of the good people of More than just Themes. I have also downloaded and enabled the Views module and the Views Bootstrap module.

I have created multiple views, all of which have as content types articles: one of them is the view studies, another one is named announcement and another one is called events. Along with these views, I have created their assorted blocks.

The blocks are customized as follows:

  Format
  : Bootstrap accordion using fields

  Fields: Content: Body , Content: Title

The problem:

I have set the blocks (three blocks each representing a different view) to appear in the themes' second sidebar. When I press the elements of any block different from the top one, the top blocks' collapse effect of the corresponding item is activated instead. That is, if I press the second accordion item of the third block, the second accordion item of the first block will be expanded(if it doesn't exist, then the second item of the second block will be expanded etc.).

The proposed solution:

I think I know why this is happening. I am currently working on the how. I used the inspect element feature of my chromium browser and came up with this:

Studies block, first element:

     Study 1

Announcements block, first element:

     Announcement 1

Events block, first element:

     Event 1

Although their data parent is different (views-bootstrap-accordion-[1-3]), all of these items reference the same collapse0 id(?) element. I am currently trying to figure out the css(?) file these point to and see if I can fix this, either by tweaking the module (views bootstrap) or the theme(bootstrap business).

Any help would be mush appreciated.


texts: How to list nodes and have them grouped by Day / Week / Month?

texts:
I have an event content type that has a date field (the time the event will take place)

I like to list these events and have them grouped by Day / Week / Month
I dislike the calendar layout, it is too messy

Any ideas are welcome

I attached this mockup of what i'm looking for. The person interested in the event's section should be able to filter the events by day/week/month

Extra question : Would it be possible to have a 'next weekend' filter (relative to the time the person is visiting the website) ?


texts: Frontpage is a menu item...title won't change

texts:
When I access site via / or /fp, I always get 'Home', this only happens for the home page...How can I change the title?

$items['fp'] = array(
    'title' => 'Front Page',
    'page callback' => 'rocdocs_main_view',
    'access arguments' => array('access content'),
    'title callback' => 'rocdocs_main_view_title',
    'type' => MENU_CALLBACK
);

function rocdocs_main_view_title()
{
    return 'THIS IS A TEST';
}


texts:
What is the proper way to address and modify a node's authored on date? I created a slew of new nodes via a CSV import via the Feeds module. These nodes now have the date of 2013-07-11 as the authored on date as that's when I did the import. But each node refers to a previous date and I need the authored on date to reflect that.
I have a content type I've created that has a separate Date field where I choose the date. I'd like to eliminate that and just use the authored on date instead.
I'm trying to use VBO to run a custom PHP snippet to make this change but the examples I've found so far do not work.
$object->created = $object->field_date[0]['value'];
node_save($object);

This snippet when run through VBO returns errors:

Notice: Undefined variable: object in eval() (line 1 of /home/chriscor/public_html  /hi_tracker/sites/all/modules/contrib/views_bulk_operations/actions/script.action.inc(20) : eval()'d code).
Notice: Trying to get property of non-object in eval() (line 1 of /home/chriscor/public_html/hi_tracker/sites/all/modules/contrib/views_bulk_operations/actions/script.action.inc(20) : eval()'d code).
EntityMalformedException: Missing bundle property on entity of type node. in entity_extract_ids() (line 7693 of /home/chriscor/public_html/hi_tracker/includes/common.inc).

Any idea what I'm missing?


texts: Path configuration in media gallery module

texts:
I am using Media gallery module to create gallery and pathauto module to generate URL.

For a gallery page I use this pattern for URL

photo-gallery/[node:title]

When user will click on any photo. I am showing that image on different page.

But I am not getting way to set path for page where the single image will be displayed.

Automatic it generates URL like this

/media-gallery/detail/356/460

Is there any way around this?
Any help will be appreciated.


texts: How can I ensure this block is properly cached?

texts:
I have been trying to get the some book menus displayed by nice menu, and after asking some questions on stackoverflow 1 and stackoverflow 2 settled on this code. My ultimate intention is to turn it into a module that creates blocks for different sets of books.

I am not sure whether this block will be cached so the queries are not computed every time. What additional code may be required to ensure this?

<?php
$master_menu = '';
unset($four_books);
  $four_books_list = "91,323,47,149";
  $four_books = &drupal_static(__FUNCTION__);
  if (!isset($four_books)) {
    $four_books = array();
    $nids = db_query("SELECT DISTINCT(bid) FROM {book} where bid in (91,323,47,149)")->fetchCol();

    if ($nids) {
      $query = db_select('book', 'b', array('fetch' => PDO::FETCH_ASSOC));
      $query->join('node', 'n', 'b.nid = n.nid');
      $query->join('menu_links', 'ml', 'b.mlid = ml.mlid');
      $query->addField('n', 'type', 'type');
      $query->addField('n', 'title', 'title');
      $query->fields('b');
      $query->fields('ml');
      $query->condition('n.nid', $nids, 'IN');
      $query->condition('n.status', 1);
      $query->orderBy('ml.weight');
      $query->orderBy('ml.link_title');
      $query->addTag('node_access');
      $result2 = $query->execute();
      foreach ($result2 as $link) {
        $link['href'] = $link['link_path'];
        $link['options'] = unserialize($link['options']);
        $four_books[$link['bid']] = $link;
      }
    }
  }

foreach($four_books as $book_nid=>$book) {
  $menu = theme('nice_menus', array('id' => $book['mlid'], 'direction' => 'right', 'depth' => -1, 'menu_name' => $book['menu_name'], 'menu' => NULL));
  $master_menu .= $menu['content'];
}
print $master_menu;
?>


texts: Setting the admin theme only inside the overlay

texts:
On my site, I have the Overlay module enabled, and I have selected an admin theme that is different from the theme used as default.
Sometimes, a page for which the admin theme is set is accessed with a direct link, and the admin theme is used. I would like to show the page with the default theme, and use the admin theme only with the overlay.

Is there a way to achieve this (module, or code to use in a custom module)?


texts: Is there a way to restore a field (in views) which has been removed using 'this block (override)'

texts: I am working with a view that has several sub-views and several fields which are common to all sub-views.  I removes a common field from one of the sub views by selecting it, setting the designation drop-down to 'this block (override)', and clicking the remove button.  This removed the field from the sub view without effecting any of the other sub-views (or the main view.)  I realized the I made a mistake when I removed that field and I would like to restore it.  Is there a way to revert an override on a view field that is no longer available on a sub view?  I would like to avoid re-adding a common filed to a sub-view (which will only be used for that sub view.)


texts: Can I change the HTTP user agent when writing browser tests?

texts:
My module has some special functionality based on the user agent of the request. I want to write tests for this functionality based on D8's BrowserTestBase, but it doesn't seem possible to change the user agent string.

The prepareRequest method of BrowserTestBase sets the user agent to the value of drupal_generate_test_ua($this->databasePrefix).

For a test, I tried changing this value to something else, and it breaks the tests.

Now I realize that there appears to be some functionality built into core based on this value that drupal_generate_test_ua returns and there's checks all over core to detect if Drupal is running within a test or not.

Is there a workaround or any hope for writing tests with a custom user agent?


texts: Change content of $page['content'] variable

texts:
I have overwritten my login page with a file named page--user--login.tpl.php. Now I have this:

    <section<?php print $content_column_class; ?>>

Xmed.be Stocksolutions

"We help you Xchange your stock"

      <?php print render($title_suffix); ?>
      <?php print $messages; ?>
      <?php if (!empty($page['help'])): ?>
        <?php print render($page['help']); ?>
      <?php endif; ?>
      <?php if (!empty($action_links)): ?>

<?php print render($action_links); ?>

      <?php endif; ?>
      <?php print render($page['content']); ?>
      NO ACCOUNT? REGISTER
      FORGOT PASSWORD?

As you can see I added two links at the end (register and password). But I would like them to be inside $page['content'], so that they are in the section. How can I edit the $content variable, loop through it or something?

UPDATE:

Now I've added in my template.php:

function hook_form_user_login_alter(&$form, &$form_state, $form_id) {
    var_dump('test');
}

But I'm not getting test around my form (also looked in html).

I've also already tried:

function hook_form_alter(&$form, &$form_state, $form_id) {
    dpm($form);
}

But no result or something ...


texts: Why does the page callback have two arguments?

texts:
function menufun_menu() {
  $items['menufun/%/bar/baz'] = array(
    'title' => 'Hi',
    'page callback' => 'menufun_hello',
    'page arguments' => array(1), // The matched wildcard.
    'access callback' => TRUE,
  );

  return $items;
}

/**
* Page callback.
*/
function menufun_hello($a = NULL, $b = NULL) {
  return t('Hello. $a is @a and $b is @b', array('@a' => $a, '@b' => $b));
}

In the menufun_menu() function, the page argument for the menufun_hello callback is only one. Why does menufun_hello() have two parameters?


texts: How to export pseudo fields display configuration to code

texts: How can I export the configuration of pseudo fields as set from the display configuration for my entities types and their bundles ? When exporting a normal fields instance (with Features) its display settings, for each available view mode, are exported with it. But I cannot find how to export the settings for the pseudo fields such as the History field of a User entity and the File field for a File entity.


texts: How do you write a drush alias for a local Vagrant box?

texts:
I'm trying to write a simple drush alias to connect to a Drupal site running on a local Vagrant instance.

I have the following in a file called ~/.drush/l.aliases.drushrc.php:

$aliases['o'] = array(
  'parent' => 'l',
  'root' => '/vagrant/docroot',
  'remote-host' => '127.0.0.1',
  'remote-user' => 'vagrant',
  'ssh-options' => '-p 2222 -i ~/.vagrant.d/insecure_private_key',
  'uri' => '127.0.0.1:8080',
);

The alias is found. drush sa returns:

l
l.o

However, when I drush @l.o status it doesn't connect to the remote host:

PHP executable        :  /usr/local/bin/php
PHP configuration     :  /usr/local/etc/php/5.3/php.ini
PHP OS                :  Darwin
Drush version         :  6.1.0
Drush configuration   :

I have confirmed that this command successfully connects to vagrant:

ssh vagrant@127.0.0.1 -p 2222 -i ~/.vagrant.d/insecure_private_key

Debugging output doesn't show an SSH command so far as I can tell:

SIG-106:ilob justin$ drush --debug @l.o status
Bootstrap to phase 0. [0 sec, 3.78 MB]                               [bootstrap]
Drush bootstrap phase : _drush_bootstrap_drush() [0.01 sec, 3.98 MB] [bootstrap]
Loaded alias @l.o from file /Users/justin/.drush/l.aliases.drushrc.php [0.01 sec, 3.99 MB]                                                                        [notice]
Cache MISS cid: 6.1.0-commandfiles-0-807b6772846e18b2741e8d5b7119b4cc [0.01 sec, 4 MB]                                                                             [debug]
Cache SET cid: 6.1.0-commandfiles-0-807b6772846e18b2741e8d5b7119b4cc [0.01 sec, 4.02 MB]                                                                           [debug]
Bootstrap to phase 0. [0.05 sec, 9.56 MB]                                                                                [bootstrap]
Found command: core-status (commandfile=core) [0.08 sec, 9.56 MB]                                                                                [bootstrap]
Loading outputformat engine. [0.13 sec, 9.6 MB]                                                                                [notice]
Calling hook drush_core_status [0.14 sec, 9.65 MB]                                                                                [debug]
Returned from hook drush_core_status [0.14 sec, 9.66 MB]

I know I must be doing something stupid but I just can't see it.


texts: View with two filter groups using "OR" not aggregating correctly

texts:
I have a view that I need to count the number of items currently unread. It is a list that combines slightly different entities on slightly different conditions, so I have two filter groups(using OR) on my view to select all content appropriately. This works well except for the aggregation of the results. When I set the view to aggregate by counting a nid field, it doesn't aggregate the results. Instead, it simply converts each nid result to display as "1".

Where is my attempt to aggregate this view going wrong?

My filters:

My Results:


texts: Programmatically create node with select List

texts:
I'm trying to add nodes via a JSON feed. However, I'm having trouble setting the value of a select list field.

I have this at the moment:

$node->field_name[0]['nid'] = $drupal_array[trim($branch[0])]

Which when I output the node object at the end of execution works correctly but when it comes saving the node this individual field isn't saving at all.

Would anyone be able to tell me what I'm doing wrong. I can paste more code if you need it.

$drupal_array is used to convert the text input of $branch[0] to a numerical value.

This is the inserted value.

["field_name"]=>
    array(1) {
        [0]=>
            array(1) {
                ["nid"]=>
                    int(193)
           }
    }

This is the renderable array output of the same field.

["field_name"]=>
    array(1) {
        [0]=>
            array(1) {
                ["nid"]=>
                    string(3) "193"
            }
    }


texts: Getting a book tree/menu programatically

texts:
Given a node ID, how do I display the outline of the book it belongs to?

I'm dispatching the pages of the book from a custom, variable, route (and not the alias of the node) so the default book navigation block doesn't work.


texts: Make variable available in template file

texts:
I am creating a custom template file for a views table and I need to put some links in the footer of the table, these links belong to 3 nodes. How can I make this data available in my template file which is - views-view-table--my-view-name.html.twig

Is there a pre-process of some sort that I can use?


texts: Using Infinite Scroll module with Views paging: Detrimental to Google SEO?

texts:
I love using the Infinite Scroll module with Views. But does Google limit indexing to to only those first bunch of nodes which appear in the view?

I'm guessing that when using a regular pager, Google will dig deeper and index all subsequent pages in the view. But what does it do when ajax is used to move forward to the next batch of nodes as is the case with Infinite Scroll?


texts: #states and #ajax are not working on pop up

texts:
I need to get form only with HTML. To do this, I've used delivery callback in hook_menu(). This is my sample code:

function test_menu() {
  $items['htmlform'] = array(
   'access callback'  => TRUE,
   'page callback'    => 'test_htmlform'
   'delivery callback' => 'delivery_text_plain',
   'type'             => MENU_CALLBACK,
 );
  return $items;
}

In this form, I've used #states and #ajax.

I've another form which is in the normal callback. I need to show htmlform into this Drupal form. So I've written a ajax callback to 'htmlform', get html, paste it into the drupal form & show this in pop up.

This is my ajax callback:

$.ajax({
    url: '/htmlform',
    success: function(data) {
      $('#formpopup').empty();
      $('#formpopup').html(data);
      $("#form_demo_pup").modal({backdrop: 'static',keyboard: false});
      Drupal.attachBehaviors($('#form_demo_pup'));
    }
  });

Now the drupal form page have all the CSS and JavaScript but the pop up (htmlform) have only the HTML.

On this pop-up, #states and #ajax are not working since it has no Drupal form JavaScript.

How do I fix this? Even I tried "Drupal.attachBehaviors" in my custom ajax.


texts:
I have a pattern set up to create the URL aliases based on a field of type list text.

the field looks like this:

selection 1|selection 1

selection 2|selection 2

How can I alter the alias so it will show something like this:

www.example.com/1-was-selected rather than www.example.com/selection-1

UPDATE:
I'm using Pathauto for the patterns.


texts: hook_views_pre_render -> how to access variables

texts:
I have a view of teasers, and would like to check the status of each node.
Using hook_views_pre_render (in the template.php file of the theme), I can access:

$view->style_plugin->row_plugin

Which gives me the output below (only first few lines printed, using debug):

entity_views_plugin_row_entity_view::__set_state(array(
 'entity_type' => 'node',
 'entities' =>
 array (
  0 =>
  stdClass::__set_state(array(
     'vid' => '19',
     'uid' => '1',
     'title' => 'My Node Title',
     'log' => '',
     'status' => '0',
     'comment' => '1',
     'promote' => '0',

However, I can't figure out how to access the status variable.

debug($view->style_plugin->row_plugin->entities());

produces a white screen, any variation that I tried either returned NULL or a white screen.

Any help greatly appreciated.


texts:
To add custom text to a node I have a code like this:

function mymodule_node_view($node, $view_mode, $langcode) {
  $var=....;
  if (.....) ){
      $node->content['new'] = array(
       '#markup' => $var,
     );
  }
}

It works perfectly, but now I need to add this text to pages that don't load any node. So I can't use this hook.

I mean something like the drupal_set_message function, showing custom text at the top of certain pages.


texts: Option for auto Masspay in ubercart marketplace

texts: Is there any auto Masspay option in ubercart marketplace module. Now working with manual payment method.


texts: When is a module shown as 'Unsupported' in the list of available updates?

texts:
In the available updates, there are few modules with the note unsupported.

What does that note actually mean?


texts: Date field displayed with wrong timezone with PHP's date_create + date_format

texts:
I have an Event content type with a Date field with a start and end date.

When this field is being displayed in a view, it displays properly, with the time matching the value that was entered.

On a different page, I am overriding field--field-date.tpl.php and using date_create and date_format to print out the date and time separately.

$start_date = date_create($node->field_date['und'][0]['value']); //dont hate me
$end_date = date_create($node->field_date['und'][0]['value2']);
//...
print date_format($start_date, 'g:i A') . ' - ' . date_format($end_date, 'g:i A');

As you can see, it is displaying 4:00pm instead of 12:00pm. It looks like a timezone translation is happening (or not happening) somewhere. I tried to screw around with the time zone argument for date_create but nothing actually changed the way the date displayed.

When I dump the date field out with devel, I get,

dpm($node->field_date['und'][0]['value']);
dpm($start_date);

How do I actually display the proper timezone for my date with PHP in my field--field-date.tpl.php?


texts: Should I put my site on maintenance mode before using "drush sql-dump"?

texts: When performing drush sql-dump, should I set the site in maintenance mode or will this command makes sure a coherent dump will be generated even if users are busy using Drupal? I can't find confirmation in the documentation.


texts: Make download available after purchase of a physical good

texts:
I am running a UC Shop with Drupal which sells CDs and LPs and most of the time everything works like it should do.

Now I want to improve the service for our customers. For this reason, I want to give them the chance to download a zip-file with mp3s of every CD or LP they bought.

After we received the payment (so we set the order status to "payment received") the customers should get an encrypted link via mail or alternatively have a download button in their profile or so. It's no problem to make that possible only for authenticated users.

Any suggestions?


texts: How to fix this issue in drupal7 using windows

texts:
How to fix this issue ?

  Fatal error: require_once(): Failed opening required
  '/var/www/.../includes/sites/all/modules/entity/includes/entity.inc'
  (include_path='.:') in /var/www/.../includes/bootstrap.inc on line
  3139


texts: How do I check if a single on/off checkbox is checked?

texts: There does not appear to be any way to check the value of a single on/off (boolean) checkbox in the data selector for the Rules module.  If "field-MyField" = checked or "field-MyField" = 1, then do 'blah'.  Can Rules do this?  I must be missing something


texts: Rendering a form element without drupal_get_form?

texts: I'm trying to render a simple form element without the accompanying  tags and other drupal goodness (validation, etc). Is it possible to render a form element using form api methodology but without running it through drupal_get_form?


texts:
     I have a webform where users insert their informations, after that the manager consulted the submission, he change the workflow state of the submission to : submission approved or submission rejected, if it's approved, then the coordinator must add attached files, after that, the finance manager should be able to download the files then to validate the submission, in the end the user can see the attached files and be able to download them, but during the process user must not see the attached files.
     It would be great if anyone give me an idea if there is a module can help me controlling attached files access. I'm using Drupal 7.


texts:
I want to create different view pages for different vocabulary types.

For each vocabulary I created a view and assigned a filter to limit to one vocabulary; as a page path I'm using taxonomy/term/% (on every view). It seems like only one view is working. For all others no details displayed (just an empty page is showing up).

Is this a valid approach? What can I do to display different taxonomy term pages for each vocabulary?

Also, the solution tvi doesn't work.


texts: how to get the form id of a particular form using Devel execute PHP in drupal 7?

texts: I wanted to get the form id of particular forms to customize those forms. I dont want to use form alter hook to obtain the form id every time. I wanted a simple way to acquire the form_id of the forms. Like a simple PHP snippet that can be executed in Devel execute PHP to obtain the form ID. or is there any other way to do it?


texts: How to display nodes that belong to a certain term twice on the same page using Views in D7?

texts:
is it possible to display nodes that belong to a certain term twice on the same page?

This is my case:

I use Taxonomy Term view to display term pages. That one has a page display that uses "taxonomy/term/%" path to overwrite regular term pages
Taxonomy Term view is used to display 10 items, but with the offset of 1 item (first item is skipped).
I would like to display the first item in a separate block in one of the sidebars.

I hoped that this can be achieved with just copying the settings of the Taxonomy Term view "page" display to a "block" display, i. e. with using the same "has taxonomy term ID" contextual filters, but it doesn't get displayed.

How can this be achieved?

Thank you in advance!


texts: Using entity metadata wrapper with custom entity type

texts:
I've created custom entity. In addition I want to add user reference field to my entity:

if (! field_info_field(MY_FIELD_NAME)) {
  // Create the field.
   $field = array(
    'field_name' => MY_FIELD_NAME,
    'type' => 'entityreference',
    'cardinality' => FIELD_CARDINALITY_UNLIMITED,
    'settings' => array(
        'target_type' => 'user',
        'handler' => 'base',
        'handler_settings' => array(
            'target_bundles' => array()
        ),
    ),
    'bundles' => array (
        MY_ENTITY_NAME =>
            array (
                0 => MY_ENTITY_BUNDLE_NAME,
            ),
    ),
);
field_create_field($field);

    // Create the instance.
    $instance = array(
        'field_name' => MY_FIELD_NAME,
        'entity_type' => MY_ENTITY_NAME,
        'bundle' => MY_ENTITY_BUNDLE_NAME,
        'label' => '',
        'description' => '',
        'required' => TRUE,
        'widget' => array(),
        'display' => array(
            'default' => array(
                'label' => 'hidden',
            ),
        ),
    );

    field_create_instance($instance);
}

In form submit I want to add users references to this field:

   foreach($result as $recipient) {
        $wrapper->{MY_FIELD_NAME}[] = $recipient->uid;
    }

I gets:

  Fatal error: Cannot use object of type EntityDrupalWrapper as array

What I am missing?


texts: How to change the behaviour or display of the language switcher?

texts:
On translated pages the language switcher shows links to translated languages, but for untranslated languages there is no link, but the name of the language without a link. In the case, that there is no corresponding node in a given language, i would like the language switcher to show a link to the front page instead.

How can i accomplish this behaviour? Thank you very much!


texts: how do I add a table and where clause to query object using hook_views_query_alter()?

texts:
I currently have a unique situation whereby I need a to use a different term reference field in a view's contextual filters based on a node's content type value. I don't want to have to manually add a display for each possible combination of content types so I have been tying to use hook_views_query_alter() to accomplish what is now seeming impossible to me.

In my .module file I have:

/**
 * Implementation of hook_views_api().
 */
function mymodule_views_api() { // your module name into hook_views_api
  return array(
    'api' => 3,
    'path' => drupal_get_path('module', 'mymodule').'/includes',
  );
}

Then in the file mymodule/includes/mymodule.views.inc:

/**
 * Implements hook_views_query_alter()
 */
function mymodule_views_query_alter(&$view, &$query) {
   //this is the name of our View and Display
   if ($view->name == 'shop' && $view->current_display == 'listings') {

       $query->add_table('field_data_field_my_category');
       //then add where clause afterwards etc etc
   }
}

This throws the error:

  Fatal error: Call to undefined method SelectQuery::add_table()

Which leads me to believe that the Views API is not loading properly, unless I'm completely on the wrong track here.

I've been trying to find the best practices for altering views queries but have just ended up being generally confused and frustrated. Could anyone lead me towards the light please?


texts:
I know Gmap is designed to work with the location module, but most spatial devs now suggest geofield as the "better" spatial data storage module.

I had to use geofield for an open layers map, and now I want to move away from the location module but I don't want to have to reimplement my other Google maps on the site.

So I can I painlessly switch?


texts: Drupal redirects to site.local/install.php

texts:
I was working on my branch this morning tweaking some CSS when all of a sudden my Drupal site went into a dead mode. I am running multi site mode and the local.settings.php in the individual sites is being ignored on load.

The parent settings.php file is also being ignored on load.

The site redirects to the installation url: http://site.local/install.php

What could have possibly went wrong and how do I go about resolving that?


texts: How can I use PHP to print a view in the content area of a page?

texts:
The Private Message module displays conversations between users as "threads" that resemble e-mail or forum friends.  I am attempting to customize the default display by printing a view that shows the recipient/sender profile information.

Through trial and error I arrived at the following code, which prints out the view content pane that I want.

  foreach($thread['participants'] as $participants => $participant ) {
    global $user;
    if ($user->uid !== $participant->uid) {
      print views_embed_view('profile_show_user_interests','show_interests_own', $participant->uid);
    }
  }

This code resides in privatemsg.pages.inc in function privatemsg_view($thread), which returns the content of the page for rendering.

The problem with this is that print views_embed_view() prints the content pane out at the top of the page, above the header, with no extra markup.  How can I print the content pane in the content region of the page?


texts:
I have the following problem with the simple_oauth module.

I can get the initial jwt token with a POST request to /oauth/token with the following form data:

username: user
password: password
client_id: xxxx
client_secret: yyy
scope: oauth
grant_type: password

This token has the actual access token and the refresh token. So I have an interceptor in Angular to refresh the token when we get a 403 return code. The call to refresh the token is again a POST request to /oauth/token with a slightly different payload:

client_id: xxxx
client_secret: yyy
scope: oauth
grant_type: refresh_token
refresh_token: def5020092674bfb5c570c518c112fbc78ec6ddb2d...

This call also succeeds but when I try to use the returned token I will get 403 returns. It is like the tokens produced using one grant type or the other have different scopes...

Have you experienced this problem? Do you know what can I do to solve it? Thank you very much in advance.


texts: Tying together creation of multiple content types in a form

texts:
I need to make a content creation form that ties in the creation of two different content types.

Imagine garage and cars as an example. There is a one-to-many relationship between garage and cars, so one garage can have 0 to many cars.

I've created the content types and established the relationship between them but I need to figure out how to best support the user in creating content. I think it is important that distinction between content types  is more or less transparent to the user, so he could be creating his garage at one point, then later on come back to add cars. Or he could be creating a garage and adding two cars in one go. Or he could go in and create a car without even assigning a garage.

I imagine accomplishing this by having a form for adding garages and a form for adding cars, but near the end of the 'create garage' form I have the option of either assigning an existing car I have created earlier (probably using an autocomplete textfield) or load the 'create car' form in a modal window allowing to create a new car right before submitting the garage form (the relatioship will then be established right away).

My question is how to accomplish this best from an architectural point of view.

Should I write a completely custom module and maybe place it in a block with panels or could I get by simply by creating a hook that changes the content creation forms for cars and garages? Or maybe you know about a contrib module that fixes this for me out of the box?

Furthermore, I imagine the end result being soaked in asynchronous requests, allowing the form to be validated and saved asynchronously. For an early proof-of-concept I could live with "nested save buttons", though. I will most likely be using AngularJS for some of the realtime stuff. Should I look into exposing the content types as a REST service build and the entire page in AngularJS right away? (something I am planning to do further down the line anyway, but I also need to have something up and running quickly and I imagine a rewrite for Drupal 8 in a not too far future. So I would prefer not having to learn how to build services in Drupal 7).


texts: Question about steps to convert from Ubercart to Drupal Commerce

texts:
After running into some discount functionality/module install issues with Ubercart for Drupal 7, my client has agreed to try Drupal Commerce. Do I need to completely remove everything related to Ubercart before Drupal Commerce can work, or can I unpublish the existing Ubercart content and disable the modules to allow my client to give it a test drive?

I see that there are some machine names that are the same from one to the other, which could pose a problem.


texts: How to programmatically code a block to show taxonomy vocabulary as an unordered list?

texts:
I'm trying to build a menu using a taxonomy vocabulary with its hierarchical structure.
I don't want to use any module to do it.

In this page I see that I can grab the terms for a given vocabulary and do it programmatically http://drupal.org/node/113651

But I need some help to star coding it.

I have a Taxonomy called: Products (the tid is : 2)

Products has the following terms and hierarchical structure:

--Cars
----Volvo
----Ford
--Games
----Football
----Rugby
----Videogames
------Pacman
------Call of Duty

PHP CODE to generate:

Cars

Volvo

Ford

Games

 Football

 Rugby

Cars

 Pacman

Call of Duty


texts: Best approach to create a troubleshouting section?

texts:
I am looking to create some kind of troubleshooting section on a website. Sort of like the Windows help with some sections, questions and answers.

I was thinking of doing this with a regular Book, and write a small form module which allows me to track the page with a "Was this information helpful or not?" question.

But are there possible alternatives, either existing modules or an approach which works best?


texts: How do I restrict a content type to a subset of vocabulary?

texts:
I have a hierarchical general taxonomy vocabulary called tags. Some of the terms are only relevant to particular content types; e.g., the "Apples" content type might have a sub-tree in the vocabulary with Cox, Granny Smith, and the "Oranges" content type might have Seville in its vocabulary sub-tree.
When editing an Apple node, I don't want users to be able to select Seville as this doesn't make sense.

I have put the terms into one vocabulary because other content types (e.g. blog articles) might want to tag against any of these.


texts:
I am making a template in Drupal 8. At this moment, I made a theme in the /themes directory; there, I have my .theme file and a copy of the html.html.twig file from the core/themes/stable directory.

I have enabled Twig debugging mode and in the Chrome inspect tool I read the following.

<!-- FILE NAME SUGGESTIONS:
   * html--front.html.twig
   * html--.html.twig
   x html.html.twig
-->

I added the following hook to the theme file.

function testTheme_suggestions_html_alter(array &$suggestions, array $variables) {
    $suggestions[] = 'html__testHTML';
}

After clearing the cache, there isn't any change to the file name suggestions.

Also I have activated kint() in html.html.twig file that is located in my theme root, but kint() also shows only these variables.

'theme_hook_suggestions' => array(2)
string(6) "html__"
string(11) "html__front"

Why doesn't the new suggestions appear?


texts: A deleted module is appearing in getEditable('core.extension')

texts:
Using Drupal core 8.9.6, created a custom module called wdocsApi. I wanted to rename it, so I uninstalled it and created wdocs_api. The problem is, when I try to install the new one, I get the error

Drupal\Core\Extension\Exception\UnknownExtensionException: The module wdocsApi does not exist. in Drupal\Core\Extension\ExtensionList->getPathname() (line 522 of core/lib/Drupal/Core/Extension/ExtensionList.php).

I tracked it down to Drupal/Core/Extension/ModuleInstaller.php where a call is made to $extension_config = \Drupal::configFactory()->getEditable('core.extension'); and my old module is returned in the list of modules.
What can I do to erase any remnants of the old one from my database?


texts: How can I attach a line item field to a custom checkout pane?

texts:
How can I attach a line item field (as form element) to a custom checkout pane ?

I tried the following with commerce_line_item_save($line_item);

function MODULE_pane_checkout_form($form, &$form_state, $checkout_pane, $order) {
  //...
  //1st TRY, which in my opinion should be the right API fn ?
  global $language;
  field_attach_form('commerce_order', $order, $pane_form, $form_state, $language->language, array('field_name' => 'field_paxsup'));

Which returns

  Fatal error: Cannot access empty property in field.attach.inc on line
  208.

field.attach.inc on line 208  $items = isset($entity->{$field_name}[$langcode]) ? $entity->{$field_name}[$langcode] : array();

Precision: the custom checkout pane is working great with a basic field as below

$pane_form['nickname'] = array(
 '#type' => 'textfield',
 //and so on...
);


texts: Date filter to choose only current month contents

texts:
What filter do I need to apply to display only current month content. Am using Drupal 7.

I want to display automatically all content created within the current month.


texts: Deprecated code cleanup: Updating EntityManager to EntityFieldManagerInterface

texts:
EntityManager is deprecated so I am trying to update code for Drupal 9. The documentation says it should usually be changed to EntityTypeManager, but in this case the code is using getFieldStorageDefinitions so it needs to be EntityFieldManagerInterface.

I changed this line:

  $fields = \Drupal::entityManager()->getFieldStorageDefinitions($entity_type);

To:

  $fields = \Drupal::EntityFieldManagerInterface()->getFieldStorageDefinitions($entity_type);

Which gives this error when I run behat:

  [error]  Error: Call to undefined method Drupal::EntityFieldManagerInterface() in _drush_behat_get_entity_field_types() (line 95 of /app/drush/Commands/contrib/behat-drush-endpoint/behat.inc) #0 /app/drush/Commands/contrib/behat-drush-endpoint/behat.inc(123): _drush_behat_get_entity_field_types('node')

However, I don't understand this error, because EntityFieldManagerInterface does have getFieldStorageDefinitions.

How can I update entityManager to EntityFieldManagerInterface?

Here's the full function if that's useful:

function _drush_behat_get_entity_field_types($entity_type) {
  $return = array();
  $fields = \Drupal::entityManager()->getFieldStorageDefinitions($entity_type);
  foreach ($fields as $field_name => $field) {
    if (_drush_behat_is_field($entity_type, $field_name)) {
      $return[$field_name] = $field->getType();
    }
  }
  return $return;
}


texts: Commerce Module allowing user to customize product

texts:
is drupal commerce able to allow user customization of products in the following way. Imagine your product is a bike.
You want your user to:

Change color of the bike (and therefore changing price, depending on chosen color)
Change wheel type (and therefore price)
Change type of break (brand for example)
Further, the individual product should be saved (cookie for example) and one should be able to share a link to the individual product (here I saw many examples where sharing the product does not work - because you will always go to the default product)

I was looking out there but could not find many shops that solve the descriped tasks.

I used commerce kickstart on simplytest.me - https://ds64.ply.st/tops/guy-short-sleeve-tee
to have a quick view. If I change the color, add it to the shopping cart, click on checkout and click on edit item again, I will end up at the standard configuration. Therefore the whole configurator does not make sense if I can not edit and save my individual customized product.

Nice to have a descriptive text that summerizes the chosen attributes and therefor for example a max. weight of the bike could be calculated...

Nike for example generates a url with a random id that can be used to share the customized product...

http://store.nike.com/us/en_us/product/air-max-95-id/?piid=40361&pbid=166815001#?pbid=166815001

Thanks for your aswers in advance!
Pedro


texts: How can I securely expose data through Drupal (via REST or something else)

texts: I'm looking to use Drupal to pull in data through forms etc, probably in the form of content types, and then expose these, probably via REST, to other things. I've had a look at the services module, but I'm concerned about securing this, and am going to be using certificates to do so. Is there anything out there that currently supports this sort of thing, or am I getting into custom made module territory here?


texts: Show only nodes that are connected via entity reference with views

texts:
I am trying to create a simpler version of Organic Groups as I don't need most of it's functionality. What I am trying to do is use entity reference, nodeaccess_userreference and nodeaccess_nodereference to duplicate the bulk of what OG does.

At the moment I am trying to create the view to show all content types content that is linked to a "group" content type.

Content types:

Group

Link

Text Post

(basically reddit.com!)

Fields:

field_group - entityreference to group content type attached to link and text post.

field_shortname - textfield with a shorter name for group (no spaces, alphanumerical, etc..)

Views:

Format: Unformatted List

Page: /g/% <---so I can use group name or shortened name to access group page

Relationships:

Entity Reference: Referenced Entity to field_group (required)

Contextual Filters:

Content: Title

Content: Field_shortname

Content: NID

(all requiring relationships to Entity Reference)

This way if some one goes to /g/Long-Group-Name-Blah-Blah /g/Shortername or /g/3 they will all point to the correct group page and show the link and text post content type content.

I can sort of get it to work if I just use Content: NID as the contextual filter. But I would like to be able to use the group name or shorter version in the URL as well. It also stops working as soon as I add 2 contextual filters.

Any help on getting this to work.

Thanks


texts:
For SPECIFIC webforms, how can I make it not save data to the database, but just send the email? It should however still save the files and link to them in the email.

Idk if I can use something like this: https://www.drupal.org/project/webform_clear since this seems to work on all webforms, while I wanna use it only on specific ones.

Thanks


texts: Is it possible to give users different roles/profiles on different part of the website?

texts:
For example, is it possible to give userA full read/write access on some part but read-only access on others?

Most importantly, is this possible without too much hassle? I mean what I'm  looking for is some sort of "inheritance", i.e.  if I give userA full read/write access on nodeA, I'd like those exact same rights are granted to userA on every child node of nodeA, recursively.

I've seen Flexi Access but this module does not seem to satisfy my "inheritance" constraint.


texts: How to mock a node field value for phpunit?

texts:
I'm working on a project where we need to have code coverage using phpunit.

I have a method that includes this code:

  $node = \Drupal::entityTypeManager()->getStorage('node')->load($node_id);

  $form['data-title']['#value'] = $node->label();

  $form['data-description']['#value'] = $node->field_description->value;

So I need to mock out the node object.

I can get the node label to work, but not the field_description->value

Here's my set up function in my test class:

/**
   * {@inheritdoc}
   */
  protected function setUp() {
    $container = new Container();
    $container->set('string_translation', $this->getStringTranslationStub());

    $renderer = $this->getMockBuilder(Renderer::class)
      ->disableOriginalConstructor()
      ->getMock();
    $renderer
      ->method('render')
      ->willReturn('Hello world');

    $container->set('renderer', $renderer);

    // Mock entity type manager.
    $this->entityTypeManager = $this->getMockBuilder(EntityTypeManagerInterface::class)
      ->disableOriginalConstructor()
      ->getMock();

    // Mock a node and add the label to it.
    $node = $this->getMockBuilder(Node::class)
      ->disableOriginalConstructor()
      ->getMock();
    $node->expects($this->any())
      ->method('label')
      ->willReturn('shaken not stirred');

    $node->expects($this->any())
      ->method('access')
      ->willReturn(TRUE);

    $node->expects($this->any())
      ->method('id')
      ->willReturn(1);

    // @todo figure out how to add a field to a mock node.
    /*$field_description = new \stdClass();

    $field_description->value = 'This is a description';

    $node->set('field_description', $field_description);*/

    $node_storage = $this->getMockBuilder(EntityStorageInterface::class)
      ->disableOriginalConstructor()
      ->getMock();
    $node_storage->expects($this->any())
      ->method('load')
      ->willReturn($node);
    $this->entityTypeManager->expects($this->any())
      ->method('getStorage')
      ->willReturn($node_storage);

    $this->uuid = $this->getMockBuilder(UuidInterface::class)
      ->disableOriginalConstructor()
      ->getMock();

    $container->set('entity_type.manager', $this->entityTypeManager);

    $entity_repository = $this->getMockBuilder(EntityRepository::class)
      ->disableOriginalConstructor()
      ->getMock();
    $entity_repository->expects($this->any())
      ->method('getTranslationFromContext')
      ->willReturn($node);

    $container->set('entity.repository', $entity_repository);

    \Drupal::setContainer($container);
    $this->form = MyForm::create($container);

  }


texts: Has anyone encountered behaviour similar to this and have any idea how to resolve it? I've checked the issues for Rules and can't find anything similar. I've run update.php and flushed caches, neither make a difference. Also tried completely uninstalling Rules and Rules UI and reinstalling from fresh.


texts:
In a Rule, how can I prevent executing subsequent actions if the first action fails?

In my case, I want the order to be marked as Processing only if the order was successfully transmitted to the fulfilment center. I've tried returning FALSE from the action but this has no effect.


texts: Order confirmation email with html content?

texts: I'm using drupal commerce with its submodules and need to change order's confirmation message to html format and add line items and customer profile. How can I organize this?


texts: How should I setup Drush to work with Drupal 8.8.1 using Git Bash on Windows 10

texts: I am using a Windows computer and using Git Bash, I just installed a new 8.8.1 site and also did 'composer require drush/drush'. I can't use Drush from anywhere so I am wondering if I should have installed Drush globally on the computer.


texts: I have running 20+ Drupal 6 sites on php 5.4 without large issues, but what about php 5.5?


texts: Multiple comma-separated values in View contextual filter only producing an OR query, not an AND

texts:
I have a View with one contextual filter, a taxonomy field. Entering a single value works as expected: the results are filtered by the taxonomy term ID.
The requirement is to allow an AND combination of terms: The argument 69,78 should only show nodes that have both tags.
"Allow multiple values" is selected:

However both 69,78 and 69+78 result in the same query that uses an IN clause:
... WHERE ((node__field_tags.field_tags_target_id IN('69', '78'))) ...

The view has no relationships. The query is set to use DISTINCT. Am I missing something?


texts: Date field repeat in same day but different time

texts: I have an Events Content Type with Date Field. How can I repeat the date in different time? For sample, I want to show the event for "Sep 9, 10am-11am" and "Sep 9, 1pm-2pm". I see there is a repeat option for Date, but not the time. I also found # 4 in this Article has mentioned "runs more than one time per day" option, but I don't see this in Date field.


texts: Filter to only nodes with an image in an imagefield

texts:
I'm sure this can't be difficult, but it has me stumped.

In my view, I want to exclude nodes that do not have an image in a specific field. The field allows an unlimited number of images. I don't care about the exact quantity, just that there are more than 0.

How do I create this filter and what do I filter on?