Add button to default D7 view Is there a way to add a selection button or a check box to the display of a default view? I am hoping to catch the node information of the selected row into a bucket or into a container. Below is the screen shot of my default view, I need to add the button or check box at the end of the 'Treatment' column. I have little understanding about the hook_views_default_views_alter(hoping that its implementation is relevant in this case) but not sure how a button could be added using it. Let me know if the question needs more clarification or any additional information is required.

Thanks

See this drupal.org documentation page called How to add a column with dynamically generated action buttons in a View. hook_views_default_views_alter has essentially nothing to do with this task. Optionally an easier path is like Rules with Views Bulk Operations if you can live with like a checkbox per row, and a dropdown for the operation selection.

The more custom a look, or outside of Drupal's default behavior you deviate. The more work you have to do.


Prod CentOS core-only site work fine but local Ubuntu backup has no css loaded I made a backup of my prod CentOS site to local Ubuntu. The site is all core --- Both by means of templates or modules; No contribs whatsoever. No customizations.

Yet the CSS won't load for whatever theme.

These are the only errors in drush ws --full

 128377  file      File temporary://filedOb2TA could not be moved/copied because the destination directory public://js is not configured correctly.   notice    http://localhost/benia/  127.0.0.1  19/Aug 22:15
 128376  file      The file permissions could not be set on public://js.                                                                              error     http://localhost/benia/  127.0.0.1  19/Aug 22:15
 128375  file      File temporary://fileEzTm0r could not be moved/copied because the destination directory public://css is not configured correctly.  notice    http://localhost/benia/  127.0.0.1  19/Aug 22:15
 128374  file      The file permissions could not be set on public://css.                                                                             error     http://localhost/benia/  127.0.0.1  19/Aug 22:15
 128373  file      File temporary://fileBagPhj could not be moved/copied because the destination directory public://css is not configured correctly.  notice    http://localhost/benia/  127.0.0.1  19/Aug 22:15
 128372  file      The file permissions could not be set on public://css.                                                                             error     http://localhost/benia/  127.0.0.1  19/Aug 22:15
 128371  file      File temporary://fileII1wDa could not be moved/copied because the destination directory public://css is not configured correctly.  notice    http://localhost/benia/  127.0.0.1  19/Aug 22:15
 128370  file      The file permissions could not be set on public://css.                                                                             error     http://localhost/benia/  127.0.0.1  19/Aug 22:15
 128369  file      File temporary://fileYPV93p could not be moved/copied because the destination directory public://js is not configured correctly.   notice    http://localhost/benia/  127.0.0.1  19/Aug 22:06
 128368  file      The file permissions could not be set on public://js.

Trying to fix it, I made sure that under admin/config/media/file-system the tmp folder is /tmp and then created a directory named tmp folder in root and gave it 755. I also gave 755 to sites/default/files

Tried 777 for both (including sudo chmod 777 files/ -R).
Tried sudo chgrp www-data files -R

While reading on how to fix these in D.O but it wasn't quite clear from what I've read; Most solutions included patches and I don't think its valid for my case. Maybe a Linux expert could shed some light why it happens.

Did you try the 777 recursively inside the files folder? (so it applies on files/css and files/js subfolders)

Also I would check if SELinux is enabled on your CentOS server to discard you downloaded an incomplete copy of your website due to lack of permissions. Use the getenforce command to check if it's set to permissive.
In case of necessary you can use the following command to set the context of files folder to read/write:

chcon -R -t httpd_sys_rw_content_t files


Create views with UI Pattern Views I have views like this:

I want use module UI Pattern Views. I defined UI Pattern. File card.ui_patterns.yml with content

card:
  label: Three column fluid
  description: Three column fluid
  fields:
    image:
      type: render
      label: Image
      description: Media image.
      preview:
        theme: image
        uri: http://lorempixel.com/900/500/sports/1
        width: 150
        attributes: {}
    title:
      type: link
      label: Title
      description: Media title.
      preview:
        type: processed_text
        text: Etiam iaculis nunc ac metus
        format: basic_html

and file pattern-card.html.twig have content:

    {% if image is not empty %}

            {{ image }}

    {% endif %}

{{ title }}

I don't know how can use multil image style for this case. Any suggetion?

Here's a step-by-step:

Install the UI Patterns Views module
Insert the fields and map them to the UI Pattern fields

Note: You are mapping fields for the rows.

At this point, each piece of content should be rendered as a UI Pattern

Now, if you want to arrange the cards in a specific way (say, using Masonry), then you can do it in one of the following ways:

Add a class to the entire view, say, js-view-masonry – you can then use this class in JavaScript to detect this view and apply the JS plugin that organizes the cards like you want.
The other way will be to create a superpattern of the card pattern. Say, a card_collection pattern, with a field named items. Next, override the view's template, especially the part where the rows are rendered. Here, instead of displaying the rows, into the "card_collection" pattern.

Here's a working example of the second method using "card_collection". The blog list consists of 2 patterns. The "card" pattern and a pattern called "card collection" which wraps the cards.


Convert node ID from string to integer Retrieve a node based on condition:
$query = \Drupal::entityQuery('node')
->condition('type', 'my_content_type')
->condition('title', 'my node title');
$nid = $query->execute();

The result of $nid is the correct node ID but the format is a string, (es: "123")
When I want to load the node by its ID, I write:
$node_id = Node::load($nid);

Doing this, the result I get is NULL because the variable $nid is holding a string (not integer).
If I write the code like this:
$node_id = Node::load(123);

I get the node loaded.
How can I convert the variable string ($nid) as an integer ?
I tried:
$nid_int = (int) $nid;
$node_id = Node::load($nid_int);

also I tried:
$nid_int = intval($nid);
$node_id = Node::load($nid_int);

But I alwas get result NULL
Thanks for your help

the $query->execute(); return an array of key/value like [KEY => nid1]:
if you are sure you have only one node with that tittle you should get the first element of the array it's your nid try with:
 $query = \Drupal::entityQuery('node')
  ->condition('type', 'my_content_type')
  ->condition('title', 'my node title');
$nids = $query->execute();
// Get the nid in the array.
$nid = reset($nids);
$node = Node::load($nid);


Is there a module to conditionally set a fields value depending another field? is there a module that can set a value of a field which depends on the value of another field first? I know i can do it via js, but was wondering if something was out there already. conditional field module doesnt work in my case as it dosent set the value depending on the result of another.

example: I am creating a basic page and I have a select box field with the following: white/black/red. when i select red, i want the body to be filled in with 'yes' and if its black i want the body to be filled in with 'no'.

No other module available apart from conditional field, you need to create your own module with hook form_alter() and use some code like

<?php
function wishlist_status_form($form_state) {
$form['status'] = array(
    '#type' => 'textfield',
    '#title' => 'Status',
    '#suffix' => '

',
  );

$form['ajax-submit'] = array(
    '#type' => 'submit',
    '#ajax' => array(
        'callback' => 'wishlist_status_change',
        'wrapper' => 'my-wrapper',
    ),
    '#value' => t('Save'),
  );
return $form;
}

function wishlist_status_change($form, $form_state) {
    dpm($form_state, 'state callback');
    return 'test';
}
?>


How to display the 'Request New Password' page for Administrators. What I'd like to do is have the exact same page as /user/password (when not logged in)  that the 'Administrator' Role could use and send out emails to existing users.

However when logged in you get a 'Password reset instructions will be mailed to'  message.  I've had a hunt for a module or how to do it programmatically but can't find a solution.

Many Thanks

Think you'd need to do it with Views Bulk Operations and Views.

Create a View (only accessible by the Admin role) which lists all the users, add VBO and I think reset password is included as one of the actions.


How to get read count of blogs in Blog module? I am using blog module to implement blog section in my website, I am not getting the count of the each blog. What is the variable that stores read count of each blog. Any suggestion will be appreciated.

The core Blog module does not track read statistics for content; that's the purview of the Statistics module.

To enable read statistics:

Install the Statistics module.
Follow its configuration link (/admin/config/system/statistics).
Set the Count content views option to enable view counting.


Date filter using $row data doesn't return any result I am trying to filter my view by using a date range so that it shows all the activities for an event for which Activity Start >= Event End & Activity End <= Event Start.
To do this I have set up a view to show all the activities with a contextual filter to allow the event dates to be accessed.
I added the 4 fields to my table: Activity Start, Activity End, Event Start, and Event End.
My $Row data when adding a Global:PHP filter criteria now has the four variables accessible to carry out the comparison above.

Activity Start: $Row->field_start_date_and_time
Activity End: $Row->field_start_date_and_time_1
Event Start: $Row->field_start_date_and_time_2
Event End: $Row->field_start_date_and_time_3

I am using views_php 7.x-2.x-dev, which fixed the issue of $row not populating.
I am trying to write the above comparison in PHP and I am not getting what I expected. (I thought this would be the easy bit; I have spent a long time getting this far.)
However, it appears that the date format is not being read correctly as it is not returning any result. I have done some research which would indicate it might need to be in Unix timecode to do the comparison accurately.
Is this correct? What does the code look like to do it?

You really shouldn't use PHP in Views have you seen the warning on the module page:

  While this module allows you to directly use PHP inside views which
  may be useful for quick and easy solutions, it is highly advisable to
  use regular handlers and plugins when available (or even to create one
  yourself). Take note that filtering and sorting a view using PHP
  always has a considerable performance impact.

Also this post has instructions how to write a Views handler or Plugin.

You should be able to achieve what you're trying to do with a combination of contextual filters, normal filters and relationships.


Show all revisions with entity reference field referencing a specific entity Here is what I am after:

I have an entity reference field that references nodes.

I want to build a view that shows a list of all revisions that have this field referencing a given entity.

Here is what I have tried so far:

New view displaying content revisions.
New relationship: Referenced entity.
New contextual filter NID using the relationship.

Now this works, but only returns one result: the current node that is referencing the nid argument in the contextual filter. I want it to list all revisions that have historical data referencing the NID in the argument of the contextual filter.

Has anybody built a view that uses a contextual filter to show revisions that reference a given NID by an entityreference field?

So if I am reading this correctly, Content Type A references Content Type B. You want to show all revisions of Type A nodes that reference a certain Type B node.

Contextual Filter: Content: Reference Field for Type B Provide Default: ___
There are two revision relationships.. ID and NID. The one with ID is provided by default. Add the one for NID and for its relationship, choose the one with ID.
After it's added, move it above the ID relationship. This is vital and I don't even know why..
Make sure your Title field doesn't use any relationship.

