texts: Implementing a search and results page in the admin interface

texts:
I'm trying to implement a search and results form in the admin interface but I am having trouble getting the search function and pager working.

[1] The pager is not showing at all. I've got this working using db_select for the query but I'd like to use a solr query. How can I get a pager to display?

[2] The form submission is not working as expected either. On submission the page is redirect to the correct url but an error message is displayed: The requested page '/admin/monitor/custom/search/?q=foobar' could not be found. Do i have to declare a separate menu route /admin/monitor/custom/search/% to handle searches?

Many thanks,

function custom_menu(){
    $items['admin/monitor/custom/search'] = array(
      'title' => 'Custom',
      'description' =>'Custom search form',
      'page callback' => 'drupal_get_form',
      'page arguments' => array('custom_form'),
      'access arguments' => array('administer site configuration'),
    );
    return items;
}

function custom_form($form, &$form_state){

    $table = build_results_table();

    $form['keyword'] = array(
      '#type' => 'textfield',
      '#description' => t('Search database by keyword'),
    );

    $form['submit'] = array(
      '#type' => 'submit',
      '#value' => 'Go!'
    );

    $form['results'] = array(
      '#markup' => $table,
    );

    return $form;
  }

function build_results_table($search_term){

    // perform query using Solr Search API
    // page number from $_GET('page')
    // search limit from a variable set by another module
    $results = query_database();

    $header = array('Firstname', 'Middlename', 'Surname');

    $rows = //... build rows from $results ...;

    $table = theme('table', array(
      'header' => $header,
      'rows'=>$rows,
    ));

    pager_default_initialize($table);
    $table .= theme('pager');

    return $table;
}

function custom_custom_form_submit($form, &$form_state){

    $keyword = $form_state['values']['keyword'];
    drupal_set_message(t('Showing results for %keyword',
    array('%keyword' => $keyword)));

    $form_state['redirect'] =
    '/admin/monitor/custom/search/?q='. $keyword;

}


texts: How do you use 'drush site-install' to install a multisite with separate databases using a single command?

texts:
I regularly use drush site-install to install single Drupal 8 sites from the command line. It works great.

I'm now working on building a Drupal 8 multisite. It'll have separate databases per site.

Can drush si be used to install a multisite from the command line? Does it use Drupal8's sites.php?

I saw Need Steps to Install multisite configuration using only drush. i.e multi-site install having different database, but I'm not clear on what's actually done there.

I figured it should be able to, but I can't find any HowTo docs for multisite.


texts: How to redirect URL of kind node/nid to its url alias

texts:
I want to replicate the effect seen in http://www.drupal.org/node/1 , where you are redirected to drupal.org/about.

I have a fresh Drupal 7 installation, I create a node with a path, and don't get the effect. I have tried with module Path Auto, and nothing.


texts: How to automatically generate anchor ids to CKEditor added headers

texts:
How can i automatically generate anchor ids to h2 and h3 added using ck editor ?
I need it for making a table of content.


texts:
I need to create a view with contextual filters that displays all nodes below the specified term.

Examle:

Colors

Blue

Cerulean
Slate

Yellow

Bright

Hi-liter
Pastel Yellow

Not so bright
Mustard

(Bold represents nodes)

So "Colors" would list Cerulean, Slate, Hi-liter, Pastel Yellow, and Mustard.

"Yellow" would list Hi-liter, Pastel Yellow, and Mustard.

"Bright" would list Hi-liter and Pastel Yellow.

etc.

How can I create a contextually-filtered view of nodes by taxonomy term that takes the entire lineage into account?


texts:
How can I add stocks in Ubercart while adding products?

I insert a new field in the product setting. How can I link the stock with the product?


texts: AJAX-form replaced div comes back empty when logged out

texts:
I have an AJAX form that replaces a section of itself successfully when the user is logged in. But when logged out, the demo-area section comes back with the #prefix and #suffix but no item-header or item-display. $files is an array of my objects that create the custom-themed sections successfully. I can't figure out what is causing them to return empty in AJAX when logged out.

I think permissions are fine. When logged in, the initial form load and AJAX replacements work as intended. When logged out, the demo-area loads correctly with the page, but is then replaced with only #prefix/#suffix on AJAX calls.

Here is the part of my form builder function in question:

$files = array();
foreach ($node->field_file[$node->language] as $field_file) {
  $files[] = new ClientDemoItem($field_file);
}

$form['file-index'] = array(
  '#type' => 'select',
  '#options' => array_keys($files),
  '#default_value' => 0,
  '#ajax' => array(
    'callback' => 'client_demo_load_item',
    'wrapper' => 'client-demo-area',
  ),
);

$file_index = isset($form_state['values']['file-index'])? $form_state['values']['file-index'] : 0;

$form['demo-area'] = array(
  '#prefix' => '
',
  'item-header' => $files[$file_index]->buildHeader(),
  'item-display' => $files[$file_index]->buildDisplay(),
  '#suffix' => '
',
);

Here is the simple AJAX callback:

/*
 * Replace the demo area with the requested file display
 */
function client_demo_load_item($form, $form_state) {
  return $form['demo-area'];
}

Here is what the buildHeader() function does:

  public function buildheader() {

    $item = array(
      '#theme' => 'client_demo_item_header',
      '#url' => file_create_url($this->uri),
      '#description' => $this->description,
      '#filename' => $this->filename,
      '#filesize' => filesize($path),
      '#timestamp' => $this->timestamp,
      '#fid' => $this->fid,
      '#item_file' => $this,
    );

    return $item;
  }


texts: How to disable the Submit button on a the delete page form?

texts:
I made a form_alter and trying to disable the submit button by greying it out by using the #disabled option on the form api. I know i can just do a unset() on the submit button, but was wondering how to use the #disabled. I tried the following:

$form['actions']['submit']['#disabled'] = TRUE;

But that doesn't do anything it seems. Here' my krumo output:


texts: Add extra values to the the document in JSON API Response

texts:
I have JSON API with filters. Its working fine.
For example:

{baseURL}/jsonapi/node/article?filter[X]=Y&sort=title&fields[node--article]=title,drupal_internal__nid

At the end of the Response I want to add some extra values. After digging through the jsonapi module, I found a Class file where the Response data is being prepared and sent from.

core/modules/jsonapi/src/Normalizer/JsonApiDocumentTopLevelNormalizer.php

In the normalize function, I want to add my info something like this:

$document['MY_INFO'] = "This is the extra Information";

The code for normalize function is:

  public function normalize($object, $format = NULL, array $context = []) {
    assert($object instanceof JsonApiDocumentTopLevel);
    $data = $object->getData();
    $document['jsonapi'] = CacheableNormalization::permanent([
      'version' => JsonApiSpec::SUPPORTED_SPECIFICATION_VERSION,
      'meta' => [
        'links' => [
          'self' => [
            'href' => JsonApiSpec::SUPPORTED_SPECIFICATION_PERMALINK,
          ],
        ],
      ],
    ]);
    if ($data instanceof ErrorCollection) {
      $document['errors'] = $this->normalizeErrorDocument($object, $format, $context);
    }
    else {
      // Add data.
      // @todo: remove this if-else and just call $this->serializer->normalize($data...) in https://www.drupal.org/project/jsonapi/issues/3036285.
      if ($data instanceof EntityReferenceFieldItemListInterface) {
        $document['data'] = $this->normalizeEntityReferenceFieldItemList($object, $format, $context);
      }
      else {
        $document['data'] = $this->serializer->normalize($data, $format, $context);
      }
      // Add includes.
      $document['included'] = $this->serializer->normalize($object->getIncludes(), $format, $context)->omitIfEmpty();
      // Add omissions and metadata.
      $normalized_omissions = $this->normalizeOmissionsLinks($object->getOmissions(), $format, $context);
      $meta = !$normalized_omissions instanceof CacheableOmission
        ? array_merge($object->getMeta(), ['omitted' => $normalized_omissions->getNormalization()])
        : $object->getMeta();
      $document['meta'] = (new CacheableNormalization($normalized_omissions, $meta))->omitIfEmpty();
    }
    // Add document links.
    $document['links'] = $this->serializer->normalize($object->getLinks(), $format, $context)->omitIfEmpty();
    // Every JSON:API document contains absolute URLs.
    return CacheableNormalization::aggregate($document)->withCacheableDependency((new CacheableMetadata())->addCacheContexts(['url.site']));
  }

What will be the right way to achieve this ? Of course we don't want to modify the same class file. Which class/file should be created to alter this and what will be the right way to add a value like this ?

$document['MY_INFO'] = "This is the extra Information";

Update:
I found a way to add my extra values to it using:

$document['MY_INFO'] = CacheableNormalization::permanent(["XX"=> 'MY INFORMATION']);

Now my question is how do I implement it in my custom module? I don't want to edit the core files.


texts: Entity reference field dependent on entity reference in referenced entity of another entity reference field

texts:
I have a content type 'order' with 2 entity reference fields. One is a reference to another content type 'brand' and the other is a reference to a taxonomy term 'categories'.

Now the content type 'brand' has an entity reference field aswell, containing a selection of taxonomy term 'categories'.

When creating a new 'order' I can select a 'brand'. Now the second field with the 'categories' should only show taxonomy terms available (selected) for the selected 'brand'.

I have tried to achieve this with the second entity reference field (categories) to use a view.

In this view I configured the following:

Relations:
- Content using field_categories
- Content referenced from field_brand

This worked when I had only 1 brand, since this brand was not connected to all categories. But now with multiple brands, the view just returns all the terms used in ALL brands.

Any idea how to achieve what I try? Any help is very appreciated. Thank you!


texts:
I can't manage to get the video link of a media, I can achieve this with a picture but with videos it doesn't work.

This is the code I am using.

function slider_get_uri_by_media($media, $style = 'background'){
  // kint(isset($media->file_media_video_file));
  if (isset($media->field_media_image)){
    $file = $media->field_media_image->entity;
    if ($file && $fid = $file->id()) {
      $image = File::load($fid);
      if ($image_style = ImageStyle::load($style)) {
        return ['url' => file_url_transform_relative($image_style->buildUrl($image->getFileUri()))];
      }
    }
  }
  elseif (isset($media->file_media_video_file)) {
    $file = $media->file_media_video_file->entity;
    if ($file && $fid = $file->id()) {
      $video = File::load($fid);
    }
  }
}

Why cannot I get the path for the video stored in $media->field_media_video_file?


texts: I'm using drupal 7.41 and have used Webform for my leave applicaiton form and there are such approvals fields that I've displayed in views, I'd like to make it editable in views by checking multiple records and it can be approved on views list page, can anybody please suggest some hints?