Now, all revisions that reference Type B will show and be linked properly.

If anyone can explain the significance of reordering the relationships, please post in the comments. I spent far too long working on this a few months ago and a reason would be great!


Flex Slider issues after upgrading Drupal to v7.39 I've been researching this issue for a week to no avail.  Perhaps someone has some suggestions?
Upgraded a site from Drupal 7.34 to 7.39 rather seamlessly.  Also updated all modules that were down level.  All seemed OK.  But then the flex slider just stopped displaying.  I've checked all I could in the various display and definitions pages and all looks fine.  I've tried different browsers and even a different server instance with on luck.
I'm just hoping someone who may have experienced this anomalie can shet some light on what to look for next?

Don't know why but in the admin/config/development/performance section I unchecked the compress javascript option, saved the page and suddenly my flex-slider images returned.  Strange though, isn't it?

Anyway - solved.


How to perform a redirect based on the value entered in a Webform component? How to perform a redirect after a Webform submission, i.e. to different pages for different answers?

The scenario is like so:

If user enters "foo" for some Webform component, then page must be redirected to /foo.
If user enters "anything else but foo", then page must be redirected to /bar.

You can achieve by altering the Webform.

function hook_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'YOURFORMID') {
    $form['#submit'][] = 'ctm_redirect';
  }
}

function ctm_redirect(&$form, &$form_state) {
  if (CONDITIONS) {
    $form_state['redirect'] = 'foo';
   }
   else{
     $form_state['redirect'] = 'bar';
   }
}

You can also check Webform Rules module.

This module adds rules integration on webforms.

  Did you ever want to react on webform submission using rules but
  couldn't find the proper event? Webform Rules makes it possible to
  catch webform submissions by rules and do whatever you'd like to do
  with it (meaning: do whatever rules let you do with it).


Define entity in module and edit existing items I am trying to create a module which defines an entity (called "didyouknow") with two fields: ID and content.

I have set it up to create new items of this custom entity, but I can't get it to work for editing existing items.

I'm trying to reuse the same form (didyouknow_item_form()) for creating and editing, which works fine for creating, but for editing. The "%didyouknow" part in the URL is supposed to mean that the argument of didyouknow_item_edit() is a loaded entity object, but it isn't; if I output it within that function using print_r(), it outputs as "structure." This results in PHP outputting:

  Notice: Trying to get property of non-object in didyouknow_item_form()

The code for the functions is below:

function didyouknow_menu() {
    $items['admin/structure/didyouknow/manage/add'] = array(
    'title' => 'Add Did You Know item',
    'page callback' => 'didyouknow_add',
    'access arguments' => array('create didyouknow'),
  );
  $items['admin/structure/didyouknow/manage/%didyouknow/edit'] = array(
    'page callback' => 'didyouknow_item_edit',
    'access arguments' => array('create didyouknow'),
    'page arguments' => array(1),
  );
  return $items;
}

function didyouknow_item_edit($didyouknow){
  return drupal_get_form('didyouknow_item_form', $didyouknow);
}

function didyouknow_add() {
    $didyouknow = (object) array (
    'pid' => '',
    'type' => 'didyouknow',
    'content' => '',
  );

  return drupal_get_form('didyouknow_item_form', $didyouknow);
}

function didyouknow_item_form($form, &$form_state, $didyouknow) {
  $form['content'] = array(
    '#type' => 'textarea',
    '#title' => t('Content'),
    '#default_value' => $didyouknow->content,
    '#required' => TRUE,
  );

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

  field_attach_form('didyouknow', $didyouknow, $form, $form_state);

  return $form;
}

function didyouknow_item_form_validate($form, &$form_state) {
  $didyouknow_submission = (object) $form_state['values'];
  field_attach_form_validate('diyouknow', $didyouknow_submission, $form, $form_state);
}

function didyouknow_item_form_submit($form, &$form_state) {
  $didyouknow_submission = (object) $form_state['values'];
  field_attach_submit('didyouknow', $didyouknow_submission, $form, $form_state);
  $didyouknow = didyouknow_item_save($didyouknow_submission);
  $form_state['redirect'] = "admin/structure/didyouknow/manage/$didyouknow->pid/edit";
}

function didyouknow_item_save(&$didyouknow) {
  return entity_get_controller('didyouknow')->save($didyouknow);
}

You have two problems in that code. First of all, you assume that having a didyouknow-id in the URL, is enough for Drupal to know where to get your object, the second problem is that your page argument is off.

This simplified code:

$items['admin/structure/didyouknow/manage/%didyouknow/edit'] = array(
  // …
  'page arguments' => array(1),
);

will pass on "structure" as an argument, not the %didyouknow id, nor a didyouknow-object, which is why you get an error about a "non-object". Argument indexing start with 0 => admin, so (as already mentioned by LToomre) you need to have:

'page arguments' => array(4),

It is also important to note that Drupal will not automatically know how to load your entity, you are required to provide the load function yourself.

As an example, look at the epay module, which has a menu hook like this:

$items['payment/epay/callback/%epay_hash'] = array();

The named argument %epay_hash, is automatically mapped to a _load function:

function epay_hash_load($hash) {}

which takes the URL argument as parameter, performs the DB queries necessary to load your object, and then returns it.


How to wrap first word of page title in span in drupal 7 I want to implement it with theme_preprocess function. Every my attempt fails.

function mdrupal_mono_preprocess_page(&$variables) {
  $variables['title'] = drupal_get_title($variables['node']);
  $title = $variables['title'];
  if($title) {
    $words = explode(' ', $title);
    $words[0] = '<span>' . $words[0] . '</span>';
    $title = implode(' ', $words);
  }
}

Not really a Drupal question, but you're setting the wrong variable

$title = implode(' ', $words);

should be

$variables['title'] = implode(' ', $words);

Or, change

$title = $variables['title'];

to

$title = &$variables['title'];

instead. Either will work


Set the custom initial date on FullCalendar based on a field in the current node I would like to populate the custom initial date based on a field in the current node. Is this possible?

(bigger)

Update after looking at the module code

I snooped around the module code and noticed the line below.

if (!empty($settings['times']['default_date'])) {
    $settings['date'] = $settings['times']['date'];
}

(bigger)

Update 2: Hard coded test

Well this looks possible, I hard coded a test and it appears to have worked. The next step is to pull this value from a Node Field.

 // First, use the default date if set.
  dsm($settings['times']);
  if (!empty($settings['times']['default_date'])) {
    //$settings['date'] = $settings['times']['date'];
    $settings['date'] = array(
      'year'=>2012,
      'month'=>1,
      'day'=>2
    );
  }

Edit from file ./includes/fullcalendar.fullcalendar.inc near line 629

So this and two additional Content Node Fields edit worked for me. Starting around line 629 in includes/views/fullcalendar.fullcalendar.inc, I changed to the following. Don't forget to add two additional fields to your Content Type with machine names field_default_calendar_year and field_default_calendar_month.

Update on project's issues list: Patch Submitted, Requested Review

See Patch code: http://drupal.org/files/fullcalendar-7.x-2.x-custom_init_date_1.patch


How can I get a list of the roles in a system, via the REST API? Similar to How to Retrieve all Forums, how can I retrieve the list of roles in a system via the Services REST API?

This is Drupal 7, Services 3.x.

Are roles terms in a taxonomy vocabulary ?

Create a custom service resource, (you'll have to create your own access callback and access callback file, unless you want to use DrupalGap which is tailored to the link mentioned here)
Then in your callback, try something like this:

return user_roles();


How to set domain based search using search_api_solr? I am using Domain and Search API Solr module in my project. On all domains, searching for a content gets result(content) from all domains. I would like to get search results according to the domain.
For example, if a user is on domain a.domain.com, then the search should return content which is published on a.example.com only and not on any other domains or sub-domains.

You could take a look at Search API Domain Access sandbox project:
https://www.drupal.org/sandbox/raf/2244229

I did a work around based on that code that worked for me:

<?php
/**
 * Implements hook_entity_property_info_alter().
 *
 * Adds an entity property for the domain access of the node.
 *
 * @TODO this is just a workaround @see https://www.drupal.org/sandbox/raf/2244229
 */
function my_module_entity_property_info_alter(&$info) {
  $properties = &$info['node']['properties'];
  $properties['my_module_domain_access'] = array(
    'label' => t('My Domain Access Information'),
    'description' => t('The domains to which the node is published.'),
    'type' => 'list<integer>',
    'getter callback' => 'my_module_get_domain_info',
  );
}

/**
 * Custom getter callback for the domains in
 *
 * @param $data
 * @param array $options
 * @param $name
 * @param $type
 * @param $info
 * @return null
 */
function my_module_get_domain_info($data, array $options, $name, $type, $info) {
  return (!empty($data->domains) ? $data->domains : NULL);
}

/**
 * Implements hook_search_api_query_alter().
 *
 * Adds a filter for the current domain.
 */
function my_module_search_api_query_alter(SearchApiQueryInterface $query) {
  $domain = domain_get_domain();
  $query->condition('my_module_domain_access', $domain['domain_id']);
}

Now, you will be able to choose the field for indexing under "admin/config/search/search_api/index/your_index/fields" and in query time this code will filter out data based on current domain, not many more things.

Hope it helps, but notice that this code it is not fully tested (nodes that have been published in more than one domain... etc).


Adding Bootstrap Tabs to a content view I've created a custom content type which I want to display in a view using Bootstrap's Tabs component.

I've found this tutorial of sorts, but I'm a bit lost trying to process it all (I'm very new to Drupal).

It looks like it does almost exactly what I need it to. I basically need to display the content I have in that view to be placed inside Bootstrap's Tab markup. I know the theme I'm using already has Bootstrap embedded and available, but I can't seem to figure out to make a "Bootstrap Tabs" option available in the "Style" option of my page view.

Can anyone share some pointers on where to start looking for a solution and on what I need to read up on?

EDIT:

I've been following the tutorial and was able to get somewhere with it. Right now, a Format option for Bootstrap Tabs shows up when editing the view and, when selected, it is followed by a form questioning which field should be used for navigation - as intended, I recon.

Although right after answering the form question, above the preview area, an error message shows up stating:

  Template "modules/custom/bootstrap3tabs/templates/bootstrap3tabs.html.twig" is not defined (Drupal\Core\Template\Loader\ThemeRegistryLoader: Unable to find template "modules/custom/bootstrap3tabs/templates/bootstrap3tabs.html.twig" in the Drupal theme registry.).

Which in turn also shows up in the view after saving.

Can anyone share some pointers on why this happens and how to fix it?

you can also use the https://www.drupal.org/project/quicktabs for this
    (The Quick Tabs module allows you to create blocks of tabbed content, specifically views, blocks, nodes* and other quicktabs*. You can create a block on your site containing multiple tabs with corresponding content. Clicking on the tabs makes the corresponding content display instantly, using jQuery. With the 6.x-2.x branch, this can be done in either ajax or non-ajax mode:)
available  for drupal 8


Migrate module, long text issue I'm trying to migrate rows from a Joomla K2 table.

The issue happens when I add the 'fulltext' field to the field list on my select inside my migration class. This field is a medium text field with html inside. The error only happens when I put this field in the query.

The error is like so:

  Migration failed with source plugin exception: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'fulltext FROM j3_k2_items n WHERE (catid IN ('43', '45', '46', '51', '68', '7' at line 1,

I have set $this->source = new MigrateSourceSQL($query, array(), NULL, array('map_joinable' => FALSE)); but it didn't help.

Any ideas? I don't know what to do.

Ok, just found the problem.

I was using this select:

$query = $this->getConnection()->select('j3_k2_items', 'n')
  ->fields('n', array('id', 'title', 'fulltext'))
  ->condition('catid', array(43, 45, 46, 51, 68, 72, 109, 117),'IN');

but the array inside the fields was the problem. When I removed it:

$query = $this->getConnection()->select('j3_k2_items', 'n')
  ->fields('n')
  ->condition('catid', array(43, 45, 46, 51, 68, 72, 109, 117),'IN');

Which was the same as doing a "SELECT *" the error gone and the migration worked!


Error messages are not translated We have successfully build a multilingual Drupal website, the only thing that isn't being translated yet are the error messages.

We have the default Drupal 6 contact form on the website. All the field labels are translated correctly including the "Send" button.

However, when someone just tries to submit the form without completing the fields, the error message always show in English.

I just had to download the translation file of the language and it was fixed by importing it through the "translate interface" area of the Drupal backend.


"Allowed memory size" errors on common tasks I get this error all the time when I'm doing common admin tasks, such as enabling modules.

  PHP Fatal error:  Allowed memory size of 33554432 bytes exhausted

How can I fix this?

Edit your sites/default/settings.php file, and change the line to set the memory limit:

ini_set('memory_limit', '100M');

or increase memory_limit in your php.ini file.


PHP Custom Form Render warning I'm receiveing the warning

Strict warning: Only variables should be passed by reference in eval() (line 2 of D:\wwwroot\tixers\modules\php\php.module(80) : eval()'d code).

Everywhere I've looked tells me its a render error but I can't find anything wrong.  The form works and submits all my info to the database, but there warning still shows up.

If you need the code for the module let me know and I will reply to it.

THANKS!

I use

<?php
print drupal_render(drupal_get_form('sellTickets_form'));
?>

then in the form 'sellTickets_form

function sellTickets_form($form, &$form_state) {

$form['team'] = array(
    '#type' => 'textfield',
    '#title' => t('Team Name:'),
    '#size' => 30,
    '#required' => TRUE,
);

......break for forms.....

$form['total_points'] = array(
    '#type' => 'textfield',
    '#title' => t('Total Points Awareded'),
    '#size' => 30,
    '#required' => TRUE,
);
$form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit'),
);
return $form;

}

function sellTickets_form_validate($form, &$form_state){
}

function sellTickets_form_submit($form, &$form_state) {
    global $user;
    $uid = $user->uid;
    $team = $form_state['values']['team'];
    $price = $form_state['values']['price'];
    $section = $form_state['values']['section'];
    $row = $form_state['values']['row'];
    $seat = $form_state['values']['seat'];
    $quantity = $form_state['values']['quantity'];
    $opponent = $form_state['values']['opponent'];
    $date = $form_state['values']['date'];
    $location = $form_state['values']['location'];
    $description = $form_state['values']['description'];
    $total_points = $form_state['values']['total_points'];
    $organization = $form_state['values']['organization'];

    db_query("INSERT INTO ticket (
    `TEID`, `price`, `location`, `date`, `organization`, `section`, `row`, `seat`, `quantity`, `opponent`, `description`, `points`)

    VALUES ('".$team."', '".$price."', '".$location."', '".$date."', '".$organization."','".$section."', '".$row."', '".$seat."', '".$quantity."', '".$opponent."', '".$description."', '".$total_points."');"
);
}

drupal_render() takes it's first argument by reference. This'll fix it:

$the_form = drupal_get_form('sellTickets_form');
print drupal_render($the_form);


How can I have the table headers repeat throughout the view results for every X results? I have a view that has a lot of columns with numbers in it and about 200 records in it.  As I view the results and scroll down, I forget what each column's title is.  Is there a module or other way to have views include the table headers ?

Assuming that you are using the display style type of table in your view, you can set the checkbox for: Enable Drupal style "sticky" table headers (Javascript)

This will freeze the headers and allow the table data to scroll.


"Merging" rows output Via the Drupal GUI, I have created the following content types and fields:

ContentType(Company)

ContentType(Site)
    Field(Company) <- entity reference to Company content type

ContentType(Contact)
    Field(Company) <- entity reference to Company content type
    Field(Site)    <- entity reference to Site content type

I'm trying to make a view (via the Views UI) which outputs a table like this:

-------------------------------------------
Company1    Site1   Contact1
-------------------------------------------
Company2    Site2   Contact2, Contact3
-------------------------------------------

I.e if two or more contacts are related to the same Company\Site combination, the output should be one row only, with all Contacts concatenated (with ", " as a separator in the example above).

But all I get is:

-------------------------------------------
Company1    Site1   Contact1
-------------------------------------------
Company2    Site2   Contact2
-------------------------------------------
Company2    Site2   Contact3
-------------------------------------------

Is there any way to get the output I want?

I know this is old but maybe it will help someone. I have found two possibilities, both with certain downsides.

Views merge rows module
does exactly what you need in terms of displaying results, however it messes up views pagination because it only changes the display of the query. But if you don't need pagination it's the way to go. Edit: I wrote a patch for the Views merge rows module to address the pagination issue. It now works perfectly.
Views Aggregation with concat function patch - if patching is an option - do it, then enable aggregation under Advanced in the view. Next step is to click on aggregation settings under the right field (in your case the 'contact' field) and set it to 'group concat'. This will aggregate the company and contact field and summarize the contact data as you specified.

Whereas this should work for the majority of use cases both solutions don't work for mine, that's why I created a new question here. Kind regards.


How do I log out with REST? I'm creating a mobile app in Ionic (which uses Angular). I've set up a D8.3-dev BE which will hold the users and their data.

I've figured out how to register as an anonymous user (this is why I'm using D8.3-dev because this functionality is introduced here) and wrote a blog post about it (https://fonsvandamme.be/en/blog/how-create-user-rest-drupal-8).

Logging in also works after I registered a user.

This is how I login:

  /*
   * Login User with username and password.
   */
  login: function (email, password) {

    var defer = $q.defer();

    $http({
      method: 'POST',
      url: config.endpoint + '/user/login?_format=json',
      data: {
        name: email,
        pass: password
      },
    })
      .success(function (data, status, headers, config) {

        // Store the CSRF token.
        localStorage.set('csrf_token', data.csrf_token);

        // Store the Logout token
        localStorage.set('logout_token', data.logout_token);

        // Set the user object.
        localStorage.setObject('user', data.current_user);

        defer.resolve(data);
      })
      .error(function (data, status, headers, config) {
        defer.reject(data);
      });

    return defer.promise;
  },

When logging in I receive the following:

current user object, a csrf_token and a logout_token.

When I use these tokens to logout (I tried a lot of different ways already:

  /*
   * Logout User.
   */
  logout: function () {

    var defer = $q.defer();

    $http({
      method: 'POST',
      url: config.endpoint + '/user/logout?_format=json&token=' + localStorage.get('csrf_token'),
      dataType: 'json',
    })
      .success(function (data, status, headers, config) {
        defer.resolve(data);

        // Go to the login page.
        $state.go("login");
      })
      .error(function (data, status, headers, config) {
        defer.reject(data);
      });

    return defer.promise;
  },

I keep getting the following error:

{"message":"\u0027csrf_token\u0027 URL query argument is invalid."}

So it seems the crsf_token I use from logging in isn't correct.

What am I doing wrong or overseeing here?

EDIT: after testing a lot and trying it seems like I need to use get. I use this code now for logout but I still get a 403:

  /*
   * Logout User.
   */
  logout: function () {

    var defer = $q.defer();

    $http({
      method: 'GET',
      url: config.endpoint + '/user/logout?_format=json',
      headers: {
        'X-CSRF-Token': localStorage.get('csrf_token'),
        'Authorization': 'Basic xxxxxxxxx',
      },
    })
      .success(function (data, status, headers, config) {
        defer.resolve(data);
      })
      .error(function (data, status, headers, config) {
        defer.reject(data);
      });

    return defer.promise;
  },

Here is what the Drupal 8.3-dev BE returns, it seems like it recognizes the user I want to log out but it's still throwing the 403.

To logout using REST in Drupal 8, you can do a POST to:
https://example.com/user/logout?_format=json&token=logout_token
Use the following headers on your request:

Content-type: application/json
X-CSRF-Token: csrf_token

The values for logout_token and csrf_token are available in the login response.
Be sure to visit admin/config/services/rest and enable the following for the User resource:

methods: POST
formats: json
authentication: cookie

Earlier versions of Drupal 8
Do a GET on ?q=user/logout
This is noted in the JS D8 REST docs: https://www.drupal.org/docs/8/core/modules/rest/javascript-and-drupal-8-restful-web-services
Although it should not matter, the Content-type may need to be set to application/x-www-form-urlencoded.
Here's an example usage from jDrupal: https://github.com/signalpoint/jDrupal/blob/8.x-1.x/src/includes/rest.inc.js#L113


Array not displaying in twig template Custom twig template is just this:

  {% for product in products %}

{{ product.title }} Image {{ product.description }}

  {% endfor %}

My custom module sends an array of products, which are something like this

array(1) { [0]=> array(3) { ["title"]=> string(9) "Product 3" ["image"]=> string(56) "/sites/default/files/2019-11/128px-Small_Storage_Box.png" ["description"]=> string(22) "Description 3" } }

And I am sending it from a controller like this:

return array(
  '#title' => t('Return products list'),
  '#products' => $products,
  '#theme' => 'return-products',
);

In my .module file I've defined hook as:

<?php
function return_products_theme($existing, $type, $theme, $path) {
  return array(
    'products' => [
      'variables' => [],
    ]);
}

I know data is there in an array, it just doesn't go inside twig template. Even if I type some Test it won't be shown.

Several things are wrong here.

Your hook_theme must return:

return [
  'return_products' => [
    'variables' => [
      'products' => NULL,
    ]
  ]
];

Now you have a template called return_products with a variable called products.

In your controller you must then use '#theme' => 'return_products', instead of '#theme' => 'return-products',.

Then create a template in mymodule/templates/return-products.html.twig.

Notice how your theme name must be with _(underscores) when referred to in PHP, but the file name must be with -(dashes).


How to display views exposed filter as links when the filter is a date field with year granularity? I have a student project View that I want to filter by year using a date field.

I would like to find a way to have the years appear as links or a menu at the top.

I have tried the Better Exposed Filters module but I don't get the option to display the year as links with a date field.

I have tried making a block view which has the date field rewritten as a link with it's token value(/2010) as well as a contextual filter on the date field .

This works except I get as many 2011's as there are values for 2011.

Is there something I could do with glossary mode?

Anyone know of a way?

You are almost there: you have to group your results by the year field.  In the settings of your display format just pick a grouping column:


Help combining 2 views? I have a content type with two fields: Exterior Images and Interior Images

Both of these fields are Unlimited Values - so the user can upload as many images as they want to exterior and interior. Screenshots: http://prntscr.com/a9m8o5 http://prntscr.com/a9m8uc

Now I'm trying to create a view that grabs all exterior and interior images uploaded and displays them.

The only way I can find to have each image displayed as its own individual field and row is to perform a UNION betwen something like SELECT exterior UNION SELECT interior etc. etc. but I just can't seem to figure out the rest.

I've tried creating two views and combining them like this:

function pgallery_views_pre_execute(view &$view){

    if ($view->name == 'photo_gallery'&& $view->current_display == 'page_1') {
        // View 1 contains Interior Images
        $view1 = views_get_view('photo_gallery');
        $view1->build('block_1');
        $query1 = $view1->build_info['query'];

        // View 2 contains Exterior Images
        $view2 = views_get_view('photo_gallery');
        $view2->build('block_2');
        $query2 = $view2->build_info['query'];

        $query1->union($query2);

        $view->build_info['query'] = $query1;

    }

}

but it won't render whatever is in $query2 - it just repeats $query1 values. So I get the correct number of "rows" from the result but it repeats the data for some reason. Please help!

Views Field View module does that. Create a new view and add both needed views as fields.

  This module allows you to embed a view as a field in a view. A new
  field handler is made available, so this can also be used in area
  (header/footer/empty) handlers as well as rows.

  This view handler can accept arguments from fields of the parent view
  using tokens and pass them into the child view for each row. Raw or
  rendered token values can be used, as well as static values.


Accessing term's tid I am trying to loop through a taxonomy term's tid, but somehow all the array elements are protected. It was very easy peasy in Drupal 7 with:

 $term_id_1 = $node->field_term['und'][0]['tid'];

I am not sure how I could access tid(here is the kint() screenshot):

and here I how I get this and my broken foreach():

public function setCollection($collection) {
$collection_array = [];
$collection_ids =  \Drupal\taxonomy\Entity\Term::load($collection);
kint($collection_ids);
foreach ($collection_ids as $collection_id) {
  $keys = $collection_id->values;
  foreach ($keys as $key){
    $collection_array[] = $key->tid;
  }
}

$this->collection = $collection_array;

}

Question 1-> Is taxonomy terms are node?

Question 2-> Is this line correct to get the fields?

  $collection_ids =  \Drupal\taxonomy\Entity\Term::load($collection);

Question 3-> Can anyone lead me to get access 'tid' from this protected 'values' array?

Warm regards.

Yes you can do $term->id() which should return the term id if $term is a Term object. See id().


Probable database character encoding error with chinese multilingual translation I am doing translation of a site's content from English to Chinese but upon saving the translation for a node(I previously did a few blocks) I get the error below. My search led me to questions like configuring drupal to use unicode characters but I just need another perspective to see if this is a different type of problem (because I already translated blocks and menus with the chinese characters) and how would I solve it.

PDOException: SQLSTATE[HY000]: General error: 1366 Incorrect string value:
'\xF4\x8F\xB0\x80\xE5\x8D...' for column 'field_overview_value' at row 1:
INSERT INTO {field_data_field_overview} (entity_type, entity_id, revision_id,
bundle, delta, language, field_overview_value, field_overview_format) VALUES
(:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2,
:db_insert_placeholder_3, :db_insert_placeholder_4, :db_insert_placeholder_5,
:db_insert_placeholder_6, :db_insert_placeholder_7); Array (
[:db_insert_placeholder_0] => node [:db_insert_placeholder_1] => 1547
[:db_insert_placeholder_2] => 7588 [:db_insert_placeholder_3] => product
[:db_insert_placeholder_4] => 0 [:db_insert_placeholder_5] => und
[:db_insert_placeholder_6] =>

 业内最可靠的视频服务器平台

作为视频服务器和存储系统的市场领导品牌,
SpectrumTM 是一 体化制作和播出系统以及完全基于文件的工作流程的理想平 台。
模块化的系统架构可以保证最大的稳定性和灵活性,使 得全球的制作人和电视专业人员都选用
Spectrum 来实现高效 的无带化工作流程。这个系统可以完全胜任于下列范围的工 作:

 从模拟到数字的设备改造,完全遵从国家标准

 从磁带到硬盘播出的改造,升操作效率

 从标清到高清的升级,升广播质量

 从单频道播出升级到多频道播出,遵从市场需
求

整合了广播视频技术领域的专家与信息技术方面的最佳实 践,Spectrum 供了最具
性价比,开放和灵活的视频服务 器,满足播出环境的严苛需求。 ￼￼￼￼ ￼
 &nbsp;

 主要特点

 独立的可扩展通道、存储、带宽并且保证冗余,智能、高 性价比架构。

在已有系统中添加新的组件即可实现高清或者 3D 播出, 确保完全的投资保护。

 在传送、
演播室制作、新闻和体育集锦、分布式播出工作 流程中是最好的基于文件的解决方案。

 可以从几百种播出应用中自由选择,基于开放标准和开放 API。

&nbsp;

 CNN - Aquisition, Playout and Storage Case Study

&nbsp;

 NAB 2013 Enter...the Spectrum!

[:db_insert_placeholder_7] => full_html ) in
field_sql_storage_field_storage_write() (line 451 of
 /var/www/html/modules/field/modules/field_sql_storage/field_sql_storage.module).

Ok So the problem was actually not the Chinese text but that I was copy-pasting from a PDF file that seemed to have injected some unwanted characters in the body that the database was rejecting.


Get the uri/path value of an image in the field template I have created a custom field template for an image - field--field_images.tpl.php with the following code:

<?php $url = file_create_url($field_images['uri']);
$url = parse_url($url);
$imglink = $url['path'];
?>

<?php foreach ($items as $delta => $item): ?>
<div data-thumb="<?php print render($imglink); ?>" data-src="<?php print render($imglink); ?>" data-time="1500" data-trasPeriod="4000" data-target="_blank" >

<?php endforeach; ?>

currently $imglink returns the value of the root folder "www". I need to find a way to get the path to the image file associated with the field e.g "http://www.example.com/sites/default/files/image.jpg" any help with this would be greatly appreciated.

UPDATE:

I think I'm almost there. Here is the code in my field-field_images.tpl.php file:
<?php foreach ($items as $delta => $item): ?>
    <div data-thumb="<?php $img_src = $element['#object']->field_images['und'][0]['uri']; $link = image_style_url('thumbnail', $img_src); print ($link);   ?>" data-src="<?php $img_src = $element['#object']->field_images['und'][0]['uri']; $link = file_create_url($img_src); print ($link);   ?>" data-time="1500" data-trasPeriod="4000" data-target="_blank" ><?php render($item); ?>

   <?php endforeach; ?>

and you can see the output here: http://www.kfpa.co.za/dev/?q=node/2

The one problem is that it loops through and creates the correct number of elements for the uploaded images, but when it creates the URLs it's only creating for the item as specified for by 'x' in <?php $img_src = $element['#object']->field_images['und'][x]['uri']; i.e if I change 'x' to '2' the third photo displays. How do I change this code so that it finds the correct URL for corresponding image in the loop?

you want file_create_url().

Note: Usage of drupal_realpath() is discouraged.

Similar question: What is the alternative to drupal_realpath()?


Files in Media and Plupload module not showing in content selector I've got the Media module installed along with Plupload. I go to the Media listing, click Add File, then I drop 3 files onto the Drag and Drop area. They show up correctly and I click Upload. They all upload correctly and the Media listing reloads and they all show up.

However, when I go to add Content and click Select Media to choose those files they are not listed.

If I go to the Media List, click Add File and then I use the File Selector to select those same 3 files and upload them that way... it works properly and I can choose them in the Content Select Media popup.

I've verified this on Chrome and Firefox. Am I doing something wrong? Has anyone run into this before? I'll post this as an issue on the Media module, but I figured maybe someone here had experienced this.

Upgrade to the latest 2.x-dev versions of media and file_entity modules.  I doubt you will see this issue anymore.


Node Hierarchy: Display Children of top most parent in views Node Hierarchy lets you assign parent/child relationships to nodes, which can be displayed in Views.

In Views, you can display the parent of a node, the ancestor of a node and the child of a node. (Instructions below*).

Is there are any way to combine this to display the immediate children of the top level parent node?

If not, are there any other modules that would allow this. (I have tried both relationship and entity references, but they don't seem capable).

*Instructions on how to display Node Hierarchy relationships in Views.

How to display Parent Node:
In Views, Go to relationships and enable the Node Hierarchy Parent relationship.
Then go to contextual filters, and selected Node ID as a filter. Under "When the filter value is available" set the Validator to content.
Create a block display and place it on your node.

How to display Ancestor Nodes:
Exactly the same as Parent Node, but the Node Hierarchy Ancestor Relationship is used.

How to display Child Nodes:
This requires a different approach from the above two, as a relationship is not used. The "Node Hierarchy: Parent Node ID" is used as a contextual filter in place of Node ID, however, the settings are the same.

You could try adding parent node as a relationship in views, then add a filter and set it to "is empty (NULL)" as a requirement of the field with relationship parent. This will only display nodes that have no parent node set.

If you want to show only nodes whose parents have no parent, you'd add a second relationship (called something like "grandparent") and then set your filter to require the grandparent, rather than the parent, to be empty.


Send email of form data? I have a block module that looks like this:

Created in the following way:

function VL_newsletter_signup_block_info() {
  $blocks['my-block-id'] = array(
    'info' => t('Enjoy Stories? - Newsletter Signup'),
  );
  return $blocks;
}

/**
 * Implementation of hook_block_view().
 */
function VL_newsletter_signup_block_view($delta='') {
  $block = array();
  switch ($delta) {
    case 'my-block-id':
      //$block['subject'] = t('Block Name');
      $block['content'] = VL_newsletter_signup_contents();
      break;
  }
  return $block;
}

/**
 * custom html block
 * @return string
 */
function VL_newsletter_signup_contents() {
  return '

Enjoy stories?

Sign up to recieve regular news

    <form>
        <input type="text" name="first" placeholder="First name">
        <input type="text" name="last" placeholder="Last name">
        <input type="email" name="email" placeholder="Email" >
        <input class="send" type="submit" name="submit">
    </form>

';
}

At the moment my form is static HTML as can be seen, but I plan to use Drupal Form API to render it. My question is: on pressing send, how can I email the form data to a designated admin email address. Can I use triggers somehow or is there another function in Drupal API that could achieve this?

You can use drupal_mail() function to send the mail data. You can also use HTML Mail module to integrate nice email templates.

I have shown drupal_mail() function.

$params = array('current_conditions' => $data);
  $to = 'user@example.com';
  $message = drupal_mail('example', 'notice', $to, $language, $params, FALSE);
  // Only add to the spool if sending was not canceled.
  if ($message['send']) {
    example_spool_message($message);
  }


How to insert a block inside the content? I need to insert a block inside in a specific place of my Drupal posts of only one type.

I understand that would be done through page.tpl.php file but can somebody explain how do I actually create that block in the first place and ascribe the right name to it? I tried searching in documentation and I'm a bit confused... Thank you!

                <?php print render($title_prefix); ?>
                    <?php if ($title): ?>

<?php print $title;  ?>

                    <?php endif; ?>
                <?php print render($title_suffix); ?>

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

You render the block in the preprocess function for that template. Each template (with its family of suggestions) has a preprocess function. For instance, if you are rendering page.tpl.php or a suggestion based off that, then the preprocess will be named THEME_preprocess_page (template_preprocess_page in the docs).

Inside the preprocess function you add a new key to the $vars array, and set it to the html output that you want printed. Then, in the template file (ie page.tpl.php) you print that variable.

example:

template.php file

function MYTHEME_preprocess_page(&$vars) {
  $block = module_invoke('module_name', 'block_view', 'block_delta');
  $vars['my_block'] = render($block['content']);
}

page.tpl file:

<?php print $my_block; ?>

You can also just assign the block to a region (below content for instance) and then move it out of there into wherever you want it by using hook_page_alter.

Drupal 7 preprocess tutorial adding variable to template

Using hook_page_alter to move node render items into blocks

Placing the contents of a block in any location

Drupal 7 - How to Print Blocks in templates


How do I find the primary links config? I'm running Drupal 7, and I am using the Acquia Marina theme. I am having issues with the drop-down menu (using superfish). The menu items with children simply remain expanded.

Every tutorial and user post I've looked at, the Primary Link Configuration table always comes up.

I cannot find this screen, anywhere. Can anybody help me?

You can get to that screen via the 'Administration' page, which you'll find at yourdrupalroot/admin . You'll need to drill down through the subpages there differently depending on your Drupal version; in Drupal 7 it will be under Structure > Menus > Main menu (the renamed version of 'Primary links').


How to avoid duplication of data using feeds module? I've set up a CSV importer using the Feeds module. My CSV is not a drupal file but one that i have, of my own. I've mapped the name of the coupon(a column in my CSV file) onto the title of my content type "coupon". This is just a test run. On importing the same data twice, it's being duplicated. I want the repetitive data to be deleted. Can someone help please?

Use Target configuration as unique to avoid duplication


drop migration tables after migration ended After uninstall migration modules the tables created not removed and still exist and can not be reasonable to deploy without remove that tables.

Problem:

The 3 modules Migrate, Migrate_drupal, Migrate_drupal_ui didn't implement Hook_uninstall() to remove these tables or other data related to migration and have no use after complete migration

The issue on drupal.org

Motivation:

List all tables prefixed with migrate_ in hook_install.
Implement hook_uninstall to remove all tables prefixed with migrate_ except those listed when install the same prefix.

Solution:

The migrate core module must list all tables prefixed with migrate_ during installl.
The migrate module must remove all tables prefixed with migrate_ during uninstall.

drop_migration_tables_during_uninstall.patch implemented the hook_install && uninstall hooks in migrate.install to drop all tables prefixed with migrate except those where found during module installation (may be other contributed or custom modules defines tables prefixed with migrate) which is not a good decision


Load more content with ajax when clicking more link in a view I have a custom block view. I display the last 5 node titles. If someone clicks the more link I want to load the next 5 titles underneath the current 5 node titles. No page refresh and not pager. Is this possible? How would I go about doing this?

So this is one of those problems that multiple people in the drupal world have tried to solve.

I recently gave a presentation on this exact same issue and how to accomplish it with drupal. Sadly I never posted any of my slides up anywhere where the rest of the world can see.

Here's the Break down of modules:

Views Infinite Scroll

Does Not work with Views Ajax support -- It hacks around it to make is own ajax request
Makes a full page request -- This is because it doesn't use the Views Ajax request
Requires Views 3.x -- This is a plus, because the pager is plug-able in 3.x

Views Infinite Pager

Support Views 2.x -- This is really not a good thing, because the pager isn't plug-able
Because it works with 2.x it really hacks around the pager theme, the regular views ajax, and preprocessing behavior. So it breaks some functionality.

And last but not least is a new project in which I just added in light of this question.  The reason for the project is my need for also needing views that support load more except the issues mention above we're not acceptable for my project.

Views load More

Requires Views 3.x - This is on purpose.
Support views regular pager options, such as offsets, page count
Fully supports views ajax feature

If Ajax is enabled on the view, the load more will add content to the bottom of the list
If ajax is disable the page will refresh and replace the old content with the new content
It does not do a full page request when doing the ajax callback, it lets views do is natural callback and instead of replacing the content it appends to it.

If you're using the waypoint module the view can be configured to automatically get new content when the user scrolls to the bottom of the page.
Supports JQuery effects (right now only the fade effect is supported, more soon to come).

Hope this answers your question. This is my "unbiased" ;-) opinion on all the views load more module.


Drupal 8: Node "options" does not exist for Node "Drupal\Core\Template\TwigNodeTrans" error after update after updating Drupal 8 from 8.6.14 to 8.6.15 (twig v1.40.1) I suddenly get this kind of fatal errors:

 Uncaught PHP Exception Twig\Error\SyntaxError: "An exception has been thrown during the compilation of a template ("Node "options" does not exist for Node "Drupal\Core\Template\TwigNodeTrans".")

It happens in my custom theme, but also in core/themes/classy/templates/views/views-mini-pager.html.twig

Do you know how to solve this or what the origin is?

According to https://www.drupal.org/project/drupal/issues/3051269 this is now resolved by the drupal team. Whatever caused the error seems to be fixed now in drupal 8.7.0


how to assign different Text formats for each Long Text fields? In my node creating form i have two Long Text fields, they are:

Article
Lists

And i have created two Text Formats they are:

Article
Lists

Now, is there any Drupal way to assign:

Article (field_article) field with Article Text Format
Lists (field_lists) field with Lists Text Format

If not, then how i can do it Programmatically in node node--article.tpl.php? or any other idea?
- Thanks

Use the better formats module. The module allows you set text formats per field.

  Better formats is a module to add more flexibility to Drupal's core
  input format system.


alter the 26 (A-Z) parent links so that just the menu link text is displayed without its associated hyperlink Within Drupal 7 I have created an A-Z menu which contains all the links on the site organized alphabetically.  In addition to these links I have 26 additional parent menu links (A-Z) from which all the site links are organized as child links within these parent links.

I then use the sitemap module to display the contents of this menu within a page with a 3 column layout.

My questions what is the most efficient way to programatically alter the 26 (A-Z) parent links so that just the menu link text is displayed without its associated hyperlink which I had to do originally when creating these links which by default I made as the homepage for all 26 parent links.

special menu items:

Special menu items is a Drupal module that provides placeholder and separator menu items.

A placeholder is a menu item which is not a link. It is useful with dynamic drop down menus where we want to have a parent menu item which is not linking to a page but just acting as a parent grouping some menu items below it.

https://drupal.org/project/special_menu_items


mysqlnd with php7.3 on debian buster I ma quite new to drupal . I've tried to install commerce 2.x on debian 10. However, php-mysqlnd is only a virtual package referring to php-mysql. there is no real mysqlnd and commerce gets stuck with this dependency.

Does that mean I cannot rund commerce 2.x on debian 10?

After taking a look at the php-mysql package for Buster it appears that the file is included with that package at /usr/share/php7.3-mysql/mysql/mysqlnd.ini.
I'd say that installing the virtual package should net you the module / driver you need. You'll likely need to enable the mysqlnd module and restart your FPM pools.
You can verify that the extension is loaded by
php -v # to get the version
php -i | grep mysqlnd

You'll probably want to enable it for cli as well as FPM.
Good luck!


How do I print logic field on page--node.html.twig? This code printing 0 or 1

{{ node.field_some_logic.value }}

I want he print NO or YES.

Somobody know, how to do this?

With simple logic, you could try using

{{ node.field_some_logic.value ? 'YES' : 'NO' }}

See ternary operator on https://twig.sensiolabs.org/doc/2.x/templates.html


How to hide Forums from anonymous users? I installed Forum module.
So, I have 'Forums' link in 'Tools' menu corresponding to the path /forum defined in forum.routing.yml in which access is defined by _permission: 'access content'.
In my site, anonymous users are allowed to "View published content", so they can see the 'Forum' link.
I don't want anonymous users to be able to see forums and, therefore, the forum topics.
I thought to override the _permission of forum.routing.yml but I don't know how to do that?
How can I do that?

Or is there another solution?

You can change the permission associated with a route doing what Altering existing routes and adding new routes based on dynamic ones / Altering existing routes says to do.

Create a service that is tagged with name: event_subscriber
The class implementing the service extends RouteSubscriberBase
The service class defines its alterRoutes() method that in RouteSubscriberBase is an abstract method

In your case, the alterRoutes() method would be similar to the following one.

  /**
   * {@inheritdoc}
   */
  protected function alterRoutes(RouteCollection $collection) {
    if ($route = $collection->get('forum.index')) {
      $route->setRequirement('_permission', 'access forum pages');
    }
    if ($route = $collection->get('forum.page')) {
      $route->setRequirement('_permission', 'access forum pages');
    }
  }

Instead of access forum pages, you can use a different permission, including an existing one that you think it suits more.


Using IN queries or joining to a temporary table inside views for data managers to use with VBO for one-off updates Our data managers routinely analyze Drupal content in external mapping and analysis programs and generate lists of nodes that require updates.  I'm looking for a solution that will allow them to update this arbitrary list of nids, preferably within a friendly UI.

Background

We've recently migrated from a custom database application to Drupal.  In the past our data managers would perform a sql in query (SELECT * FROM table WHERE ID IN (27, 83, 99, ....)) or upload a temporary table to the database, do a join and perform updates.  I'm looking for a way for them to do the same thing, but inside of Drupal so the proper update hooks are fired.

So far my Google skills and searches on drupal.org are failing me.  It seems this should be a common problem?  Is there a best practice when performing these sorts of one-off query/updates?

Some related solutions I've considered

Views contextual filters using either default arguments or arguments in the url (Create a view from specific Node ID's) - This is limited to only a few dozen nid's as a default argument or maximum url length.  Not suitable for long lists of nid's
Researched using Node Queue with the solution above but the UI doesn't seem to allow bulk adding of nodes, but perhaps I'm overlooking something.
Custom module to expose a table to views (Join a custom table on a View) - not ideal since requires programming every time a new update needs to be performed
Write a custom query and update to perform IN queries (Using IN clause in db_query) - again requires code, which I'm not opposed to if I can work up a reusable solution that our data managers (not programmers) can use to maintain our data.

An ideal solution would be a fiter criteria that allowed our data managers to paste a long csv string.  Something like "In list" which operates similar to the "Is between" functionality.

I'm overlooking something obvious! Ideas?

You could try Feeds as well .... but ...

Use either a CSV file or one of its other Migrate Sources, for instance it can use another database table as your source of change-data. But I recommend the Migrate module.

Your CSV can hold the primary key and whatever fields you need to update. You could use the new hash() functionality in Migrate 2.6 to check for changes in your data so that content is either Updated or Inserted as needed.


HTML in square brackets -> output as normal HTML We do import (using Feeds_ex) some data into Drupal (we do not control data-source we use to import data) and these data contains HTML in a brackets.

so far I have found these 3 brackets:

 1. [b]bla bla bla[/b]
 2. [i]my text[/i]
 3. [url=http://www.google.com/[/url]

I'm wondering if there is a good approach to deal with these values:

 - Convert them during import?
 - Somehow define in Drupal that these tag are equal to <b>, <i> or <a
   href>?

At the very end I want to output these data as HTML.

I would be happy to get any suggestion.

Thanks.

That's BBCode.

One option would be to simply install the BBCode module, which contains a BBCode filter. You can then apply that filter to the text format you're using for the body field, and it'll be converted to HTML automatically when rendered.


Filter Views results by users mobile OS I'm building a mobile website with Drupal 7 and I need to filter articles displayed using Views by visitors mobile OS. If visitor is using Android phone - I would like display only articles with "Android" tag, etc. Visitors with "other" mobile OS'es will get "no results" message.
What is the best approach to accomplish this task?

I would take a look at the Context module with this add-on: Context Useragent


unable to link my custom content type nodes to a menu I created I created a custom content type (pics). I can add this new "pics" content to my site (and if I want to, it can appear on front page, but I don't want to...) with no problem. But I would like those new added contents appear in my new menu (called Photos).

When I created my new content type I got a " machine name" : "pics". Then I created a new menu called "photos" and I put this name into the path field like this: http://www.example.com/drupal/pics

But it doesn't work this way. The menu will be empty with a Page not found message.

I'm new to drupal, so please bare with me.
Please let me know the solution.

By default, Drupal 7 does not create a filtered list of content. You're going to want to use Views Page to create a list of content.

Delete the menu item you created, then install https://www.drupal.org/project/views and its dependency https://www.drupal.org/project/ctools

If you have Drush installed...

drush dl views
drush -y en views views_ui

In your browser, go to /admin/structure/views
Click "Add new view".

View Name: Photos
Show [Content] of type [Pics]
[X] Create a page

Page title: Photos
Path: pics
Display format: Table

Click "Continue & edit" to customize

For information on Views, see https://www.drupal.org/documentation/modules/views


Where does views's template files get saved? I have created a view for content type = "Article" and have chosen "FORMAT" = GRID

FORMAT

Format:Grid | Settings

Show:Fields | Settings

My question is where does this view related template get saved?

I know Views default templates are located under "/core/modules/views/templates/" folder.

Here is the basic GRID template. How this grid template recognize a specific view that can render fields only of "ARTICLE" content type?

Is there any other template formed using view's machine name and row style?

Where should I place any view template so that it can effect all views of specific content type like "Article".

Where should I place any view template so that it can effect all views
  of specific content type like "Article".

While you can do this with nodes, I don't believe it's possible on views to affect all views of x content type. As you can see in FILTERS, there is a Type filter (=Article). It's just a filter.

The best option you have is to make it affect a specific view name and a view display.

EX: views-view-grid--[view-name].html.twig

if you want to specify a display then views-view-grid--[view-name]--[machine-name].html.twig

Then you copy the code from core's views-view-grid.html and paste it on your template file and modify as you wish.

If you want to alter fields, then use views-view-fields--[view-name]--[machine-name].html.twig

You place your custom template files in /themes/[Your Theme]/templates folder.


How to code a views filter to exclude parents that have children I am using the Project Modules.

Some projects have no tasks others can have one or more tasks. In SQL terminology this is a one-to-many relationship, I believe.

I think the generated SQL joins Tasks node type and Projects node type.

I am using grouping so that tasks belonging to the same project are grouped together and projects without tasks are also grouped together. The problem is that projects that have tasks appear twice--in the "header" above the tasks associated with that particular project AND in the list of projects without tasks. I want the project title to appear only in the header above the tasks associated with that particular project.

There is an Entity Reference that links tasks to projects utilizing the field_data_pmtask_pmparent table. I am not using this in my view.

How can I code a filter to omit projects that have tasks from the list of projects that have no tasks?

My View

The following is designed for Projects and Tasks, but would probably work for any Entity Relationship with optional children of a parent.

To create a view that lists all parent nodes (in this case Project content type) whether they have children (in this case Tasks) or not use the following methodology.

The output will be all Projects with Tasks listed below them if they have Tasks.

Create a View for Projects. The Format chosen was Table, but other options would probably work.

Table Settings should include Grouping field Nr. 1 set to Content: Title. Check all the boxes Hide Empty Column for each field.

In the Fields section of the View do not list fields that are in the Project data type. Use only those in the Task data type. The Project title will automatically be retrieved because of the relationship in the Task data type that points to the owning Project. Filter Criteria should be set to Content Type = Project.

Click Advanced on the View page then click Add (next to RELATIONSHIPS). Click the drop down box and select Entity Reference. Select "A bridge to the Content entity that is referencing Content via pmtask_parent". Type Tasks into the Identifier blank. This establishes a BACKWARD reference to Projects. Require this relationship should NOT be checked because there are Projects without Tasks. You must read the Entity References very carefully. Some are very similar to each other.

There appears to be no way to find a list of all Entity References in Drupal except to add an existing field to a content type (Manage Fields) and to click the drop-down arrow next to it to select a field. Entity References are preceded by the term Entity Reference.

From the database perspective, the pmtask_parent Entity Reference is an index (or pointer) to the parent database record. In this case, the Project. Traditionally relational databases would create separate tables for Tasks and Project, but Drupal does things differently with both stored in the node table. The field_data_pmtask_parent table serves as the linkage between the two node types.

Above from https://www.drupal.org/node/2533748.


Show 1 random node out of the 5 most recent in views I would like to create a block on my homepage where I show my visitors the most recent node (of a specific content-type) I've created. The block should load the 5 most recent nodes but only show one of them on page load.

I've managed to show a random product on page load, but the views takes a random node from all my nodes of that content-type. Is there a way I can limit the nodes, where the random block can chose from, to 5?

I wasn't able to get this working within views proper, so I added a subquery instead.
There are three relevant things that need to be set up in your initial view to get this to work:

Filter Criteria: Content: Type = 'my content type' (blog post in
the attached image)
Sort Criteria: Global: Random
Pager: Use Pager: Display a specified number of items: 1

As it is, that will get you a view that will pull in 1 random result from among all content of type "my content type".
But the question is asking you to pull in 1 item from the last 5 created posts, not from all posts.
To do that, you need to add an additional where condition. That can be accomplished with this snippet:
/**
 * Implements hook_views_query_alter().
 *
 * Limits results to the most 3 recent blog posts.
 */
function MY_MODULE_views_query_alter(&$view, &$query) {
  if ($view->name == 'MY_VIEW_NAME' && $view->current_display == 'MY_CURRENT_DISPLAY') {
    $query->add_where_expression('AND', "node.created > (SELECT node.created AS created
      FROM
      node node
      WHERE  (type = 'MY_CONTENT_TYPE')
      ORDER BY created DESC
      LIMIT 1 OFFSET 5)");
  }
}

That snippet says:
"Find me the creation timestamp of the node that is the fifth-newest. Then filter my final result by nodes with creation timestamps greater than that."
There might be a better way, but this works for me.


How to show results from the last search? I have this senario:A user makes a search (using search api solr).
After some days he returns to the site and in the front page appear results related to the last search he made.
How can I accomplish that with Search api?
thanks

You could try Search API Saved Searches Module

  This module offers users the ability to save searches executed with
  the Search API module and be notified of new results. Notifications
  are done via mails with token-replacement, their frequency can be
  configured both by admins and/or users and saved searches can also be
  created without first executing the search.

  Facet, Views or other filters set for the search will also be included
  in a saved search, thus reflecting exactly the same search results as
  displayed.


Add an item to a list for Rules and References I have a Node Reference in Users.

When I set Add an item to a list with Node identifier for some event, it doesn't add.
It looks like this

Add an item to a list
Parameter: List: [account:field-badges], Item to add: 28

Set a data value works with comma separated list.

The "add an action" form says: "To make entity fields appear in the data selector, you may have to use the condition 'entity has field' (or 'content is of type')."

My field was in the data selector but the item was not added by the action.

I changed the action to a rule with a condition "entity has field" as requested, the field being the one I wanted to add a value to. Then I recreated the action in the actions area.

This was the solution for me. Hope this helps.


Content publication authorization I need some information on how to achieve a solution which will allow a group of users to create content but the content remains unpublished until multiple managers have somehow signed off on the content of the node page.

I'll be happy if the suggestion comes in the form of a module and/or a recipe on configuration steps.

The Workbench module provides you a customizable editorial workflow. Here is a quote about it (from the module's project page):

... provides overall improvements for managing content that Drupal does not provide out of the box. Workbench gives us three important solutions:

a unified and simplified user interface for users who ONLY have to work with content. This decreases training and support time.
the ability to control who has access to edit any content based on an organization's structure not the web site structure
a customizable editorial workflow that integrates with the access control feature described above or works independently on its own

These features benefit the end users as well as Drupal Site Administrators and Technical Support.


Masonry effect not loaded in D7 Masonry Views I had installed Masonry Views module, along with Masonry module in my Drupal 7 site.
In my view, I can select format as "Masonry", and had updated the details such as column width.
But the output still displays the view like unfomatted list.

In my status report, it shows
jQuery Masonry: 2.1.08
jQuery Update: jQuery 1.7.1 and jQuery UI 1.10.2

My js file is in: www/mydomain/sites/all/libraries/masonry/jquery.masonry.min.js

I had flushed cached, but the masonry effect still doesn't appear. Any idea what's the problem?

It's just because you are just updating a Jquery version in front end theme but not updating in admin theme. Because views opens in admin theme so you should also update Jquery version in it. For getting this work just goto admin/config/development/jquery_update  and click on configure link in front of admin theme, then select the same version of Jquery as you selected in front theme. Now you can edit the masonry views as per your needs and check the result.


ajax_command_invoke adding a new item in a field collection I'm using the field_collection module.
A collection has a "custom field" I've created, which rely on a jQuery plugin.
When I add another item in my collection, the jQuery plugin is no more invoked, and the field doesn't work anymore.

At the first load, all is working, it's only after adding a new item.

I don't know how to invoke the jQuery plugin initialization, there is probably something with the ajax command "field_add_more_js", but I can't figure out which hook or which solution I can use :(

Do you have any idea ?
many thanks

Actually, it was quite simple... I use Drupal.behaviors to attach my jQuery plugin initialization to the form, and it's now called on ajax callback as well, when a part of the form is updated by this ajax call.
So it's fixed !

The drupal documentation helped me, and the Lullabot article as well !


Capturing return value from remote post hander I have a number of forms set up using Webforms (the module formerly known as yamlforms) in Drupal 8.

This data is stored in Drupal, but is also sent to a remote CRM using a Remote post handler added to the form. The CRM handler generates a key for the newly added lead that I would like to use in my success message. There's no option for capturing data from a remote post though.

Does a solution already exist for this, or am I doomed to writing my own module?

There is no built in solution for this, you have extend the Remote post handler and write some custom code.

Please open a ticket in the Webform issue queue. Ideally, the remote post handler would be able to populate some meta data that could be exposed via a token.


How to use t() function with node_load in custom drupal module? I am using a custom module for my site, and I am using node_load to get the field value of type "long text" field and field of value of type "text".

Something like this

$com_types = "".$ucom->node_title."";

How should I translate $ucom->node_title ?

t() function does not translate variables.

Thanks

Node translation should be done at the node level.  the t() function is for labeling elements of the interface and theme things.

You should look at multi-language node translation modules,  this link is helpful

You'd first want to use something like this:  https://api.drupal.org/api/drupal/modules!translation!translation.module/function/translation_node_get_translations/7

It'll let you get the NIDs of the translated versions of the node you want,  then you can use node_load() to get the translated version.


Additional Information pop up box next to a variation in drupal commerce I am creating a commerce site using Drupal Commerce, there are some variations for products that I would like to inform the customers about. Theres the option of having a sticker finish that is a variation and I wanted to have a "What is this?" text field right next to the select list that then launches a colorbox/fancybox/popup that displays additional information about that variation. Something similar to this:

I was surprised that there wasn't a module that did this so I've created one.

It is only a sandbox project at the moment as I'm still waiting to get approved to create full projects.

Sandbox page

It can however be downloaded from here. You will then need to extract the .tar.gz to a .tar, and then extract that to a folder called "2240445-cbcb2b4" and then rename that folder to field_info_popup (Phew!).

I've tested it with all the core field types and seems to work fine but if you do find any bugs then they can be posted here.


What is placeholder_token in html.html.twig for? Started to dive into Drupal 8 twig, and what better place to start than from the top:  html.html.twig

But found this:

<head-placeholder token="{{ placeholder_token|raw }}">

Here is the change record:

#2565021: HTML template head, scripts, styles and scripts_bottom replaced with placeholder_token

And some related issues:

#2538950: Replace SafeMarkup::format() in template_preprocess_html with placeholders in the template
#2603074: Remove |raw from use in core templates

And the documentation:

html.html.twig on api.drupal.org

But nothing really clarifies why this was done.

Is this a Drupalism? A Twigism? What are these tokens for?

The only other time I've seen a placeholder token system like this was with CTools where they create a placeholder in the generated HTML output and then go back later and replace the token with the actual value.  If this is the same concept, why does Drupal core need to do this? (The CTools system was ostensibly to get around some core limitations).

The reason why placeholder_token is used in html.html.twig instead of using just a normal variable is that in Drupal 8 we have different render strategies than just the simple rendering where everything gets rendered in the template and we are able to collect the assets.

In the Drupal cores default Renderer we have placeholders (placeholders might attach some additional assets). If we would print the assets in a normal variable it would happen before all the assets have been collected. So what Drupal 8 does is it first renders everything with the normal rendering in the template, then it replaces the placeholders and collects assets from then, and after all that has been done we finally replace the asset placeholders to add the assets to the page.


How to add custom path for taxonomy term page I need to give custom path for one of my taxonomy term page which will be redirected to view page.
Example:- I have view page called testimonial and in my taxonomy i have a term called user testimonials which should be redirected to testimonial view page once user click on the term.

I have tried taxonomy menu but its custom path feature is no more available.
Any suggestion, how can i complete this functionality.

Here is sample code that will allow you to redirect all taxonomy paths to a custom URL.

function sample_entity_info_alter(&$entity_info) {
  $entity_info['taxonomy_term']['uri callback'] = '_sample_taxonomy_term_uri';
}

function _sample_taxonomy_term_uri($term) {
  return array(
    'path' => 'path-to-your-view/' . $term->tid,
  );
}

Hope this helps.


No page content displaying on front page When I go to set my Drupal 7 site's front page (Administration » Configuration » System » Site information) to a basic page that I've created, and then load the front page, nothing is displayed in the content section on the front page except for the site's header (masthead, navigation, search, etc.), footer, and sidebar for that page. Basically, the content of the page won't display when it's set to be the front page. It displays fine when it's not the front page. What gives?

Try viewing the page source to see what is there. Does it match your front page layout file?

Have you modified the front page layout file?


RSS does not validate properly I am trying to generate an RSS feed, but it does not validate. I googled around and found RSS Feed does not validate using Views RSS module, but unfortunately it's for Drupal 7, while I am using Drupal 8.4.4.

What a similar method for Drupal 8 would be? The XML I get has an empty line before <?xml version="1.0" encoding="utf-8"?>, which I believe it's the main problem.

<?xml version="1.0" encoding="utf-8"?>
  <rss version="2.0" xml:base="https://example.com/feeds.xml" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:foaf="http://xmlns.com/foaf/0.1/" xmlns:og="http://ogp.me/ns#" xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#" xmlns:schema="http://schema.org/" xmlns:sioc="http://rdfs.org/sioc/ns#" xmlns:sioct="http://rdfs.org/sioc/types#" xmlns:skos="http://www.w3.org/2004/02/skos/core#" xmlns:xsd="http://www.w3.org/2001/XMLSchema#">
    <channel>
      <title>Title</title>
      <link>https://example.com/feeds.xml</link>
      <language>en</language>

      <item>
        <title>UAE Lenders Upbeat as Growth Prospects Surge</title>
        <link>https://halaltimes.com/uae-lenders-upbeat-growth-prospects-surge</link>
        <description>  &lt;img src=&quot;/sites/default/files/styles/large/public/Article/growth-prospects-surge-in-uae.jpg?itok=VEwWB-9R&quot; width=&quot;480&quot; height=&quot;320&quot; alt=&quot;&quot; typeof=&quot;Image&quot; class=&quot;image-style-large&quot; /&gt;

Do you have a template for views-view-rss.html.twig in your theme folder?
Try enabling the Twig debug feature if you are not sure.

The default one in core/modules/views/templates works properly (same core version).


How to style the help text that appears at the top of pages? I'm using the "Piano" theme, and I just don't like the way it displays the help text that would normally appear as a red box when there's an error or a green box for information or to indicate that something processed successfully. I really just want it to be back to normal because right now it's easy to miss and it kind of blends in to the rest of the text.

What you're looking for is the $messages variable, which is given the following styling by core, yet seems to be removed from that contributed theme:

div.status {
  background-color: #f8fff0;
  border-color: #be7;
  color: #234600;
}
div.warning {
  background-color: #fffce5;
  border-color: #ed5;
  color: #840;
}
div.error {
  background-color: #fef5f1;
  border-color: #ed541d;
  color: #8c2e0b;
}


How field values are stored in the database I'm working in a migration from Drupal 7 and I'm trying to find out where the value of some fields are. I've tried but could not find an answer for this on this site.

I see each field has a pair of tables:

field_data_field_{field_name}
field_revision_field_{field_name}

Some of the field_data tables have a column named field_{field_name}_value and that's easy to find.

However, other tables don't have this column and have one called field_{field_name}_target_id. Inside it they have an integer but I can not find where it is referenced to...

I'm looking only at the database, I don't have the code (yet) and I don't know if this is related to a module, or if this is Drupal native. Anyhow, I can't find any other table with the values that relate to these Ids...

Different field types can have different data columns in the database. Most modules have a 'value' column. Others, like reference fields, have a 'target_id' column instead. The Date module can create a 'value1' and 'value2' column (for start date / end date).

You can't assume that it is always 'value'.

The 'target_id' value refers to the ID of the entity being referenced. So, if the field is referencing nodes, target_id is holding a node id value. If the field was referencing users, the value stored is the user id.


Can I use simple XML to feed views? I want to use the power of views to handle my data which comes from simple xml representing just a grid resp table

<list>
  <listpos id="12312">
    <foo>attr1</foo>
    <bar>attr bar</bar>
    ...
  </listpos>
  <listpos id="124412">
    <foo>attr 2</foo>
    <bar>attr barxy</bar>
    ...
  </listpos>
  ...
  ...
</list>

So the main task is to display that table sortable, exclude some columns, filter and search etc.

Is this possible with views? It would be handled by a plugin i guess? Or are plugin only for output? (I know of the json, atom etc plugin / modules.)

I also tried the feeds module plus xml / xpath parser and let the importer create the nodes so a view can display them. But I have to delete them anyway after user logs out because it's sensitive data and should not be kept on the webserver.

And what about combining this data with other sources i.e. join with a node table?


Email Validation php When validating an email address using the code below I get this error when i run the same code from within a drupal node, where I coded a form using php/html

if (filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE) {
$errors[] = 'Please enter valid email';
}

I get this error:

Fatal error: Call to undefined function filter_var() in /var/www/html/drupal1/includes/common.inc(1743) : eval()'d code on line 53

A better option might be to use valid_email_address() to keep it all Drupal friendly :)

  Verifies the syntax of the given e-mail address.

  See RFC 5322 for details.

Example:

if (valid_email_address($email) != TRUE) {
  $errors[] = 'Please enter valid email';
}


Manually including Webform in a single node Anyone know how to include Webform module into a single node?  Is there a function I can include to do this.

A discussion on Drupal has resulted in a patch that allows you to display a webform in a block (and then you can display that block only on your node tpl page).

EDIT: The patch has been included in the latest version of webform.

Additionally, you could try using this PHP code:

<?php
    $node = node_load($nid);
    print node_view($node);
?>


Template suggestions based on path alias I'm trying to work out how I can add my own template suggestions based on the set URL alias. I've found lots of information out there regarding Drupal 7, but very little for 8.

I know I can use hook_theme_suggestions_page_alter(array &$suggestions, array $variables).

Basically, I'm looking to convert this to Drupal 8.

$alias = drupal_get_path_alias($_GET['q']);
if ($alias != $_GET['q']) {
  $template_filename = 'page';
  // Break it down for each piece of the alias path.
  foreach (explode('/', $alias) as $path_part) {
    // Added the str_replace because path parts with - were not being picked up properly by the theme_hook_suggestions().
    $template_filename = $template_filename . '__' . str_replace("-", "_", $path_part);
    $variables['theme_hook_suggestions'][] = $template_filename;
  }
}

OK, I seem to have got it working.

function THEME_NAME_theme_suggestions_page_alter(array &$suggestions, array $variables) {
  $current_path = \Drupal::service('path.current')->getPath();
  $result = \Drupal::service('path.alias_manager')->getAliasByPath($current_path);

  $path_alias = trim($result, '/');
  $path_alias = str_replace('/', '-', $path_alias);

  $suggestions[] = 'page__path_alias__'.$path_alias;
}


Why do I get errors abot undefined variables and errors with unserialize()? Sometimes I get these errors on my site that I'm developing with the distribution of Commerce Kickstart:

  Notice: Undefined index: title_value en link_field_update_instance() (línea 1305 de /home/content/90/9397890/html/a/profiles/commerce_kickstart/modules/contrib/link/link.module).
  Notice: Undefined index: title_value en link_field_update_instance() (línea 1305 de /home/content/90/9397890/html/a/profiles/commerce_kickstart/modules/contrib/link/link.module).
  Notice: unserialize() [function.unserialize]: Error at offset 10301 of 11637 bytes en views_db_object->load_row() (línea 2243 de /home/content/90/9397890/html/a/profiles/commerce_kickstart/modules/contrib/views/includes/view.inc).

Do you have any suggestion about how to avoid these notices are reported?

The best way to get the issue resolved would be to file an issue for the Commerce Kickstart project on drupal.org.

The reason you're receiving those notices is because ideally, in a perfect world, line 1305 would say something like this (to avoid such notices):

  if (function_exists('i18n_string_update') && isset($instance['widget']) && isset($instance['widget']['type']) && $instance['widget']['type'] == 'link_field' && isset($prior_instance['settings']) && isset($prior_instance['settings']['title_value']) && isset($instance['settings']) && isset($instance['settings']['title_value']) && $prior_instance['settings']['title_value'] != $instance['settings']['title_value']) {

But as you can probably see, that if statement is now twice as big. And since it's only a notice you're receiving, chances are the developer(s) won't put that issue as a top priority.

The easiest way to resolve the issue on your own though is to set the value of error_reporting to E_ALL & ~E_NOTICE inside your php.ini file, like so:

error_reporting = E_ALL & ~E_NOTICE

That should suppress all notices that you might be seeing, including the third notice regarding unserialize.

Hope that helps... :)


for anonymous user, webform not submitted because of private file I have one webform which contain the private file field.

As admin user: i can upload the file and submit the form.

As anonymous user: i can upload the file but while saving the form, i am getting 'file field is required'

Uploaded file '/system/files/webform/abc.jpg' present at  '/sites/default/files/private/webform'.

As Anonymous user:
i can access file using '/sites/default/files/private/webform/abc.jpg' but get access denied using '/system/files/webform/abc.jpg' url.

Additional Info:

File Setting:

Private Path : 'sites/default/files/private'

Public Path : 'sites/default/files'

Drupal 7.64

Webform : 7.x-4.18

First and foremost, you've got an error in how you set up your private files path. It should be located outside of your web root, not as a subfolder of your public files. The way it is now, your private files are actually public. That is the reason why you can acces the file at '/sites/default/files/private/webform/abc.jpg', you shouldn't be able to do that.

Now as to why you get an error uploading it is probably an issue with how your permissions are configured for private files. The anonymous user can upload to the private files, but does not have sufficient permissions to access the uploaded file.


How to store user location I use Smart IP module to track user location with option IPInfoDB.com. But as I understand Smart IP does not store by default user location in database. Is there any option to configure this or I need to make own module? Ultimately I need to show user who is in the same city or region.

No. Smart IP is solely for IP geolocation, it doesn't not touch storage of user location addresses.

Depending on your needs, Location (with the User Location submodule) or a combination of GeoField/Address Field on your a profile (you might want to guess the location while letting the user determine what his address) will get your location storage needs.

None of those modules have Smart IP integration so you'll have to build some custom code to add IP geolocation to either of those storage options.


FieldCollection/PLUpload - Recurring error when uploading images on PROD - "No file by that name exists" TL;DR Pantheon's distributed file system can't handle modules that refer to the temp file system across multiple requests, which messes up the Plupload module. What alternatives are there?
The error occurs when users upload images to the site using PLUpload, and it only occurs in the LIVE environment.  Our discussions with pantheon support indicate that this is likely something to do with our code not playing nicely with the load balancing in the live environment.  At this point though, we're pretty stumped on how to proceed.  I was hoping someone here may have encountered it and could provide some insight on how to proceed.
In case the screenshots do not share correctly, I have included a link to a google doc
Here's an example of the error message.

Some notes:

We uploaded 5 images here.  2 were rejected as you see in the pink
notification below.  The number of failed images appears to be
entirely random - sometimes all will work.  Sometimes just 1,
sometimes none.
We have tried changing the path
from temporary:// to public:// - this error appears to occur
regardless of where the temp space is pointed. Only occurs in the
live environment due to the load balancing in use with our hosting provider
Cloud-based hosting, so we do not have access to make changes to the load balancer.

Steps we've taken:

Insert watchdog in file.inc where we see this error
Enable dblog and try to reproduce the error you see above.
Identify the failure point in the debug log.  Here's what we see:

Watchdog is showing that the file in question does not exist
We check the SFTP, and it's definitely there.

In our discussions with the hosting provider, here's what we learned:

This is likely a fringe case that the load balancer doesn't have the ability to handle.
It sounds like the module is making a number of requests with the assumption that they can share a tmp directory.
and this comment:

Do you know if the PLUpload file issues multiple HTTP requests (via AJAX maybe?) when doing the uploads? If so, it may be that it's assuming that the temporary filesystem is shared between all requests.
This is a common flaw in a lot of contributed modules or plugins: they assume that there's only one place the code is executing, and that the "temp" filesystem space is available consistently across N requests.
This isn't what temporary filesystems are really for, but in a legacy single machine architecture it will rarely cause failures. Once you are distributed that assumption will fail quite reliably.

Now for the part that has us stumped:

It seems that PLupload might not be our best approach.  If we want to get it to work, we'd have to figure out how it's handling temporary file requests.
Our site was originally built with PLupload and Field Collection working together.  I'm curious if there's other modules we can look into that will allow us to get the functionality of both within the confines of the hosting environment.

This is a note for people who face this problem. Maybe it can help them.

I had this error on a project. I see that it occurs on a plupload widget with a limit of file number set to 1. I replaced this field by a classic upload and the problem gone.


Check Login and display login page in views I created a Search on my website with views exposed filters. I want only the logged in users to view the entire content. So, when the user clicks on View More.. Link I want them to be redirected to the log in page or pop up a login block.

Thanks,
Prerna

In your view set the Access of the page display to role > authenticated user. This will present an Access Denied message to anonymous users.

You can then enable the Login Toboggan module and enable "Present login for on access denied (403)". After the user logs in, they will be taken back to the view page automatically.