texts: How to capture form fields to programmatically create new users

texts:
I briefly worked with Drupal several years ago, and now have come back to it for a single project. For all intents, I'm a total beginner. I need to create a new user from a custom form (html in a block.) I've found some info on how to do the back-end processing (this and this), but can't figure out how to capture the form submission values in my custom module. Can I just use $_POST values? Is that allowed? Or is there some other way I'm supposed to go about it?

My initial module code looks like this:

function create_vector_user_block_info() {
    $blocks['create_vector_user'] = array(
    // The name that will appear in the block list.
    'info' => t('Create Vector User'),
    // Default setting.
    'cache' => DRUPAL_CACHE_PER_ROLE,
  );
  return $blocks;
}

function create_vector_user_submit() {
    //This will generate a random password, you could set your own here
  $password = user_password(8);

  //set up the user fields
  $fields = array(
    'name' => 'user_name',
    'mail' => 'user_name@example.com',
    'pass' => $password,
    'status' => 1,
    'init' => 'email address',
    'roles' => array(
      DRUPAL_AUTHENTICATED_RID => 'authenticated user',
    ),
  );

  //the first parameter is left blank so a new user is created
  $account = user_save('', $fields);

  // If you want to send the welcome email, use the following code

  // Manually set the password so it appears in the e-mail.
  $account->password = $fields['pass'];

  // Send the e-mail through the user module.
  drupal_mail('user', 'register_no_approval_required', $email, NULL, array('account' => $account), variable_get('site_mail', 'noreply@example..com'));
}

What I need to do is get the value of a username and email field in my custom block and pass them to the elements in the $fields array.


texts: View that uses both taxonomy terms and title(or nid) in contextual filters

texts:
Is it possible to create a view that uses both taxonomy terms and the node title or nid as contextual filters?

Ideally this would mean that you could have one view that just handled the taxonomy terms eg. the parent-taxonomy-term/child-taxonomy-term view would display all the nodes matching those taxonomy terms and parent-taxonomy-term/child-taxonomy-term/node-title would display a different view with more information on the specific node returned.

Is such a view possible and if so how would i set it up (all my experiments at this have failed)?

The reason I require this is that I wish a view of the same node to be accessible via a number of different taxonomies. I am creating a store where users can see the same gold diamond ring by navigating on the main dropdown menu via 'Jewellery > Rings', 'Gemstones > Diamond' or 'Metal > Gold'. While the user is navigating in this way the breadcrumb trail and url are looking good 'jewellery/rings' etc. But when a product is clicked on and its node is viewed it has its own url that can only fit the pattern of one of the taxonomies. So the breadcrumb trail would suddenly change when getting to the product via another taxonomy.


texts: How to dpm() the Drupal.settings.basePath var

texts:
For debugging purposes I need to use dpm to output the value of Drupal.settings.basePath. I tried this (but not working):

dpm(Drupal.settings.basePath); // not working


texts: Drupal 7 - Anyway to make Facebook Picture take place of User Picture if not available

texts:
I am creating a view of users that displays a list of Users with Picture and Name. This drupal install allows facebook users to sign in and automatically have an account created. Their account is also added to this jCarousel view.

The problem I am facing is that when a user signs up from Facebook, but does not upload an image directly to drupal, their facebook picture does not show on the list. Anywhere else on the site, however, their facebook pictures shows with the profile.

On the views field, I have:

User:Picture
User:Name

Is there anyway to have a logic in the view where I can request the Facebook Picture if User:Picture is not available?

Thank you in advance,


texts: I have a custom field that is an unordered list that I want to be placed under a static title and to the left of an advertisement. I only want this to show on article pages, but right  now I can't seem to figure out how to place the custom field where I want it to be placed. I know a module is required, but what I am asking is if anyone can give me the correct hooks or whatever to retrieve the custom field information, so I can place it where needed.


texts: Add rule for a webform checkbox to autosend email after specified time

texts:
Im running D7 with webform.  I have a multstep form, on the last step the user is asked to participate in a future survey.  If they enter their email and check the box to agree, they should receive an email reminder with a  link to a new survey I have created in two weeks from when they agreed.

Im planning to use webform rules, rules, and token modules to create this feature.

Am I going to be able to verify the condition and generate a scheduled email using these modules?  Or do you think I should focus my efforts on a custom module?


texts: How to set the default "Show as expanded" to true in a custom menu item

texts: I am creating a series of menus in a custom module. This site also has a custom theme. Is there a way in the theme, or in the module, to set a menus "Show as expanded" to true. This way, if I move my site, uninstall, or whatever, it comes back the way it should right out of the box.


texts: How to figure which function(s) are triggered upon file download to check permissions

texts:
I am experimenting with private file system, done custom way :) .

There is file system/files/test.txt (That is, private://test.txt).

When I try to access the file, I get access denied from Drupal, as expected (site redirects to Access denied page, and dblog shows that accesss have been denied).

But now I want to know what module/function have blocked access to the file. I am blindly trying to check hook_file_download or hook_file_download_access, but as far as I can see it does not go through that functions.

All that in attempt to solve this.


texts:
I have node  golosuizaprognoz_lenta with hidden field argument-lenta, node golosuizaprognoz with field field_argument, view of table with Rating wiget:

The node have title with date, for example 21/06/14 Голосуй за прогноз!!!

I need that in node was view only with date equal date in title.

What I have done:

I add to node golosuizaprognoz_lenta hidden field argument-lenta where I add url of result node, for example 210614-golosuy-za-prognoz.

I make EVA display:

with contextual filter:

when I insert content of field field_argument wich equal of url node  golosuizaprognoz_lenta , for example  all OK, I get what I want, but in node I have no this view (without contectual filters view is shown so I attached it).

How I need to fit contextual filters that in node I will see only views with content wich have field field_argument wich equal of url node  golosuizaprognoz_lenta.

http://myforecast.esy.es/210614-golosuy-za-prognoz/


texts: Modify node in hook_node_view() for Drupal 7

texts:
I'm trying to modify the array of content, and add an extra link.

I don't want to use the Link module; this link is going to be generated with other fields, it's something like Computed Field module (which is in developing stage for Drupal 7, and I'd rather not use it).
I don't want to just add HTML/PHP to node.tpl.php. I want this to be nice solution.

I've been trying with adding new field to $node->content. I managed to copy another field and display it once again. I was able to change label of that field, but not the link itself.

Does anyone have any idea on how to proceed?


texts:
I have a few OG Groups and now I want to limit the taxonomy term selection for each group. For the first part I'm planning on checking if the user is a member of a certain group and then proceeding accordingly. So far, so good. The problem is, that I really have no idea how to actually limit the term selection. I tried something with the form api, but I just keep getting fatal errors when saving a node.

So... Can you guys help me limit the term selection? Telling me what do I actually need to do would really help. Thanks.


texts: A good markdown that supports syntax highlighting like SE sites?

texts:
I'm looking for a Markdown module or something similar to Stack Exchange sites Markdown.
It would be great if it provides syntax highlighting for some languages.

Do you have any suggestions?


texts: Which Rules event can I use to send a weekly mail to all users using Rules?

texts:
I'm using Drupal 7 and I need to send a weekly mail to all users.

I want to use the Rules module to do this. But I couldn't find a Rules Event which allows for this.

How can I implement that?


texts: Form with AJAX callback to query database and display info in block['content']

texts:
I have a simple select form that I want to use as a "Sort By" handler. When user chooses a different option I want it to change the query and display the new results. E.G. sort by duration ASC or sort by duration DESC.

This is my form:

function mortgage_multi_view_sort_form($form, &$form_state) {
     $form = array();
     $sortOptions = array(
        1 => t('Mortgage Duration: Shortest to Longest'),
        2 => t('Mortgage Duration: Longest to Shortest'),
     );

     $form['mortgage_sort'] = array(
        '#type' => 'select',
        '#title' => t('Sort By'),
        '#options' => $sortOptions,
        '#default_value' => 1,
        '#required' => TRUE,
        '#ajax' => array(
            'event' => 'change',
            'callback' => 'ajax_select_callback',
            //'wrapper' => 'replace_model_div',
            'method' => 'replace',
            //'effect' => 'fade',
        ),
     );

     return $form;
 }

When they change this to Longest to Shortest I want to asynchronously display the mortgages in reverse order. Is this best to do in the callback function?

My callback function (currently):

 function ajax_select_callback($form, &$form_state){
 switch($form['mortgage_sort']){
    case 1:
        $result = db_query('SELECT * FROM {mortgage_database} ORDERBY duration DESC');
        displayMortgages($result);
        break;
    case 2:
        $result = db_query('SELECT * FROM {mortgage_database} ORDERBY duration ASC');
        displayMortgages($result);
        break;
 }

}

In my displayMortgages() function it just takes the entire query and displays it in a table. How do I get this information to block['content'] from my displayMortgages() now?


texts: Profile 2 display field on my account page

texts: Use this module - Profile2 Registration Path and Profile2 -  when registering, so that would be made at check-in person was filling certain fields, in this regard, I have a question - how do I display the fields that person fills during registration, on the profile page?


texts: How can I execute a JavaScript function before the form submission handler is called?

texts:
I was trying to save an image in the database using the following code.

function myid_user_page_form() {
  $form = array();
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'Save',
    '#attributes' => array(
      'id' => 'myid_save',
    ),
    '#submit' => array('formsave_action'),
  );

  return $form;
}

function formsave_action($form,&$form_state) {
  $save  = db_update('student',array('target' => 'import'))
    ->fields(array('id_status' => '1'))
    ->condition('stud-id', '101-03043', '=')
    ->execute();

  if ($save) {
    drupal_set_message("Successfully saved.");
  }
  else {
    drupal_set_message("Unsuccessfully save.");
  }
}

The JavaScript file content is the following.

 $('#myid_save').on('click', function(e) {
   myid_save_signature();
   myid_save_photo();
 });

In my case, the two JavaScript functions aren't called; the page refreshes before they are executed. I want to run those functions before formsave_action() is called.
How can I achieve this?


texts: Different behaviour saving programatically vs UI

texts:
I am having a problem saving nodes programatically.  I am attempting to save nodes that use the following pathauto pattern for an alias:

[node:og-group-ref:0:url:relative]/[node:menu-link:parents:join-path]/[node:title]

Both the first and last token work fine both ways.  However, the middle token - [node:menu-link:parents:join-path] - returns empty when saving through a script and populates fine when saving through the UI.

I've inspected $node object that is being passed through in each case and they are identical, except for $node->path.  When saving through the UI the $node->path value looks something like this (copied from devel dsm message):

[path] => Array
    (
      [alias] => communications/some-person
      [pid] => 153
      [source] => node/100
      [language] => und
      [pathauto] => 1
    )

However, when saving programatically $node->path looks like this:

[path] => Array
          (
            [pathauto] => 1
            [alias] =>
          )

As you can see, its missing data that is present when saving through the UI, and I suspect that data is needed to correctly parse the token.

Anyone have any idea why these two would be different or why the [node:menu-link:parents:join-path] token doesn't work when saving through the script?

If it matters, script is pretty straight-forward:

<?php
$nids = db_query('SELECT nid FROM {node} where nid = 100')->fetchCol();
foreach (node_load_multiple($nids) as $node) {
  echo "Saving node " . $node->nid . "\r\n";
  print_r($node);
  node_save($node);
}

Thanks in advance.


texts:
I have 3 content types. Town, Hotel and Price. Hotel has a node-reference to Town, Price has a node reference to Hotel.

I'm trying to create a block view to use one the Town node page displaying a list of Hotel nodes in that town, together with the lowest Price (field_price of the Price node).

Is something like that achievable with views? I did manage to get a list of all hotels in a town by using a contextual filter, but I can't seem to get the additional step of getting the prices in the view.

A custom module would obviously be an option, but if it's possible with views, I would prefer that solution.


texts:
In my project i am using the Rules module to schedule the sending of emails to some users on my site.

At cron run, the scheduled emails are sent as expected.

However I found out that at each subsequent cron run, the mails are repeatedly sent to users.

When i checked the "queue table" in my database, i found out that at each cron run, the "expire value" of the rules_scheduler_task is reset into the current date.

Is this the cause of the problem?

Please how can this be resolved? I want emails to be sent only once.


texts: Rewrite negative number into positive numbers

texts:
I'm preparing some charts, with positive and negative values.
I would like to create one pie chart, including all the values (the positive and negative). Of course, this doesn't work as only positive numbers should be considered.
So I tried to rewrite the results (to cancel the "-") but it doesn't work. I would like to have "-100" displayed as "100", and the "100" staying at "100", so that I can create my graph.

Does somebody has an idea?


texts:
Price Field Type from the Commerce module package is not exportable for Feeds. So as a work-around, I saved my prices ('min price', 'hot price' and "deposit price') into  normal Float fields and just move the values to the Price Field Types  on-the-fly. And so here it is (set using Rules: After an item is saved of content type 'Property'):

$node->field_price_amount['und'][0]['value'] = [node:field-current-price-temp];
$node->field_hot_price_amount['und'][0]['value'] = [node-field-hot-price-temp];

etc.

and then applying the node_save($node) with $node->is_new set to FALSE.

All the other values are saving properly except for the field type defined by the Commerce module. No actual data saved to tables at all.

"$node->field_price" should be the right machine name I have defined for this field. But for some reason importing leads to error field_price_amount cannot be NULL. This is also weird. So I changed it to field_price_amount so it won't complain but still not saving despite no more errors in importing. (The db table is still named field_data_field_price but for some reason it is complaining as 'field_price_amount should not be null ).

Anyone have ideas?


texts:
I am able to migrate organic groups easily enough, but when I attempt to migrate the group content, I am not able to successfully migrate the "parent" group ID(s) (or group audience if you prefer). I could only find snippets of code, and never a complete example, so hopefully I'm missing something simple.

Here is my complete migration code for the group content (as per multiple sources, but for example and per the OG issue page:

  $arguments = $common_arguments + array(
    'description' => t('Migration of group nodes from Drupal 6'),
    'machine_name' => 'RanchoNodeGroupNews',
    'source_type' => 'groupnews',
    'destination_type' => 'groupnews',
  );
  Migration::registerMigration('RanchoGroupNewsMigration', $arguments['machine_name'], $arguments);

class RanchoGroupNewsMigration extends RanchoNodeMigration {
  public function __construct(array $arguments) {
    parent::__construct($arguments);

    // OG Audience field
    $this->addFieldMapping('og_group_ref', 'og_group_ref')
         ->separator(',')
         ->sourceMigration('RanchoNodeGroup');
    $this->addFieldMapping('is_public', 'is_public');
    // Set the default owner to rm.com
    $this->addFieldMapping('uid', 'uid')
         ->defaultValue(4);

    $this->addUnmigratedSources(array(
    ),'DNM', FALSE);

    $this->addUnmigratedDestinations(array(
    ),'DNM', FALSE);

  }

  protected function query() {
    // Get the default query
    $query = parent::query();
    $query->leftJoin('og_ancestry','oga','n.nid = oga.nid');
    $query->addExpression('GROUP_CONCAT(DISTINCT oga.group_nid)', 'og_group_ref');
    $query->addField('oga', 'group_nid', 'group_nid');
    $query->addField('oga', 'is_public', 'is_public');

    return $query;
  }

  public function prepareRow($row) {
    if (parent::prepareRow($row) === FALSE) {
      return FALSE;
    }
    drush_print_r($row->og_group_ref);
    return TRUE;
  }

  public function prepare($node, stdClass $row) {
    // Set og field_mode to 'admin' so we can save this group content despite not being a member of the group.
    // See https://www.drupal.org/node/2399997
    if (!empty($node->og_group_ref[LANGUAGE_NONE])) {
      foreach($node->og_group_ref[LANGUAGE_NONE] as $delta => $value) {
        $node->og_group_ref[LANGUAGE_NONE][$delta]['field_mode'] = 'admin';
      }
    }
    drush_print_r($node->og_group_ref);
  }
}

The output I receive from drush_print_r is as follows:

drush mi RanchoNodeGroupNews --idlist=60274 --user=1
56288
Array
(
    [und] => Array
        (
            [0] => Array
                (
                    [target_id] => 56288
                    [field_mode] => admin
                )

        )

)

Processed 1 (1 created, 0 updated, 0 failed, 0 ignored) in 0.2 sec (267/min) - done with 'RanchoNodeGroupNews'

                          [completed]

Note that nid 56288 is indeed the parent group node, and is the only parent that has been migrated. I am able to edit the group content and set the parent manually. Any idea what's wrong with my code?


texts: How to call a function when a node is being viewed?

texts:
Whenever I view a node page, I want to call a function but I'm not sure how to do that.

I was thinking I should use hook_menu() and declare the path as node/%, and attach a callback function to that path. Is that the right way, or is there a correct/better way?


texts: View display nodes with taxonomy term found in URL

texts:
Using Drupal 8

I have a working setup my problem is when I try to access a taxonomy term that is made up of two words.

Set up.

View : shows nodes of content type A
Has relationship (required) with a field in the content type that stores the taxonomy term (one or more terms need to be associated to each content type)
Has contextual filter (that uses previous relationship) to get the taxonomy term from the URL. The filter gets the default value from Raw value from URL with Path component: 2 , and it has Use path alias instead of internal because the URL has the taxonomy term name. It also has Specify validation criteria by Taxonomy term name by Transform dashes in URL to spaces in term name filter values so that fan-art can be correctly matched to taxonomy term fan art.

I have no problem with taxonomy terms made up of one word, it's the ones made up of two words that are giving me a headache, any ideas?


texts:
I like to have a general api for sending notification. I am not sure if there is out there somewhere for Drupal.

For instance, is should be possible to provide a node id and some criterias for which users to send notifications to. The options could be something like "not to the node author", "all who has commented on the node except specific ones (perhaps a comments that has just been written), true/false on sending notification to user who already got a notification about new comments, etc.

There are probably other notification scenarios that could be supported. It would be nice with a general notification framework for Drupal. It seems to be lacking right now (I have looked at subscription and notification). However, I am new to Drupal and might have missed something.


texts:
Can anyone tell me how to set the taxonomy in the following order

super Category---eg(Area)
Category--- eg(food)
sub category --- eg(fruits)

if a visitor chooses a super category area, then the fruits in that area should be shown
 And the path should be http://www.example.com/supercategory/category/subcategory/apple.php


texts: Warnings still show on page even after setting Error messages to None in Logging and Errors

texts:
I have set the Error messages to display to None

but still the website shows warning messages on top.

Also cleared the cache after this but the anonymous user can still see warning messages.

Is there anything else to be changed?


texts:
I removed some fields from phpmyadmin; now I get the following error from Drupal:

  PDOException: SQLSTATE[42S02]: Base table or view not found: 1146 Table 'restech1_newDrupal.field_data_field_contactus_images' doesn't exist

I removed the contactus_images field together other fields I wasn't using, in order to make space on my server.

How do I get the site to come back?


texts:
I have a custom module which contains a template directory and a .tpl.php. I would like to add a specific stylesheet for this template. Right now, my tpl-file looks like:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML+RDFa 1.0//EN" "http://www.w3.org/MarkUp/DTD/xhtml-rdfa-1.dtd">

  <title>My Title</title>
 <link rel="stylesheet" type="text/css" href="sites/all/themes/mytheme/css/styles.css" />

My content

And it works, but only partially... How can I include the css stylesheet in a more proper (read: more Drupal) way? I've tried the drupal_add_css(), but with no results... But maybe I did it the wrong way. Any suggestions?


texts: How to hide node by Role similar to the Hide Block by Role module?

texts:
Does anyone know of a module similar to the "Hide Block by Role" module, but for nodes?

The scenario I'm looking to achieve is:

User 1 has Role A and Role B
User 2 has Role A and Role C

I need to be able to create a node and limit access to Role A and Role B, but also hide/block it for Role C. So, User 1 would see the node but User 2 would not. Currently, because User 2 has Role A, he is able to see the page which is why I need something similar to "Hide Block By Role".

I'm currently using the Content Access module to control access.


texts: How to Make Required Fields Temporarily Optional?

texts:
Under a specific Content Type with a ton of fields, my coworkers create nodes.

Most of the fields are required because we do not want any incomplete nodes.

However, since there are so many fields, is there a way for people to Save the node as a draft even without the required fields being filled out?

My first instinct was to use the Conditional Fields and have a Boolean called "Draft" that allows users to Check/Uncheck. Checking the box would cause each field to be Optional instead of Required.

However, since there are so many fields, each field would have to have conditions set to it individually.

That is my fallback solution, but is there a way I can accomplish this in a less tedious way?


texts: Programmatically Place View With Defined Fixed Contextual Filter

texts:
I'm currently using the starter module which adds the Twig function place_view(). This works well in most cases, however I'd like to be able to pass another parameter to populate the fixed value given in a contextual filter.

This would be my contextual filter settings:

Here's the place_view() Twig function:

public function place_view($name, $display_id = 'default') {
  $drupal = \Drupal::service('renderer');
  $view = views_embed_view($name, $display_id);

  if(! is_null($view)) {
    return $drupal->render($view);
  }

  return null;
}

Preferably I'd like to be able to use place_view() with a parameter to adjust that fixed value. It'd be even better if I could somehow reference the contextual filter I wanted to adjust the fixed value of.

Hopefully that all made sense, thanks in advance.


texts: How to remove the global library from specific page??

texts:
How to remove the global library from specific page ?

I want to rearrange java script files.


texts: Does DrupalWebTestCase::drupalGet() use the permissions of DrupalWebTestCase::$loggedInUser?

texts:
I'm trying to test the permissions of a particular role, and this code:

$this->drupalLogin($this->editor_user);
$this->drupalGet($node->path['source']);

returns a 200 (OK) status, when I'm expecting a 403 (forbidden).

Does DrupalWebTestCase::drupalGet() ignore the permissions of the currently logged-in user, and if so, how can I test page view permissions?


texts: Views - how to pass number field to javascript?

texts:
I need to create settings javascripts with data from views row. So I used views_php module and created next view field structure:

Taxonomy term: Name (string, hidden)
Taxonomy term: Max price (numerical, formatting turned off, hidden)
Taxonomy term: Min price (numerical, formatting turned off, hidden)
PHP field

In PHP I used next :

drupal_add_js(array(
  'term' => array(
    'name' => $row->name,
    'max_price' => $row->field_min_price,
    'min_price' => $row->field_max_price,
  )
), 'settings');

But, e.g. for next values :
- Name: 'test term'
- Min price: 0
- Max price: 1000
I getting next JS:

{
  name: 'test term',
  min_price: 1,
  max_price: 1,
}

Both of min_price and max_price fields contains 1. Also, when I showing this fields at view - I can see correct values in rendered HTML, but not in JS.


texts: Cannot see Display Suite menu under Administration

texts:
I am following this training. I have downloaded the module and have also enabled it. The video mentions a new 'Display Menu' under 'Administration'. I can't see it, though I am logged in as an administrator.

What am I doing wrong? (I am still new to Drupal)

UPDATE

I just tried to install the Module on a fresh install, and I don't get an issue there. Looks like my current system is corrupted. Is there any tool to 'correct' it?


texts:
I have used VBO on a view for a particular set of nodes that have a flag associated with them. In the view I have included a javascript toggle button for each node so a user can flag the nodes they want one at a time. When clicked, this button runs a custom PHP script to do some external stuff. I have then implemented hook_flag_validate so that if this external stuff fails for any reason, the node isn't flagged and an error message is displayed to the user.

This all works fine when clicking an individual toggle button, but the problem occurs when I try to flag the nodes with VBO. The nodes are still flagged or not flagged depending on the success of the PHP script, but the message displayed to the user by VBO is always a success message.

I would like to find a way to allow VBO to 'see' which flagging have failed or not (so to see the return value of hook_flag_validate for each node) and then to display a custom message describing which flagging have failed and which have succeeded.

I am using Drupal 7.41.


texts:
I have a node being pulled into a modal with overlay using Colorbox Node but it's pulling in more markup and pieces of the page than I really want.

After trying to pick through some user threads on drupal.org, the only solutions I saw suggested were ones that only work for Drupal 6 and/or break when page caching is enabled.

Is there a robust way to template the output of nodes in modals in Drupal 7?


texts: Getting other fields during a Drupal Services GET

texts:
I made the following request via GET: api/node?fields=nid,title,field_media

But I'm getting the errror: Invalid query provided, double check that the fields and parameters you defined are correct and exist. SQLSTATE[42S22]: Column not found: 1054 Unknown column 't.field_media' in 'field list'

I'm assuming its only looking at the node table, but how do you make it grab all the fields of this content type?

I couldn't easily find the documentation of these endpoints and how to call them properly. How is everyone figuring this out?


texts: Multiple Drupal Commerce line items in the database but one in the order page

texts:
I am doing a report module to show various information about drupal commerce orders and line items.

I am now facing a problem with the line items:

For some orders, in the commerce_line_item table, there are multiple line items for the same product and quantity.

However, in the order page of these orders, I only see one line item.
I suppose only one of these line items is the good one, but how can I know which one is good in the table?

They looks the same except the line_item_id field which is different.
So how can I get the line items of an order without any of these dupplicate line items?

Why are there dupplicate line items in the table?

For instance, this query:

SELECT SUM(quantity)
FROM {commerce_line_item}
WHERE order_id = 388

gives me 5 intead of 1.

Note:

I am using Drupal Commerce 7.x-1.3.

Dump for the order 388:

-- commerce_product
product_id  revision_id sku     title   type    language    uid status  created changed data
1   52  sku     Product Name    product_type    und     1   1   1342634788  1352819763  [BLOB - 4o]
-- commerce_order
order_id    order_number    revision_id type    uid mail    status  created changed hostname    data
388     388     1865    commerce_order  123     mail@example.com    completed   1359728586  1359755276  1.2.3.4     [BLOB - 208o]
-- commerce_order_revision
order_id    order_number    revision_id revision_uid    mail    status  log revision_timestamp  revision_hostname   data
388     388     1838    984     mail@example.com    cart    Log message     1359754659  1.2.3.4     [BLOB - 6o]
388     388     1859    984     mail@example.com    checkout_checkout   Log message     1359754827  1.2.3.4     [BLOB - 6o]
388     388     1860    984     mail@example.com    checkout_review     Log message     1359754829  1.2.3.4     [BLOB - 6o]
388     388     1861    984     mail@example.com    cart    Log message     1359755005  1.2.3.4     [BLOB - 6o]
388     388     1862    984     mail@example.com    checkout_checkout   Log message 1359755034  1.2.3.4     [BLOB - 6o]
388     388     1863    984     mail@example.com    checkout_review     Log message     1359755074  1.2.3.4     [BLOB - 74o]
388     388     1864    984     mail@example.com    checkout_payment    Log message 1359755075  1.2.3.4     [BLOB - 153o]
388     388     1865    0   mail@example.com    completed   Log message     1359755276  1.2.3.4     [BLOB - 208o]
-- commerce_line_item
line_item_id    order_id    type    line_item_label quantity    created changed data
773     388     product     sku     1.00    1359754516  1359754829  [BLOB - 232o]
763     388     product     sku     1.00    1359728686  1359728686  [BLOB - 232o]
762     388     product     sku     1.00    1359728699  1359728699  [BLOB - 232o]
761     388     product     sku     1.00    1359728689  1359728689  [BLOB - 232o]
758     388     product     sku     1.00    1359728642  1359728642  [BLOB - 232o]

Thanks for your help.


texts:
In my field's description, I want to link to more documentation. If I do it like this:

$form['field_name'] = array (
  '#description' => t('Here are some words about') . ' ' . t('stuff') . ' ' . t('and things and whatnot'),
);

It works. It looks like this:

  Here are some words about stuff and things and
  whatnot.

If I do it the proper way, like this:

$form['field_name'] = array (
  '#description' => t('Here are some words about @stuff and things and whatnot', array('@stuff' => l('stuff', 'blah')),
);

Then the HTML is generated and then output into my description as raw text, like so:

  Here are some words about stuff and things and
  whatnot.

Why is the "correct" way not working?


texts: Will the site load slower when using a sub-theme of a sub-theme?

texts:
In Drupal, you have a base-theme, and maybe a sub-theme. That sub-theme can also have another sub-theme.

Will Drupal be slower when using 3 themes, where each of them is a sub-theme of the previous one, or doesn't this affect the performance?


texts:
Is it possible to add PHP bits to nodes? I would like to achieve something like this:

Some paragraph I blablabla blablabla blablabla blablabla...

<?php Some PHP code I with echo statements ?>

Some paragraph II blablabla blablabla blablabla blablabla...

Some paragraph III blablabla blablabla blablabla blablabla...

<?php Some PHP code II with echo statements ?>
...

If yes, how can I achieve this?


texts: Biased results based on node type (Search API Solr)

texts:
I want to create a weight bias for all of my node types.

Node Types:

Articles
Blog
Content

The situation:

Right now Articles will be mixed in with Blog and Content. What I want is whenever there is an "Articles" node returned I want them to show first no matter what. Second would be Blog, third would be Content.

-

What I have done:

I have looked into possibly trying to bias using the QueryElevationComponent but that elevates based on the Solr Doc ID which I would have to manually set for each node. I have also looked into boosting based on the value of a field but this is numerical in nature I would somehow need to get a numerical value associated with every document that was a reflection of the Content Type's order. This doesn't seem like the best way to go.

-

References:

http://wiki.apache.org/solr/QueryElevationComponent
http://wiki.apache.org/solr/SolrRelevancyFAQ#How_can_I_change_the_score_of_a_document_based_on_the_.2Avalue.2A_of_a_field_.28say.2C_.22popularity.22.29

-

Results from hook_search_api_solr_search_results_alter

results (Array, 10 elements)
    15681 (Array, 3 elements)
        id (String, 5 characters ) 15681
        score (Float) 4.8259773
        fields (Array, 2 elements)
            search_api_id (String, 5 characters ) 15681
            search_api_relevance (Float) 4.8259773


texts: How to find which module is causing PHP warning

texts:
In the Recent log messages I get this message repeated many times:

  Warning: array_flip(): Can only flip STRING and INTEGER values! i
  DrupalDefaultEntityController->cacheGet() (rad 388 av
  C:\wamp\www\includes\entity.inc).

I assume that the problem lies within one of the modules I have installed, but after spending the whole day trying to narrow down which module is causing the problem, without luck, I post this question. I have read other answers that relates to the same log message, but they did not help me.

Anyone that can explain how to get more info out of that warning?


texts: How do I access an Entity Reference's field values?

texts:
I have 2 content types.

BaseContent:
Field1: Title
Field2: ID#

RelatedContent:
Field1: [Entity reference to a BaseContent]
Field2: **[Automatically insert the value of the referenced BaseContent here]**

But I can't work out how to do the part in the **s.

I feel like it should be easy, but nothing I have tried has worked.

Can I do it with any of the following:

-Tokens?

-Entity References using a Views Selection Type and relationships?

-Programatically with PHP (using the Computed Field module?)

If so, how?

any help much appreciated!


texts: Create a derived field for a custom Drupal 7 Entity for use with Views

texts:
I've created a really simple entity; basically it's for news headlines - that is, links to articles on other sites. (Using nodes would have been overkill). I've used the entity module to take care of the heavy-lifting, and everything's working nicely.

Thus, my entity has a title and a URL field.

This entity then needs a "rendered link" field - the title, linked to the URL. Essentially just a call to l() - that's the easy part. I've got this working in the most part by adding a new "derived" field to the entity, by overriding the entity controller's buildContent method.

What I now want to do is make this available as a field in my Views. All my other fields are available, and whilst I know how to override a views handler and use hook_views_data_alter for a given field which maps to a pre-existing schema column, e.g.:

/**
 * Implements hook_views_data_alter().
 */
function mymodule_views_data_alter(&$data)
   $data['table']['column']['field']['handler'] = 'my_custom_view_handler_field';
}

...what I can't work out is how to create a "derived field" such as this, where there's no one-to-one mapping with a schema field.

Any ideas?


texts: How to show a user login form on a completely separate page?

texts:
I am developing a application where I want to restrict everything from anonymous users. If anyone tries to access any page from url directly they will be redirected to login page. How to do this?

Also I want show the login page in a completely separate page where there should be no menu or any other links, just the login form (like for example: google login page). What is the best way to do this.


texts:
I'm transitioning a Drupal 6 site to Drupal 8.1 so following the official instructions, I set up a new install in its own directory. Since this is only one site, I followed the instructions to put my database credentials in sites/default/default.settings.php after the declaration of the $databases array.

Running drush --status returns the following.

Drush version          :  8.1-dev
Drush temp directory   :  /tmp
Drush configuration    :
Drush alias files      :
Drupal root            :  /media/psf/Home/apps/newp
Drupal Settings File   :  MISSING

Since this Drupal is 8.1-dev that must mean I need to upgrade it. Since this is a global install using Composer, I run composer global update.

  Your requirements could not be resolved to an installable set of
  packages drush/drush dev-master requires codegyre/robo ~1.0.0-beta1

Checking the drush-ops page on github doesn't show any anomalies like this nor my Google search.

What am I overlooking?


texts: I'm adding OG to and existing site with hundreds of existing nodes. I'm looking for a way to assign existing content to groups. Sort of OG after-the-fact. Does anyone have any recommendations?


texts:
I have a product (for example, "Desk") which has two attributes (size and life). Size has the values small, medium, and large. Life has the values 7 years and 10 years.

The price is different for each variation. How can I change the price for each variation?


texts: Insert block content into the $content variable to be indexed by search

texts: I have a block that is generated by a view.  It brings in the author's name and other information for the specific node that is being viewed. The problem is that the block data is not indexed by drupal since it is not in the "content" of the page.  How can I get around this?  I tried moving the region to the node.tpl.php but that didn't help. Any suggestions would be great.


texts: SQL query the Drupal way, complex SELECT, conditional aggregate

texts:
I'm starting to invest time in learning custom Drupal entities like the ones explained here and I want to make sure that I am going to be able to do something in the future.

I am working with Drupal 7 with MySQL and have the entities API. Being tied to MySQL is okay.

Is it possible to perform a query like the one listed below in Drupal? If not, can I access a MySQL database view?

 select
        `listProducts`.`productId` AS `productId`,

        group_concat(if((`listProducts`.`className` = 'manufacturer'),
                `listProducts`.`optionValue`,
                '')
            separator '') AS `manufacturer`,

        group_concat(if((`listProducts`.`className` = 'model'),
                `listProducts`.`optionValue`,
                '')
            separator '') AS `model`,

        group_concat(if((`listProducts`.`className` = 'sub model'),
                `listProducts`.`optionValue`,
                '')
            separator '') AS `sub model`,

         group_concat(if((`listProducts`.`className` = 'year'),
                `listProducts`.`optionValue`,
                '')
            separator '') AS `year`
    from
        `hqr`.`listProducts`
    group by `listProducts`.`productId`

It's sort of an intense select statement. The data I'm working with is in the form

productId  className      optionValue
---------------------------------------
1          manufacturer   abcCompany
1          model          aModel
2          manufacturer   xyzCompany
2          year           2005

and should come out like

productId  manufacturer  model  sub model  year
-------------------------------------------------
1          abcCompany    aModel    -        -
2          xyzCompany      -       -       2005

Is doing this possible using the Drupal tools? If so, knowing how would be a big bonus too. Somewhere in my travels I saw a Drupal patch to enable group_concat in Drupal views (if that changes anything).


texts:
I am working on web services in drupal. I have created a sample module for get method to expose the data using web services. I have not found any sample code for the patch method.
code for get method:

namespace Drupal\demo_rest_api\Plugin\rest\resource;

use Drupal\rest\Plugin\ResourceBase;
use Drupal\rest\ResourceResponse;

class DemoResource extends ResourceBase {

}
/**
 * Provides a Demo Resource
 *
 * @RestResource(
 *   id = "demo_resource",
 *   label = @Translation("Demo Resource"),
 *   uri_paths = {
 *     "canonical" = "/demo_rest_api/demo_resource"
 *   }
 * )
 */
class DemoResource extends ResourceBase {

}
/**
 * Provides a Demo Resource
 *
 * @RestResource(
 *   id = "demo_resource",
 *   label = @Translation("Demo Resource"),
 *   uri_paths = {
 *     "canonical" = "/demo_rest_api/demo_resource"
 *   }
 * )
 */
class DemoResource extends ResourceBase {

  /**
   * Responds to entity GET requests.
   * @return \Drupal\rest\ResourceResponse
   */
  public function get() {
    $response = ['message' => 'Hello, this is a rest service'];
    return new ResourceResponse($response);
  }
}

I am novice to drupal. I did not find any example for patch method. Can any one usher me or provide a sample code for patch method.


texts: How do I attach AJAX click events on  or  tags?

texts:
There are many examples how to make ajax form submits and also many examples how to make drupal ajax links.
How do I attach AJAX click events on, for example, <button> or <div> tags?


texts: "Initial Menu Level" config in Block Layout not working

texts:
Using Drupal 8...

Goal

There are 2 regions in the header. The top region holds the Level 1 menu links while the bottom region holds the Level 2 menu links (or child links of the top regions).

What I want is for the Who am I? and About to only show on the top region. That's easy, initial menu level is 1 and max num of menu levels to display is 1. That works great.

Problem

Problem comes along when I add the same menu to the bottom region and choose the following set up:

I thought that with these when a user clicks About on the top region, then the child links ("Just more links") of that menu link would be displayed on the bottom region. But nothing happens. It only works with the Who am I? link.

The only difference is that Who am I? points to /node/2 while About points to the homepage with an added ?parameter=value


texts:
I am trying to place a block region inside a news content type but it is not rendering.

node--news.html.twig:

{{node.label}}

{{ date }}

    {{ content }}

      {{ page.article_sidebar }}

How can I get the block to render inside of a node?


texts: Create a custom form from Custom Content Type & Save it

texts:
I've created a custom content-type using GUI interface.

I need to customize the form which takes input while creating a content of the content-type. I can do this by hook_theme implementation but I'm trying to create a brand new form, and save the content's fields in database, so that it appears as a full-functional content of my content-type.

How do I create a form (I know how to create forms in my custom module) that contains the fields (all, or selectively some) of my custom content-type?
Most Importantly, when the form is submitted, how do I save the fields so that it appears as a brand new content-type?

I think I've made it clear, please answer, or ask me to clarify the question more if necessary...


texts: How can I sell time slots using drupal Commerce?

texts:
I want to allow customers to purchase products for a specific time slot and within a date range. Can this be done?

I want to achieve the following.

Allow products to be sold within a certain date range.
Also allow products to be sold for a certain time within that date range, for example between 1200 and 1300 or 1200 and 1220.
Show availability of those dates / time slots on a calendar for people to choose from.


texts: How to include only an updated custom field in an email created using Rules?

texts: I used the Rules module to create a rule with an event "After update existing content". This rule sends an email to the editing user when that user makes an edit to one of the multiple custom fields in a node. I would like to include only the custom field that he/she changed in that email.


texts: Links displaying as plain text, and html tags not applying, no matter which text format is selected

texts:
I have a text field type, that I'd like to be able to include links within. It appears that all of the formatters should be able to do this by default, and that the full/filtered html formatters should be able to handle html tags. However, for some reason, my text field is not doing either of these things. Links are simply appearing as plain text.

I think that they did work before, although I can't exactly remember where else in the site these filters are used to double-check, but they are no longer honoring links or html. Additionally, if full/filtered html is selected, then any html tags are hidden from view but are not being applied to the text. This leads me to believe that the formatter is recognizing the tags, but for some reason is failing to process them. Any suggestions?

So, just in case I wasn't clear at all:

Links are displaying as plain text (e.g. typing in http://www.google.com simply renders as http://www.google.com - plain text, no link). This is occurring with all formatters, including the "Plain Text" formatter, even when "Convert URLs into links" is selected. This is occurring with email addresses as well.
All html tags are being ignored (e.g. entering Google or Local Link displays only as Google or Local Link, without rendering the link. Additionally, something like Bold renders as Bold, without the style applied).


texts: Why is the Pressflow Last-Modified header not like plain Drupal?

texts:
The Last-Modified header is set in includes/bootstrap.inc. Plain Drupal uses

header("Last-Modified: ". gmdate("D, d M Y H:i:s") ." GMT");

which yields

Last-Modified: Sun, 27 Jan 2013 21:52:57 GMT

Pressflow uses

$default_headers = array(
    'Last-Modified' => gmdate(DATE_RFC1123, $_SERVER['REQUEST_TIME']),

which yields

Last-Modified: Sun, 27 Jan 2013 21:52:57 +0000

'+0000' is incorrect according to RFC 2616, and is flagged as an invalid date by http://redbot.org/

What gives? Is this a Pressflow performance technique, or an error, or what? Do browsers care?

We're trying to nail down some load issues on our site, and want to be sure we are not getting more repeat requests than is appropriate.


texts: Display custom text if there is no comments

texts:
I want to display custom text on a node if there is no comments yet.
I think i should check for comments count in preprocess_node, and somehow add the text below Comments title.

function MYTHEME_preprocess_node(&$variables, $hook) {
  if($variables['comment_count'] === '0') {
     //somehow i need to display text - There is not comments yet
  }
}

How can achieve this? here is an example of how it should looks like:

EDIT:
Also i have found better solution, may be useful for someone.
(using Zen theme - aka STARTERKIT modified)
I have added comments-wrapper.tpl.php

And in a template.php added preprocess function of this wrapper

function MYTHEME_preprocess_comments_wrapper(&$variables) {
    $variables['MYTHEME_comment_title'] = t('Comments');
      $commented_node = $variables['node'];

      if(!empty($commented_node) && is_object($commented_node)){
        $comment_count = 0;
        if(isset($commented_node->comment_count)){
          $comment_count = $commented_node->comment_count;
        }
        $variables['MYTHEME_comment_title'] = format_plural($comment_count, '1 comment', '@count comments');
         if($comment_count == 0) {
            $variables['MYTHEME_comment_title'] = t('Comments');
            $variables['empty_comments'] = t('There is no comments yet');
     }
}

And in a comments-wrapper.tpl.php i have printed out $empty_comments variable

  <?php print $empty_comments; ?>


texts: Scale down resolution of images with Media

texts: I have always been using the combination of IMCE and CKEditor and I am quite happy with it. Lately I tried installing Media, WYSIWYG and CKEditor because it looks like this combination is much more feature rich. The only key thing that seems to be missing is a maximum resolution setting for uploading images. This works perfectly with the IMCE combination but I cannot find a setting anywhere in the Media combination. Am I missing something or is there someway I can get uploaded images to be down scaled automatically?


texts: CKEditor Internal links are not prefixed with language

texts:
I have a multilingual Drupal site and I noticed that the paths of relative links added by CKEditor ignore the current language prefix and redirect to that node pages with default language (ie. /cn/home -> /introduction). I have tried using Linkit Module but the issues still exists. My Drupal version is 8.4.7.

Any possible solution for this problem?


texts: Commerce error on product stock reaching zero

texts:
I'm using Commerce Stock as all my products have specific quantities.
When I sell the last of an item it gets marked disabled and stock goes to 0, but it continues to display on the 'all products' view and the page generates the following error:

  Notice: Undefined offset: 39 in search_api_ranges_minmax() (line 188 of /Library/Server/Web/Data/Sites/brevardguns.com7/profiles/commerce_kickstart/modules/contrib/search_api_ranges/search_api_ranges.module).

If I change stock back to one the error goes away.
Also, if I disable the product and set stock to 0 manually, it does not display on the 'all products' view and does not generate the error.

Any help greatly appreciated.

Thanks,
David


texts: How to view a user's personal data after the user performs a login?

texts:
I wonder how to view a user's personal data after the user performs a login.

Example: they have 4 tables in database "it", "business", "hrm", "educ". All the 4 tables have a student data when the 1st column in it table are login only the first column in table are viewed his data in webpage.


texts: How to display Articles on another page ? not in home page

texts:
I had Crated some articles for my project how to display that all articles on another page ?
not on home page.


texts: Is it possible to use a path like that : user/%user/word with MENU_NORMAL_ITEM instead of MENU_LOCAL_TASK

texts:
i hope you understood the title of my topic because i have difficulties to express this problem in english.

I would like to change the menu item which is a tab (saved searches) and put it on my menu block.

So i went to the files of the module and found this:

search_api_saved_searches.module

$items['user/%user/saved-searches'] = array(
'title' => 'Saved searches',
'description' => 'View and edit your saved searches.',
'page callback' => 'search_api_saved_searches_user_listing',
'page arguments' => array(1),
'access callback' => 'search_api_saved_search_edit_access',
'access arguments' => array(1),
'weight' => 5,
'type' => MENU_LOCAL_TASK,
'file' => 'search_api_saved_searches.pages.inc',
);

I know that MENU_LOCAL_TASK is a generally a tab, so i tried MENU_NORMAL_ITEM but it didn't work.

I tried some other thing and removed %user $items['user/saved-searches'] but after that i had many error, i tried to debug them but after many hours i stopped, it was clearly not a good solution to change code directly on a module.

So my question is: Is there a easy way to move a menu item from a tab to a menu block when the path has a wildcard components ? If it's not possible, do you think there is, maybe, a workaround to accomplish what i want to do?

Thanks,


texts:
Is it possible to show contents in a specific sites for multilingual
  site?

I have a site of multilingual support with english and bangla language.
There is a content type blog. so Now I want to publish english content in a en.demo.com site and bangla content at bn.demo.com site and the different content will be visible at different site and it will generate different url. Is it possible and how ?


texts: Can we display region label from Layouts?

texts:
We have a MYTHEME.layouts.yml file which defines regions...

layout
  label: 'Layout Name'
  path: templates/panels
  template: layout-template
  default_region: theregion
  regions:
    theregion:
      label: 'This is The Region'

In the template we display fields added to the region with

{{ content.theregion }}

Can we display the label that we defined?


texts:
I have a drupal8 multisite with no default site settings. So my folder structure looks like:

sites/Asite/settings.php
sites/Bsite/settings.php

With a separate database connection in them and none in the default directory.
I've setup a behat.yml with the following:

default:
  suites:
    default:
      contexts:
        - FeatureContext
        - Drupal\DrupalExtension\Context\DrupalContext
        - Drupal\DrupalExtension\Context\MinkContext
        - Drupal\DrupalExtension\Context\MessageContext
        - Drupal\DrupalExtension\Context\DrushContext
  extensions:
    Behat\MinkExtension:
      goutte: ~
      selenium2: ~
      base_url: http://172.24.0.13:80
    Drupal\DrupalExtension:
      blackbox: ~
      api_driver: 'drupal'
      drush:
        alias: 'local'
      drupal:
        drupal_root: '/srv/web'

I have added

 "behat/behat": "3.3",
  "behat/mink": "^1.7",
  "behat/mink-extension": "^2.3",
  "drupal/drupal-extension": "^4.0",

to my composer.json file.
If i place my behat.yml file in the root i'm getting an error:

In Database.php line 361:

  The specified database connection is not defined: default

Where and how can i configure my behat file so i can run my test against each subsite.


texts: "user:one-time-login-url" token not getting replaced by token_replace

texts:
I'm trying to send e-mails to users manually by using the hook_mail_alter hook. The following is my function in its entirety:

function custom_module_mail_alter(&$message) {
    $email = '[user:name],

A site administrator at [site:name] has created an account for you. You may now log in by clicking this link or copying and pasting it to your browser:

[user:one-time-login-url]

This link can only be used once to log in and will lead you to a page where you can set your password.

After setting your password, you will be able to log in at [site:login-url] in the future using:

username: [user:name]
password: Your password

--  [site:name] team';

    $account = $message['params']['account'];
    $uid = $account->uid;

    $_user = user_load($uid);

    dpm(token_replace($email, array('user'=>$_user)));
}

The output looks like this:

Peter,

A site administrator at Website has created an account for you. You may now log in by clicking this link or copying and pasting it to your browser:

[user:one-time-login-url]

This link can only be used once to log in and will lead you to a page where you can set your password.

After setting your password, you will be able to log in at http://localhost/website/user in the future using:

username: Peter
password: Your password

--  Website team

As you can see, things like [user:name], [site:name], and [site:login-url] are properly processed. The only token that isn't processed is [user:one-time-login-url]. Any ideas why this is happening?

EDIT: Just for reference, the token does get processed in the Welcome e-mails that's sent out by the system automatically, so the token module is active and working... It just doesn't seem to get processed when I manually call token_replace().


texts:
Using the pathauto module, we could have created custom URL patterns using the hook_pathauto(). I could not find any such way to achieve the same in D8.

ref. https://envisioninteractive.com/drupal/using-the-pathauto-api-drupal-module-a-simple-example/

Can someone please explain is this possible in D8 and if so how.

Thanks


texts: Change text displayed when cart is empty

texts:
I'm using Drupal 7 with Commerce and I'd like to change the text shown when the user visits /cart and they have not added any items, from the default "Your shopping cart is empty." to a custom message, preferably that contains HTML.

I have tried adding custom text under no results behavior commerce_cart_form view with no luck.

What is the best way to do this?


texts: accessing block type in the theme_preprocess_node()

texts:
I have a block which include a view which is based on node.tpl.php, and I want to change the mark up in the node.tpl.php file just for a specified block.

function theme_preprocess_node(&$variables) {
  $block = unknown_way_to_get_it();
  if ($block->region == "product_stream") {
    $variables['theme_hook_suggestions'][] = 'node__productstream';
  }
}

How do I get a block from the preprocess function?


texts: Conflict among mymodule_block_view_MODULE_DELTA_alter and module_invoke

texts: I have, in Drupal 7, a Views which returns a list of items. The views display is a block, which I render in a section of the page. I was trying to dynamically display the block in the template using module_invoke. The block is perfectly displayed. However, if I use mymodule_block_view_MODULE_DELTA_alter to change the content of the block, the content is modified after the page has been processed, so Drupal still prints the unmodified version retrieved with module_invoke. I am a bit confused about the priority of events. Please advice (my goal is to have the block programmaticaly changed before displaying).


texts: Overriding hook_preprocess_html page contents set by a module

texts:
I want to override/remove some HTML added to page_bottom by a Drupal module, using a second Drupal module.

I tried to use hook_page_alter but this appears to be run before hook_preprocess_html as I can't see the content that the first Drupal module inserts in the page variable at that point.

The only solution I've found at the moment is to use hook_process_html and remove the unwanted HTML from page_bottom using regex - at this point all page_bottom additions are merged into a single array value so I can't just unset the unwanted value. This seems very messy.

Edited to add, here's the preprocess hook from the original module:

function module_one_preprocess_html(&$variables) {
  $theme_variables = array(
    'var1' => $var1,
    'var2' => $var2,
  );

  $variables['page']['page_bottom']['module_one'] = array(
    '#markup' => theme('module_one', $theme_variables),
  );
}


texts: Change the url parameter 'search_api_views_fulltext' used in views exposed filter

texts:
Im trying to modify the url parameter 'search_api_views_fulltext' so that it becomes nicer to read.

i would like something like "s" or "search"

Im using search_api + search_api_db + facet_api modules, with views.

Ive been looking every where but couldn't find any way to do this

Maybe someone among you guys could have an idea ?


texts: Show a field on form only when body field has been edited

texts:
On my nodes, users won't need to make a description of their changes unless they modify the body field.

Therefore I would like to hide the revision log field on the form unless the body field (the standard CKeditor long textfield) has been changed in the form.

The standard states API approach doesn't work, because data-editor-value-is-changed is not one the permitted arguments that states API knows.

$form['revision_log']['#states'] = [
  'visible' => [
    ':textarea[name="body[0][value]"]' => [
      'data-editor-value-is-changed' => 'true'
    ],
  ],
];

The natural next attempt is to attach a jquery function to listen to changes in textarea. I can't get this to work, possibly because this textarea is being changed programatically so these events may not be firing.

(function ($, Drupal) {
    Drupal.behaviors.ahsRevisionLog = {
        attach: function (context, settings) {
            // Apply the erEnhancedRemove effect to the elements only once.
            $(context).find('textarea[name="body[0][value]"]').once('ahsRevisionLogShow').each(function () {
                console.log('Textarea has been found'); // Fires on page load
                $(this).on('input selectionchange propertychange',function(event){
                    console.log('On change event fired'); // Never fires
                    if ($this.data('editor-value-is-changed','true')){
                        console.log('Has been changed'); // Never fires
                    }
                });
            });
        }
    };
})(jQuery, Drupal);

The only other thing I can think to do is to use the onchange event defined in Drupal's ckeditor.js. But I've no idea how to do that.


texts:
I am following the drupalgap hello world creation tutorial, however all i tried to make the hello world proven to be unsucessful.

here is the frontpage config fron settings.js

i did the installation on mobile folder and the setting file is settings.js

// App Title
drupalgap.settings.title = 'gsam';

// App Front Page
drupalgap.settings.front = 'hello_world';

the module name is gsam with directory structure:

mobile/app/modules/custom/gsam

and here is my gsam.js,

when every i load my server pointing to the mobile I have 404, that is after i placed this code.

/**
 * Implements hook_menu().
 */
function gsam_menu() {
  var items = {};
  items['hello_world'] = {
    title: 'DrupalGap',
    page_callback: 'gsam_hello_world_page'
  };
  return items;
}

/**
 * The callback for the "Hello World" page.
 */
function gsam_hello_world_page() {
  var content = {};
  content['my_button'] = {
    theme: 'button',
    text: 'Hello World',
    attributes: {
      onclick: "drupalgap_alert('Hi!')"
    }
  };
  return content;
}


texts: Form - Show partial form in block then populate full form with partial data

texts:
I have a content type with various fields.
Now i would like to show a couple of it's fields in a block globally and on submission post that data to the full form page and pre-populate the already provided fields.

Can this be done easily with the drupal core or is there a helpful module you guys can recommend?


texts: Set a date field equal to "current time" + "5 minutes" using tokens

texts:
I am using the Field Timer module to display countdown timer on my article node.

Say my article node has the date/time field named (field_article_datetime)

This module will take the value of the date/time field (field_article_datetime) and convert it into a countdown timer in the display of the article.

When the article node is created, I want to set the value of the date/time field (field_article_datetime) equal to current time + 5 minutes.

To extract the current time, I am using the token [node:created] from the token module, but I cannot find a solution on how to add +5 minutes to the token [node:created].

EXAMPLE:

Say at 12/03/2019 08:50:15 PM, a user has created a new article node... So I need a solution to add +5 minutes to the created time so the date/time field named (field_article_datetime) will be equal to 12/03/2019 08:55:15 PM...

This way, the user will see a countdown timer for 5 minutes on the article node display page.

Note: I am using the Business Rules module (similar to Rules module) to set the value of the date/time field (field_article_datetime) with the help of the token module.

Update #1:
Say the node is already created on the site and I want after the submission of a webform to fetch & update the node with update time + 5 minutes.

I think the best Idea is to use a custom module which will do the below:

Fetch the article by nid.
Set the value of field_article_datetime equal to: updated time + 5 * 60.
Save the Node

Since the above actions will be triggered when a user will submit a webform, so why not create a customwebformhandler.php file.

I have created a custom webform handler file but I need help to finish it since I am not a programmer:

<?php

namespace Drupal\my_module_name\Plugin\WebformHandler;

use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Serialization\Yaml;
use Drupal\Core\Form\FormStateInterface;

use Drupal\node\Entity\Node;

use Drupal\webform\WebformInterface;
use Drupal\webform\Plugin\WebformHandlerBase;
use Drupal\webform\webformSubmissionInterface;
use Drupal\webform\Entity\WebformSubmission;

/**
 * Update a node entity from a webform submission.
 *
 * @WebformHandler(
 *   id = "Update a node",
 *   label = @Translation("Update a node"),
 *   category = @Translation("Entity Update"),
 *   description = @Translation("Updates a node from Webform Submissions."),
 *   cardinality = \Drupal\webform\Plugin\WebformHandlerInterface::CARDINALITY_UNLIMITED,
 *   results = \Drupal\webform\Plugin\WebformHandlerInterface::RESULTS_PROCESSED,
 *   submission = \Drupal\webform\Plugin\WebformHandlerInterface::SUBMISSION_REQUIRED,
 * )
 */

class UpdateNodeWebformHandler extends WebformHandlerBase {

  /**
   * {@inheritdoc}
   */

  // Fetch & Update node object from webform-submission.

  // Function to be fired while submitting the Webform.
  public function submitForm(array &$form, FormStateInterface $form_state, WebformSubmissionInterface $webform_submission) {
    // Get an array of the values from the submission.
    $values = $webform_submission->getData();

    // The webform has an element text field with machine name (update_nid) which
    // contains the node ID of the node to be updated.
    // This is the part where to fetch the node by the value of (update_nid) element.
        Some code here

    // This is the node Updating part.
    $created = $entity->updated->value;
    date_default_timezone_set('GMT');
    $createdadd5 = date('Y-m-d\TH:i:s', $created + 5 * 60);
    $entity->field_article_datetime->value = $createdadd5;

    // This is the node Saving part.
    $node->save();
  }
}


texts: My site will run on D7. but it will too slow. i want to compress (gzip) js and css. I have check my site on https://developers.google.com/speed/pagespeed/insights and it will told me for compression of js can css files.


texts: Is there a function to return all the multisite names?

texts:
Is there a Drupal function to return all the multisite names?

I have searched a bit but have not come up with anything.


texts: How to extend Views Plugin ViewsSelection.php to have $form_state

texts:
I need to add in the current $form_state into the ViewsSelection. I have copied the file /core/modules/views/src/Plugin/EntityReferenceSelection/ViewsSelection.php to /modules/custom/fsed_entry/fsed_project_entity_reference_options/src/Plugin/EntityReferenceSelection/ProjectsSelection.php where I have the file overriding views' implementation. However, I can't seem to figure out how to get $form_state into my variables so that I can use a value from another form element. I have been trying to experiment with FormCache but I have not been successful. Any ideas on best approach here?

For background, I need the $form_state because the field that is being rendered (and this plugin is used on) here was ajaxed in and I want to pass in a value that I can add onto the handler_settings -> view -> arguments that this plugin uses.


texts: Where is the content of a node's body stored?

texts: In the node table, you'll find everything except the actual body. Where can I find this body text? I'm assuming it's being stored as a blob somewhere.


texts: How to change items under edit tab on user account page?

texts:
I know how to remove the user tab completely from the user menu with hooks.

I want to know where I can find the template file that render the items under this tab (or where I can edit what to show under this tab) as I want to hide some parts for all users).

I have tried Home » Administration » Configuration » People » Account settings.
But it only changes items on the user account page NOT the edit tab.


texts: I see it in premium themes and D6 themes (demo).  I would like to use it on my site.


texts:
I'm using <?php print $name; ?> in node--front.tpl.php for an exceptional case, where I can't use Views and the output goodies Views has to offer. By default $name output is themed to link to author profile.

Is there anyway to output the author name in raw text, without going throught a preprocess function?


texts: #states and language in selector - best practice

texts:
I am having trouble understanding when to use the language of the field in the selector when using #states.

I have a content type of post. It has:

a term reference post_type that has terms such as news and learner
an entity reference to a learner content type

Only when post_type is selected on the form as learner term do I want learner entity reference field visible.

This is my code that works :

function MODULE_form_alter(&$form, &$form_state, $form_id){
  if ($form_id == 'article_node_form') {
    $form['field_learner']['#states'] = array(
      'visible' => array(
        ':input[name="field_post_type[' . $form['field_learner']['#language'] .  ']"]' => array('value' => '14'), // (14 is the tid of term learner)
      ),
    );
    dpm($form);
  }
}

I read a comment Two gotchas from the doc page on drupal_process_states that

  Fields need to have the language in the selector or the name doesn't
  match.

I remember working with #states in the past and it worked without the language in the selector, but I think it was with a form I custom created.

Also, to work in a language agnostic manner I suppose I will have to do this rather:

':input[name^="field_post_type["]' => array('value' => '14'),

So my question is what is the best practice to do this, and will there be exceptions.


texts: How to hide menu item from high level roles but show for low level

texts:
I have 3 roles on site:

anonymous user
authenticated user
admin

I created a new page:

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

    $items['learning'] = array(
        'page callback'    => 'learning_output',
        'access callback' => 'learning_access',
        'type' => MENU_CALLBACK,
        );

    return $items;
}

I manually created a menu item for this page in the top menu. This item should be displayed only for authenticated users, but not admins. Unfortunately, admin as also an authenticated user. So I had to use a trick to disallow access to this page to admins using this access callback:

function learning_access()
{
    global $user;

    $n = count($user->roles);
    if ($n === 1)
    {
        $data = array_values($user->roles);
        if ($data[0] === 'authenticated user')
        {
            return true;
        }
    }

    return false;
}

It works but when I uploaded this module to server, I was unable to manually add a menu item for this page. Because admin doesn't have access to it.

How can I allow an admin to access this page? In the same time the menu item shouldn't be shown for him.


texts:
field_group.module defines a function as follows:

function field_group_pre_render_accordion_item(&$element, $group, &$form) {
  $element += array(
    '#type' => 'markup',
    '#prefix' => '
format_type . ($group->collapsed ? '' : ' field-group-accordion-active') . '">' . check_plain(t($group->label)) . '

classes . '">',
    '#suffix' => '
',
    //'#attributes' => array('class' => array($group->format_type)),
  );
  if (!empty($group->description)) {
    $element['#prefix'] .= '
' . $group->description . '
';
  }
}

Which is an instance of field_group_pre_render_<format-type>.

What I want to do is change that prefix code from an h3 to a div. But I'm not sure what the appropriate function/hook would be to use.

The Field Group API defines a hook_field_group_pre_render function but the $element argument in this function doesn't supply the #prefix element - so I'm not sure.

Ideally I could just totally override the function field_group_pre_render_accordion_item in my own code...


texts: ADFS integration - user session creation without the user creation

texts:
I did not find my answer after reading some articles.

For the user authentication, my Drupal site needs to communicate with a SAML IdP (ADFS).

I have an additional requirement: The user must be authenticated against the IdP and the Drupal user session must be created without a Drupal user is available or created in DB.

The definition of its roles would be evaluated on the basis of AD group at session creation time.

So far, I found the simpleSAMLphp Authentication module that manages this type of authentication BUT it needs to create a Drupal user (manually or automatically).

Other modules I viewed follow the same logic.

Someone knows how implementing the additional requirement?


texts: AJAX checkboxes in Views to change node values

texts:
I have a use case in D7 where I need to make a listing of nodes in table format, and included in the fields are checkboxes that us AJAX to do  things like publish/unpublish a node and set other field values in the node.  I know I saw merlinofchaos mention somewhere that there is a way to do this in Views, but I haven't been able to find details on how.  I can do it easily enough by creating a table and manually filling the cells, but I would like to use Views if I can.  Does anyone know how this can be done?

Thanks.


texts:
I am trying to adapt the relatively new off canvas dialog introduced in Drupal 8.5.

It is suggested to use it with the Drupal Form-API and a link element like this:

$form['off_canvas'] = [
  '#title'      => 'Some title',
  '#type'       => 'link',
  '#url'        => \Drupal\Core\Url::fromRoute('some route'),
  '#attributes' => [
    'class'                => ['use-ajax'],
    'data-dialog-type'     => 'dialog',
    'data-dialog-renderer' => 'off_canvas',
    'data-dialog-options'  => \Drupal\Component\Serialization\Json::encode(['width' => '40%']),
  ],
  '#attached'   => [
    'library' => [
      'core/drupal.dialog.ajax',
    ],
  ],
];

This works pretty straight forward and out of the box, but for a very special use case I need to attach an AJAX-callback with a button element which is not possible using a link element when looking at the Drupal form API specifications.

This is what I got trying to use a button element and a callback with off canvas dialog functionality:

$form['some_button'] = [
  '#type'     => 'button',
  '#value'    => 'some value',
  '#attached' => [
    'library' => [
      'core/drupal.dialog.ajax',
    ],
  ],
  '#ajax'     => [
    'callback' => '::some_callback',
  ],
];

Callback function goes here:

public function some_callback(&$form, FormStateInterface $form_state) {

  $response = new \Drupal\Core\Ajax\AjaxResponse();

  $title = 'Some title';

  $content = '
Some content
';
  $options = [];
  $response->addCommand(new \Drupal\Core\Ajax\OpenOffCanvasDialogCommand($title, $content, $options));
  return $response;
}

The funny thing is: once the off canvas dialog is initialized using $form['off_canvas'] it works on both elements for $form['off_canvas'] and $form['some_button']. On pageload it uses the old dialog for $form['some_button'] and the new off canvas dialog for $form['off_canvas'].

So this must be an initialization problem for $form['some_button]. But I can not get this to work with the off canvas dialog at pageload and documentation for the new off canvas functionality is quite rare.

I tried to tell $form['some_button'] to use off canvas as a parameter in a lot of ways, but it does not work. I guess I missed something here.

Can you guys give me a hint how to make this work from the very start using a button with an Ajax callback?


texts: How do I create a template for custom display mode of user registration form?

texts:
I have multiple registration pages, each with corresponding to a form display under
admin/config/people/accounts/form-display.
I added this to Mytheme.theme

function Mytheme_theme_suggestions_alter(array &$suggestions, array $variables, $hook) {

  if ($hook == 'form' & !empty($variables['element']['#id'])) {
    $suggestions[] = 'form__' . str_replace('-', '_', $variables['element']['#id']);
  }
}

Then I can create a template form--user-register-form.html.twig but that will affect all the form display modes. Is it a way to create a template for each display mode? For instance for a form display "Allied" something like form--user-registration-form---allied.html.twig ?


texts: How does a PaymentGateway signal a completed order

texts:
I'm trying to implement the Commerce Ingenico payment gateway for a Drupal 8 Commerce site. As this module is still in unfinished for Drupal 8, I'm fixing it up as I go. Most of the implementation is located in Composer packages, so it's mostly plumbing.

I'm hitting a bit of a wall now though. I'm using the off-site payment gateway, and I've configured the IPN (server to server notification). The values for the payment in the database look good*, but the Cart never turns into an Order. Somehow the trigger for signaling a completed payment to the order is missing.

The results is that after returning from the offsite payment (and the onNotify has already been triggered, so the payment is marked as completed), I end up back at the start of the payment flow; the order summary.

How are these parts supposed to fit together?

Here's the code to the onNotify method in the PaymentGateway:

public function onNotify(Request $request) {
    parent::onNotify($request);

    // Common response processing for both redirect back and async notification.
    $payment = $this->processFeedback($request);

    // Let's also update payment state here - it's safer doing it from received
    // asynchronous notification rather than from the redirect back from the
    // off-site redirect.
    $state = $request->query->get('STATUS') == PaymentResponse::STATUS_AUTHORISED ? 'authorization' : 'completed';
    $payment->setState($state);
    $payment->setAuthorizedTime(REQUEST_TIME);
    if ($request->query->get('STATUS') != PaymentResponse::STATUS_AUTHORISED) {
      // setCapturedTime has been relegated to the mists of history
      $payment->setCompletedTime(REQUEST_TIME);
      // $payment->setCapturedTime(REQUEST_TIME);
    }
    $payment->save();
  }

And this is the resultant row in the commerce_payment table:

 payment_id
13

type
payment_default

uuid
payment_default

payment_gateway
ogone_offsite

payment_gateway_mode
test

payment_method
NULL

order_id
29

remote_id
3039111240

remote_state
9

amount__number
26.400000

amount__currency_code
EUR

refunded_amount__number
0.000000

refunded_amount__currency_code
EUR

state
completed

authorized
1534516744

expires
0

completed
1534516744

test
NULL

captured
NULL

Of course I don't know what these values are supposed to look like. I'm actually a little concerned about payment_method being NULL in this row. Is that normal for an offsite payment gateway, or should that be set to something?


texts: How do I execute a view in a custom module and print the output (as HTML markup)?

texts:
I want to print the output from a simple view in my custom module. But is doesnt work. I have tried many options from forums and stackoverflow. All of them print "array" instead of html-markup.

My controller:

class DefaultController extends ControllerBase {

    public function myfunc1() {

        $view = Views::getView('myfirstview');

        $view->setDisplay('page_1');
        $view->preExecute();
        $view->execute();

        // $myresults = $view->preview();  = array
        // $myresults = $view->render();  = array
        $myresults = $view->result; // = array

        return array(
            '#title' => 'Hello World!',
            '#markup' => $myresults,
        );
    }
}

How can I print the result/output of a view programmatically?

I dont want to make it without "embed view" , because I want to set some exposed filters later.


texts: using panels to create custom page for all blogs

texts:
I used panels to create static or landing pages, but now I'm wondering if it would be possible and how to create a custom page template for all blogs using panels, so a user would simply have to write a blog and not have to fuss without creating a specific panel variant for every blog page that is created.

thanks,

Chad


texts: Add product image to drupal commerce cart form

texts:
Is there a way of hooking into the commerce cart form and adding a custom field which so happens to be the product image that I want to display?

I've tried via the view itself but I have no idea on how to when there is only the Order or Order Item objects available in the commerce cart form itself.

I've also tried the following hooks:

theme_views_pre_render
theme_preprocess_views_view
theme_views_data_alter
theme_commerce_cart_form_views_pre_render
theme_form_alter

But i've had no luck.

Can anyone suggest a solution, it's only temporary as I should imagine it will eventually be entwined with the drupal commerce module.

Thanks in advance.


texts:
I load some libraries in my module by using this hook :

function food_truck_form_views_pre_render(&$view) {
  if ($view->name == 'marqueurs_admin') {
    drupal_add_css(libraries_get_path('animate') . '/animate.min.css');
    drupal_add_js(libraries_get_path('bootstrap_notify') . '/bootstrap-notify.min.js');
    drupal_add_js(drupal_get_path('module', 'food_truck_form') . '/js/food_truck_form_admin.js');
  }
}

But when I write a notify in my food_truck_form_admin.js (this code) :

(function($) {
    $.notify({
    icon : 'fa fa-exclamation',
    message : 'TEST'
    }, {
    animate : {
        enter : 'animated flipInY',
        exit : 'animated zoomOutUp'
    },
    type : 'danger'
    });
})(jQuery);

I get this error :

  2bootstrap-notify.min.js?o68oa5:1 Uncaught TypeError:
  this.$ele.find(...).on is not a function

have you got an idea ?

PS : is it the best method to load libraries ? I see on libraries API there was libraries_load... method but i don't understand how to use them :/


texts: button for boolean field during node display

texts:
I have a boolean field in my content type which takes values either 1 or 0. I want to provide a button instead of just displaying the value of field so that the user can click on it and toggle the value.

Is it possible to doing something like this ?


texts: Installed Boost module. How do you tell it is working on your site?

texts: I just installed the Boost module on Drupal 7 and activated everything properly. How do I even tell if its working properly?


texts: Feeds tamper fetch data from external API

texts:
I am using drupal_http_request and drupal_json_decode to retrive and parse json from an external API in the feeds tamper by using the execute php code plugin. My code is as follows:

$json = "https://api.coursera.org/api/onDemandSpecializations.v1?ids=".$field;
$response = drupal_http_request($json);
$data = drupal_json_decode($response->data);
return ($data['elements'][0]['name']);

This returns a null value.

The json is as follows:


texts:
I made node with location field (track) and computed field. I want to measure distance between two points. In computed field is:

Computed Code (PHP) :

$longitude1= $entity->field_track[LANGUAGE_NONE][0]['longitude'];
$longitude2 =  $entity->field_track[LANGUAGE_NONE][1]['longitude'];
$latitude1 = $entity->field_track[LANGUAGE_NONE][0]['latitude'];
$latitude2 = $entity->field_track[LANGUAGE_NONE][1]['latitude'];

$entity_field[0]['value'] = earth_distance($longitude1, $latitude1, $longitude2, $latitude2);

Display Code (PHP):

$display_output = $entity_field_item['value'];

I think, I am stucked in reading field_track[LANGUAGE_NONE][0]['longitude']; Can anyone help me how to read longitude an latitude to earth distance formula? Thank you.


texts: How to set the permission for each file separately for downloading?

texts:
want to add a functionality of uploading files so that users can download these files.

First is there any module to provide this functionality (Uploading files from admin and then on front end, users can download these files).

Second If I upload some files then can I set the permission on the specific files.
My requirement is that some files will be only downloadable for registered users. The anonymous user could not be able to download the file.
And the 2nd scenario is that some files will be required the admin approval. Means if a user click on the file for download, a notification will be sent to the admin, then if admin approved it then the user can be able to download the file.

Any Idea about this.

Thanks in Advance.