Views filter based on value in referenced entity I'm attempting to use a view to display the body of a content type that is referenced based on a field referencing another content type as long as that content type is referenced by another field. Confusing I know. Here's a diagram of what I'm trying to accomplish.

I need to display the body and title of all 'news' that reference a 'horse' that an 'owner' references as long as that 'owner' is referencing the current user.

I understand that there would be much better ways to structure my content type fields to get them to play more nicely, and I understand that I could easily accomplish this by not using views and making a custom module but that isn't an option available to me. I am required to use views. I wouldn't mind creating a custom views filter plugin, or use a hook though. I understand how to perform entity queries that can accomplish this task. However I'm not sure how view filter plugins work.

Is there a way to accomplish this specifically with views?

So assuming there's a content type with machine name new for News, owner for Owner, horse for horse.

The news content type has a field named field_horses referencing horses

The owner content type has an instance of the same field field_horses and a
reference field to User, field_user

Create a view listing Content of type News

Add a relationship

Entity Reference: Referenced Entity
A bridge to the Content entity that is referenced via field_horses

require this relationship

add a second relationship

Entity Reference: Referencing entity
A bridge to the Content entity that is referencing Content via field_horses

have this second one use the first relationship "Content Entity referenced from field_horses"

require this relationship

add a third relationship

Entity Reference: Referenced Entity
A bridge to the User entity that is referenced via field_user

have this third relationship use the second relationship "Content referencing content from field_horses"

require this relationship

For filters you need two content type filters
One for Content type = News, using no relationships
another for Content Type = Owner using the "Content referencing content from field_horses" relationship

One user filter, Current User (yes), using the "User entity referenced from field_user

$view = new view();
$view->name = 'news';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'node';
$view->human_name = 'News';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'News';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '10';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'fields';
/* Relationship: Entity Reference: Referenced Entity */
$handler->display->display_options['relationships']['field_horses_target_id']['id'] = 'field_horses_target_id';
$handler->display->display_options['relationships']['field_horses_target_id']['table'] = 'field_data_field_horses';
$handler->display->display_options['relationships']['field_horses_target_id']['field'] = 'field_horses_target_id';
$handler->display->display_options['relationships']['field_horses_target_id']['required'] = TRUE;
/* Relationship: Entity Reference: Referencing entity */
$handler->display->display_options['relationships']['reverse_field_horses_node']['id'] = 'reverse_field_horses_node';
$handler->display->display_options['relationships']['reverse_field_horses_node']['table'] = 'node';
$handler->display->display_options['relationships']['reverse_field_horses_node']['field'] = 'reverse_field_horses_node';
$handler->display->display_options['relationships']['reverse_field_horses_node']['relationship'] = 'field_horses_target_id';
$handler->display->display_options['relationships']['reverse_field_horses_node']['required'] = TRUE;
/* Relationship: Entity Reference: Referenced Entity */
$handler->display->display_options['relationships']['field_user_target_id']['id'] = 'field_user_target_id';
$handler->display->display_options['relationships']['field_user_target_id']['table'] = 'field_data_field_user';
$handler->display->display_options['relationships']['field_user_target_id']['field'] = 'field_user_target_id';
$handler->display->display_options['relationships']['field_user_target_id']['relationship'] = 'reverse_field_horses_node';
$handler->display->display_options['relationships']['field_user_target_id']['required'] = TRUE;
/* Field: Content: Title */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'node';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['label'] = '';
$handler->display->display_options['fields']['title']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['title']['alter']['ellipsis'] = FALSE;
/* Sort criterion: Content: Post date */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'node';
$handler->display->display_options['sorts']['created']['field'] = 'created';
$handler->display->display_options['sorts']['created']['order'] = 'DESC';
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'node';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = 1;
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;
/* Filter criterion: Content: Type */
$handler->display->display_options['filters']['type']['id'] = 'type';
$handler->display->display_options['filters']['type']['table'] = 'node';
$handler->display->display_options['filters']['type']['field'] = 'type';
$handler->display->display_options['filters']['type']['value'] = array(
  'news' => 'news',
);
/* Filter criterion: Content: Type */
$handler->display->display_options['filters']['type_1']['id'] = 'type_1';
$handler->display->display_options['filters']['type_1']['table'] = 'node';
$handler->display->display_options['filters']['type_1']['field'] = 'type';
$handler->display->display_options['filters']['type_1']['relationship'] = 'reverse_field_horses_node';
$handler->display->display_options['filters']['type_1']['value'] = array(
  'owner' => 'owner',
);
/* Filter criterion: User: Current */
$handler->display->display_options['filters']['uid_current']['id'] = 'uid_current';
$handler->display->display_options['filters']['uid_current']['table'] = 'users';
$handler->display->display_options['filters']['uid_current']['field'] = 'uid_current';
$handler->display->display_options['filters']['uid_current']['relationship'] = 'field_user_target_id';
$handler->display->display_options['filters']['uid_current']['value'] = '1';

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['path'] = 'horse-news';


How to embed drupal content in other sites (remove X-Frame-Options: SAMEORIGIN)? I tried to make a iframe with a drupal page but I received the following message:

  Multiple "Refused to display (page adress) in a frame because it set 'X-Frame-Options' to 'SAMEORIGIN'."

Then, I tried to change the header of response in page controller using

$response->headers->set('X-Frame-Options', 'GOFORIT');

And I received the following message

  Multiple 'X-Frame-Options' headers with conflicting values ('GOFORIT, SAMEORIGIN') encountered when loading '(page adress)'. Falling back to 'DENY'.

Drupal core puts the following code in all responses.

$response->headers->set('X-Frame-Options', 'SAMEORIGIN', FALSE);

So, how can I override the X-Frame-Options header for only this response to embed this page in other sites?

I'm using Drupal 8.0.0.

Drupal 8 adds the response header X-Frame-Options: SAMEORIGIN to all pages. This prevents that the content is included in iframes on third party sites.

You can check this for example in the google image search that your content does not appear in the preview frame.

This feature was introduced in drupal 8 beta 13.

The change record

Core is now protected against click-jacking by default (X-Frame-Options: SAMEORIGIN)

is not correct in that the priority has to be higher, in fact it has to be lower. The code example changes the request but it has to change the response.

To provide a solution to the question here is the complete code including the yaml file to put this in the service container:

mymodule/src/EventSubscriber/RemoveXFrameOptionsSubscriber.php:

<?php

namespace Drupal\mymodule\EventSubscriber;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;

class RemoveXFrameOptionsSubscriber implements EventSubscriberInterface {

  public function RemoveXFrameOptions(FilterResponseEvent $event) {
    $response = $event->getResponse();
    $response->headers->remove('X-Frame-Options');
  }

  public static function getSubscribedEvents() {
    $events[KernelEvents::RESPONSE][] = array('RemoveXFrameOptions', -10);
    return $events;
  }
}

mymodule/mymodule.services.yml:

services:
  remove_x_frame_options_subscriber:
    class: Drupal\mymodule\EventSubscriber\RemoveXFrameOptionsSubscriber
    tags:
      - { name: event_subscriber }


Views: upcoming events list with first upcoming event at the top I have content type which have date field(multiple). It also collect the end date.

Now I am creating a view which will list the nodes of that content type.

It will sort the nodes with the start date in ascending order.
And only those nodes will display whose start date is greater than the current date.

I have added the filter of start date. If start date is greater than the current date. The option Add multiple value identifier is set to Yes in the filter settings.

In the query settings I Distinct and pure distinct is checked. I have also tried the aggregation but still the view returns duplicate results.

Any Idea how will remove the dupliation?

EDIT

This is the sql query that view generates

SELECT DISTINCT node.title AS node_title, node.nid AS nid, field_data_field_event_date_time.field_event_date_time_value AS field_data_field_event_date_time_field_event_date_time_value, node.created AS node_created, 'node' AS field_data_field_event_date_time_node_entity_type
FROM
{node} node
LEFT JOIN {field_data_field_event_date_time} field_data_field_event_date_time ON node.nid = field_data_field_event_date_time.entity_id AND (field_data_field_event_date_time.entity_type = 'node' AND field_data_field_event_date_time.deleted = '0')
WHERE (( (node.status = '1') AND (node.type IN  ('event')) AND (DATE_FORMAT(ADDTIME(field_data_field_event_date_time.field_event_date_time_value, SEC_TO_TIME(-25200)), '%Y-%m-%d\T%H:%i') >= '2014-05-15T22:19') ))
ORDER BY field_data_field_event_date_time_field_event_date_time_value ASC, node_created DESC
LIMIT 10 OFFSET 0

The problem is if an event has 2 dates then it is displaying two times and if it has 3 dates then it is displaying 3 times in the results.

I have managed to do this by creating a module (easier than you might think) and adding a post execute function like this (text in caps has to be replaced by your module and view names):

function MODULENAME_views_post_execute(&$view) {
  if($view->name == "MYVIEWNAME") {
    $view->result = array_reverse($view->result);
  }
}


Post Migrate Development to Live Production Server issue I'm positive I've successfully done this before but in testing a project today from a localhost Development (Ubuntu) to a live Production server (shared server, general market provider ala Bluehost) I'm getting a White Screen Of Death (WSOD) after importing the main filename.sql via phpmyadmin and I'm not sure why it's not working correctly.

Here's what I'm doing:

1) - copy via FTP all core and /sites/modules and my relevant dir contents.

2) - setup all Database with user/passwords including Admin as required.

3) - install generic Drupal v.7.2x onto server using Drupal /install.php

this then gets me a 'Standard' install but without all my data content but all accessable as per a generic standard Drupal install.

Next, back to phpmyAdmin, go to the relevant DB structure and chose 'Import', because I'm using a raw. sql I can just select the 22.5mg .sql file and wait, then I get the 'Success' message. I cannot use Backup & Migrate (M&G) Module due to the file limitation given my B&M.

After this point, I get a WSOD and cannot move forward.

The only thing I know that is different is that on my locahost Dev I used a simple 'Admin' name and a simple Password such as 'DeadEasy'. On the live Prod site, I changed this for better security to a name relevant to a SuperUser (ie AlphaBravoCharlie,(thats NOT real!!), Password: such as "DrG6%7DyE".

FYI, I did have some Fatal Errors yesterday based on Memory allocation, (I'm allowed 128meg max) but the example highlighted here is after I reduced module load to resolve the previous fatal error given.

Can anyone shed any light on what may have happened?

Notes #1:
I had thought it may have been that I hadn't uploaded my 'sites/all/themes', but it wasn't. #2 any other 'test' index.html work fine (as in temporarily disabling the index.php).

The first place to look would be the BlueHost Error Logs; their article at https://my.bluehost.com/cgi/help/562 describes where to find them within cPanel. If you're seeing failed calls to functions / modules that you know exist in your codebase, there's a strong probability that Drupal's registry is not current.

Drupal caches extension (module and theme) file locations within its registry. Given that you are importing an existing site database into a different structure, those locations are out-of-date.

If you haven't already, I suggest installing Drush (the DRUpal SHell) using the instructions at https://drupal.org/node/1181480

Then, clear the site cache:

drush cc all

If that does not clear it up, the next step is a registry rebuild. This forces Drupal to rescan executable file locations. Install the Drupal contrib project registry_rebuild using the instructions on the project homepage, then

drush rr

to rebuild the registry.


Access control for announcement users to view via link Is there a module available or anyone have a hint as to how one could create private links? I have a site that is locked down via access control, but I would like to send an announcement user a link to be able to view that piece of content.

Sort of like a Dropbox share. I can elaborate more on my use case if needed.

Try Node authorize link.

  Generates link for view, edit, or delete content without login.

  Module maintains authorization key for every node and gives additional
  grants (view/edit/delete) to every user (anonymous too) who accesses
  page with correct key in URL. Module offers function
  node_authlink_get_url($node, $op = 'view') for generate absolute URL
  to selected operation (e.g. for e-mail notifications).

Although the module is minimally maintained I used it two years ago and I did the work.

You can generate links that an anonymous user can use to get access to view a node, for example. I think it works with Conent Access, but not I'm not sure. May be you have to tweak precedence.


Create an Action on 'node_insert' or 'node_presave' I created a new action on a new node being created, it shows up in my triggers and the action gets triggered. Works so far. Problem is trying to add additional functionality using some submitted field values. As of now, all its doing is logging in Watchdog. My goal is to be able to set a flag on the node based on certain values.

------------------------------------------------------------------

/**
 *  Implementation of hook_action_info().
 */

function my_custom_action_info() {
  return array(
    'my_custom_action' => array(
  'type' => 'node',
  'bundles' => array('article'),
  'label' => t('Check article for stuff'),
  'configurable' => FALSE,
  'triggers' => array('node_insert'),
    ),
  );
}

function my_custom_action($node) {
    $myvar = $node->nid;
    my_custom($myvar);
}

function my_custom($myvar) {
    watchdog('Test', 'My Custom Variable: ' . $myvar);
}

--------------------------------------------------------------------------

If I set the variable to an integer or text, it works.
But how to get any value from the submitted node?
Eventually I'd like to get a value from a specific field, but for now just testing with the Node ID and can't seem to get it.

The error I'm getting is :
"Notice: Trying to get property of non-object in my_custom_action() ... "

This part: $myvar = $node->nid;

yeah,

for some reason, my variable needed to be initiated first.

$myvar = 0;
$myvar = $node->nid;

that's it. works now.
Problem/solution applies for Drupal 6 or 7.


How to fix the variable names in a simplenews subscription confirmation mail? I have a Simplenews subscription block for the anonymous users of my site. When they enter their name and email address and hit subscribe, a mail is sent to their email ID for confirmation. It is a single confirmation email.

When i see the mail it displays the variable names that i am using.
For eg :

  1) The subject of the mail is Confirmation for !newsletter_name.
  2) please use the link below, then click "Subscribe" on the web page that
  will open: !confirm_subscribe_url

How can it be fixed?

I am guessing you upgraded from D6. The tokens you are using are D6 tokens.

Go to /admin/config/services/simplenews/settings/subscription and change the tokens. For instance, the default subject for D7 is :

Confirmation for [simplenews-category:name] from [site:name]

Note the new (D7) token format. You can find he new tokens by expanding 'Replacement patterns'.


How do I load CSS files to a custom theme? I understand this question has been asked many times. However, I still can't figure out why the CSS files of my custom Drupal 8 theme are not loading.

Edited (more info): The CSS files are not being defined at all (they do not show up in the HTML).

Here is my test.info.yml file:

name: "test"
type: theme
description: "Theme by ..."
package: custom
core: 8.x

libraries:
  - test/global-styling
  - test/global-scripts

regions:
  headline: Headline
  header: Header
  content_special: 'Content special'
  content: Content
  sidebar: Sidebar
  footer: Footer

And here is my test.libraries.yml file

global-styling:
  version: 1.0
  css:
    theme:
      css/bootstrap-4.0.0.css: {}
      css/content.css: {}
      css/footer.css: {}
      css/header.css: {}
      css/IE.css: {}
      css/lista.css: {}
      css/navigation.css: {}
      css/style.css: {}
      css/taulukko.css: {}

global-scripts:
  version: 1.0
  js:
    js/scripts.js: {}
  dependencies:
    - core/jquery

Note: The CSS files are not being defined at all (they do not show up in the HTML). So the console is not showing any errors about this issue. The css files are accessible if you manually type the path in the browser window.

After trying alot of different things I found the problem in page.html.twig file. Had misspelled one region name (a "-" instead of a "_"). Fixing the misspelled region name just got the CSS working.

Thank you all that helped me by commenting on the question.


Views and Fields help I have product images that I want to appear in a view. Easy enough.  At the same time I have 6 different product types.  So what I'm trying to do is create a view that is 6 columns across.  Each column is a different product type.  Then each product will fall into 1 of 6 categories.  Some columns will have 4 items, some 7. I cannot seem to do this with the "Grid" layout.  Which seems the best way to do this.  Any suggestions?

What I would do is add a taxonomy with 6 "product-types" terms, then add a term reference field in contentype, make "6 content pane views" displaying your contentype and filtering on term reference, and with panels module (or display suite) do a 6 column display with all fields that you require, each view will have it's own column, and you are done.


How to resend same newsletter from Simplenews? I'm using simplenews module in Drupal 7. Also I have working mailing system as well as Cron system. I want to resend the newsletter that has been sent previously. I don't want to edit the database every time for resending. I want to send newsletter using user interface itself.

I tried editing simplenews.module and simplenews.admin.inc files.

I edited simplenews.module

/**
* NEWSLETTER SENT STATUS
*/
define('SIMPLENEWS_STATUS_SEND_NOT', 0);
define('SIMPLENEWS_STATUS_SEND_PENDING', 1);
define('SIMPLENEWS_STATUS_SEND_READY', 0);
define('SIMPLENEWS_STATUS_SEND_PUBLISH', 3);

But as I edited for SIMPLENEWS_STATUS_SEND_READY, it started giving me notice in the admin panel stating:

  Notice: Undefined offset: 2 theme_simplenews_status() (/home/#####/public_html/#######/sites/all/modules/simplenews/includes/simplenews.admin.inc file row number　1776 ).

But I couldn't edit simplenews.admin.inc file. And in the newsletter sending option it shows following message but don't send message when I run Cron:

  This newsletter is pending

Please help if someone has faced the same issue.

Perhaps easier to clone and then resend the newsletter node with the node_clone module.

The clone module allows users to make a copy of an existing item of site content (a node) and then edit that copy.


How can I add a custom attribute to a link field? For analytics/tracking purposes, I would like to add a custom attribute to a link field. Is there a way to add an additional text field to the link, similar to the title attribute field?

On Drupal 7 there are several ways to go about this depending on your setup.

If you are using Display Suite you can add custom attributes to the link field (and all the various wrappers) by setting the field template to Expert:

You could also use template_preprocess_field() in a module or your theme to add additional attributes to the link before it is rendered.

Display Suite is more limiting but often easier (particullarly if it is already in use). Since the preprocess function is in PHP it will give you more flexibility that may or may not be useful.


How to export and import from View in Drupal7? i have a view in my project. And i want to import and export the views in Excel format. How to achieve this?

You can use views data export module.

  This module is designed to provide a way to export large amounts of
  data from views. It provides a display plugin that can rendered
  progressively in a batch. Style plugins are included that support
  exporting in the following types:

CSV
Microsoft XLS
Microsoft DOC
Basic TXT
XML.


how to remove element from node__product__type.tpl.php commerce kickstart In my website with commerce kickstart, I would like to remove div with its class name "field_label" in node__product__type.tpl.php. I have no idea of how to code to remove it. Any suggestion is greatly appreciate.

html

    tshirt size:

node__product__type.tpl.php

<article<?php print $attributes; ?>>
<?php print "testing product testing" ?>
<?php print $user_picture; ?>
<?php print render($title_prefix); ?>
<?php if (!$page && $title): ?>

     <h2<?php print $title_attributes; ?>><a href="<?php print $node_url ?>" title="<?php print $title ?>"><?php print $title ?>

<?php endif; ?>
<?php print render($title_suffix); ?>
<?php if ($display_submitted): ?>
<?php print $date; ?> -- <?php print $name; ?>
  <?php endif; ?>

   <?php print render($content['product:field_images']); ?>

   <div<?php print $content_attributes; ?>>
     <?php
      // We hide the comments and links now so that we can render them later.
       hide($content['comments']);
       hide($content['links']);
       print render($content);
    ?>

    <?php if (!empty($content['links'])): ?>
    <?php print render($content['links']);?>
  <?php endif; ?>
    <?php
      print render($content['comments']);
    ?>

If you want to remove both the class and the label, 'tshirt size:', you don't have to do it via code. You can use the "Display settings" of the product and make the label hidden. ie, Go to content type -> Manage Display -> Node and select hidden for the size label.


Display Field Collection items as select list in other content type I have 2 content types, lets say A and B. There is field collection item in content type A (in which unlimited values could be added). User adds data in this field as he creates new content.
I want all those field collection options filled by user in A to appear as a select list while submitting content type B.
I create an entity reference field in content type B and tried to display all options of field collection item from A. It shows perfectly as I tested it in view.
Issue:

If I select to display all values in a single row, it shows all options in one row of select list.
I actually want to display each option in separate row, but it shows only the last item.

Anyone knows the solution?
Here are Settings of my View:

And this is my Field Setting:

As you can see, in View it shows both option. But in select list it shows only last option or all options in single row (by changing setting).

This is a partial answer, looking for further guidance!

After a lot of exploration, I still couldn't find exact solution to my question.

While searching I found this topic titled: Entity Reference view to populate select list for reference field => only one result when using a contextual filter, might help others. This is a long node addressing similar problem.

But my problem was not solved by above mentioned link. So I used hook_form_alter,

function module_form_alter(&$form, &$form_state, $form_id){
    if($form_id == 'your_form_id'){
        $url_arg=arg(); //get arguments from URL
        $node_id=$url_arg[1];
        $node=node_load($node_id); //load appropriate node of Content type A
        $info = field_info_field('field_testing_code'); //load field from Content Type B's form
        $values = &$info['settings']['allowed_values']; //get list of allowed values
        $values= array(); //remove all existing values
        $i=0;
        while($node->field_consignment_text_field[und][$i][value]){
            $values[$node->field_consignment_text_field[und][$i][value]] = $node->field_consignment_text_field[und][$i][value];
            $i++;
        }
    field_update_field($info);
  }
}

As I mentioned, each B content type is a sub part of A content type. And URL contains id of A. When I open content type B's creation form one at a time, it works fine. When I open more that one forms having different A parent, form_alter shuffles data e.g Field data of tab 1 gets assigned to tab 2.This is the issue now.
Looking for some solution for this.


How can I capture JavaScript value for use on tpl.php I have a custom module, in a javascript file that is located in the js folder of the module, I captured a value from a previously written function using an if statement. Ex: if($numb==6) show this img else show this img.

I need to access this value/var so I can display a particular image on my tpl.php when it loads.

How can I accomplish this in drupal7?

What you can do in this particular case is add the HTML for both the images inside tpl file.
On the js file, you can display/hide the images according to your IF condition.

To capture JS value for use in tpl, you can use javascript/ajax to send the information through a url / xmlhttp and then use hook menu to grab the information inside module file, then send the variable to the tpl


How can I use rules to grab fields from one content type to another then delete the old nodes? I have an D7 site using feeds that create dozens of nodes daily populated with RSS articles. I use the body fields from these articles as well so I can read them on-site without clicking to the actual publisher. Means my database is getting bigger. Here's what I want to do:

Any node over 4 weeks old of 'feed' type needs to create a new node called 'feed archive' and do this by using the old title and just the article URL - no other fields need to be transferred. Then the old node can be deleted. So I basically dump all the body content and other fields attached to the old 'feed' node and just leave the title and URL and create a new node with these two things.

I have created a rule using VBO views before so kind of understand that, but don't know how I say: 'create a new node, only grab these two fields from it, then delete it'

Any help greatly appreciated.

In your rule, i think your can write a custom php code:

  //$node is your original node

  $node_new = new stdClass();
  $node_new->type = 'content_type_2';
  $node_new->status = 1;
  $node_new->uid = $node->uid;
  $node_new->title = $node->title;
  $node_new->promote = 0;
  $node_new->created = $node->created;
  $node_new->timestamp = $node->timestamp;
  $node_new->field_article_url = $node->field_article_url;

  node_save( $node_new );
  node_delete( $node );


Create a view block that shows list of nodes that references same node as current node I have two content types. "Article" and "Collection". Any article can be placed into collection. Also when you create collection, you can select articles to be placed into collection. So I have created "collection" as node reference field in "Article" content type, and "article" as node reference field in "Collection" datatype.

Now when I am on any article page, I want to create view that shows other articles from the same collection. I have tried adding "collection" as relationship and contextual filter as "NId" with relationship with "collection", but it is listing all articles that is having any collection(may reference to other collection) and not the articles that belongs to collection of current article.

Am I doing something wrong?

Please suggest.

-- Thanks for your time.

Let us assume the the filed in collection that referes to article is field_entity_article

Then you would do the following.

With in your view first you would add a relationship called Entity Reference: Referenced Entity (A bridge to the Content entity that is referenced via field_entity_article)
The you would add another relationship Entity Reference: Referenced Entity (A bridge to the Content entity that is referenced via field_node_article) While you are here select the previous relationship you created from the dropdown Relationship
Add a contextual filter of the type content: nid and provide default argument and select node id from url form the dropdown.
Add the required field and give the second relationship we created for this.

That should do it.


Is there any way to add the css class to tinymce inside wysiwyg editor I have several classes defined inside style.css, I want tinymce to recognize these classes. Below is the popup to configure hyperlinks. It also provide a way to use css styles defined already.

I am looking for a way to add the css class to tinymce inside wysiwyg editor in Drupal 7.

As you are using wysiwyg module with tinymce library. You should implement the alter function provided by wysiwyg module to add the editor settings.

For tinymce 4.x:

function MYMODULE_wysiwyg_editor_settings_alter(&$settings, $context) {
  if ($context['profile']->editor == 'tinymce') {
    $settings['link_class_list'] = array(
      "Class Example" => "class-example",
    );
  }
}

For tinymce 3.x:

function MYMODULE_wysiwyg_editor_settings_alter(&$settings, $context) {
  if ($context['profile']->editor == 'tinymce') {
    $settings['theme_advanced_styles'] = array(
      "Class Example" => "class-example",
    );
  }
}

References

documentation of tinymce 4.x
documentation of tinymce 3.x
API of wysiwyg


Cannot send drupal_http_request authorization header I'm trying to post a request using drupal_http_request, but my headers are causing authorization errors.

This is my request:

$headers =  array('Authorization'=>'Bearer [my token here]', 'Content-Type'=>'application/json' );
$url = "https://api.ionic.io/push/notifications";
$message= new stdClass();
$message->message='That works';
$message->title='titleofmessage';
$data = array('tokens' => array('DEV-f765ac70-1bcb-4e0f-8bfd-adfd9612f185'), 'profile'=>'fake_push_profile', 'notification'=>$message);
$result=drupal_http_request($url, $headers, 'POST', json_encode($data));

In cURL it works fine, but I want to use drupal_http_request:

curl -X POST -H "Content-Type: application/json" -H "Authorization: Bearer [my token here]" -d '{"tokens": ["DEV-f765ac70-1bcb-4e0f-8bfd-adfd9612f185"],"profile": "fake_push_profile","notification": {"message": "That works", "title": "titleofmessage"}}' "https://api.ionic.io/push/notifications"

The error message I get is 'Authorization header is missing' so something seems to be happening to that header.

Any help much appreciated!

You have the second param to drupal_http_request wrong; it should be an array of options, not an array of headers. Headers is just one of those options.

To fix:

$result = drupal_http_request($url, array('headers' => $headers), 'POST', json_encode($data));


Where do I programmatically create new roles? I want to programmatically create new roles in Drupal 8. I found this code in this post.

//your data array
$data = array('id' => 'client', 'label' => 'Client');
//creating your role
$role = \Drupal\user\Entity\Role::create($data);
//saving your role
$role->save();

But I don't know where I should put it, in which file, which folder? And how do I run it?

You have many place to create your roles, a simple way for you (As you says that you don't know nothing about Drupal) can be create a custom page (read the post) if you follow the example in the myPage() function you can go trough your list of roles and create each role in a loop, something like this;

public function myPage() {
...
  /* Read your roles
   * $my_roles[0]['id'] = 'client';
   * $my_roles[0]['label'] = 'My Client';
   */
  for ($i = 0; $i < count($my_roles); $i++) {
    //your data array
    $data = array('id' => $my_roles[$i]['id'], 'label' => $my_roles[$i]['label']);
    //creating your role
    $role = \Drupal\user\Entity\Role::create($data);
    //saving your role
    $role->save();
  }
...
}

And if you go to your page you will create your roles.

EDIT: As Kevin says is better in other places like the hook_install()

Follow the steps to create a module and implement the hook_install() (Read at the end of the page how to do it)

Inside the hook implementation you will put the code:

/**
 * Implements hook_install().
 */
function YOUR_MODULE_install() {
    /* Read your roles
     * $my_roles[0]['id'] = 'client';
     * $my_roles[0]['label'] = 'My Client';
     */
    for ($i = 0; $i < count($my_roles); $i++) {
      //your data array
      $data = array('id' => $my_roles[$i]['id'], 'label' => $my_roles[$i]['label']);
      //creating your role
      $role = \Drupal\user\Entity\Role::create($data);
      //saving your role
      $role->save();
    }
}

To create your roles you only need install your module.


How to open quicktab tab from external page (after clicking link url) i have a slider with link field at my front page, and quicktab section on another page. The slides and the quicktabs are connected, so i want when i click on the link at the slider to open the specific tab. The quick tabs in my case use class active for the clicked section to show. How can i make the tab active externally with click on the link at the slider?

Thanks in advance!

right click with mouse on the Quicktab in question, and copy url. Then use that url on your slider.


What is Calendar Legend block for? enabled but shows nothing Playing around with Calendar + Date.

There is a block called Calendar Legend, but shows nothing. What is it for? Where should I configure?, I checked the block configuration and views setup, no clues.

Thanks.

The Legend is used on the large calendar page view to help denote between content types or taxonomy. You can set the colours of the content types or taxonomy by editing the view at /admin/structure/views/view/calendar/edit and select Format > Show > Settings


Additional Query String in a Node Url I'm not sure if this is possible in drupal 7, but I think I may have seen something like this happen before.  Let's say i added a content and you can see it at the url http://mysite.com/my-article.  In the content area, I'm displaying a block that's made by a custom module.  Right now, I have no problems going to a url like http://mysite.com/my-article?var1=hello, and then having my module responsible for creating the block to print $_GET['var1'].

However, the only change I would like to make is to have friendly urls.  I would prefer the url to be http://mysite.com/my-article/hello, then I would output the same content in my module block.   Is this easily do-able?

All is right what you are doing.

You cannot pass additional parts randomly with URL without adding them to menu registry and associating with callback.

Drupal uses $_GET['q'] for default URL path and makes it SEO friendly. $_GET['q'] can contain 9 parts in total in Drupal 7 (7 parts in Drupal 6). Each part can be accessed via arg(n) function.


How can I encrypt the username and email address in the database, to protect against emails being stolen from a compromised database (D7) Is there a way to encrypt the following user fields in the database so that they cannot be retrieved from a compromised database?

Username
Email address

A solution to encrypt the whole database would also be great.

If you want encrypt it, it means you need to decrypt it. So it means that the algorithm that encrypt and decrypt are available somewhere in your application or drupal files.

I guess if the user that has access to your database he has also access to your files, or at least I guess he can have access easily.

And in that case, encrypted datas are useless.

The most important its to hash the password with algorithms like SHA1 and use a salt or private key, thing that Drupal 7 is doing.

This is just my point of view, but if you want do it what you can use this module http://drupal.org/project/aes and with some user hooks, such as hook_user_presave() and hook_user_load().

The trick in this case it's that your module should be the last one before saving save the data and be the first one that decrypt data.


Add Unique ID to Menu Item Is it possible to add a unique id or class to each li element in a menu, perhaps using a preprocess function? I want to be able to target each menu item individually with CSS.

I could probably use css rules like li:nth-child(1) etc, but I would rather add a unique ID or class to the element.

I use this module https://www.drupal.org/project/link_attributes

It allows you to add classes/ids to menu items by editing them through Drupal's core menu admin screens


D8 | submitForm | Get the $_POST - vars via $form_state or via \Drupal::request()? On an regular sumbmitForm function, should I fetch the user input via \Drupal::request()->request->get... or is $form_state->getValues(); the better (more saver) way?

thx

$request->request->all() != $form_state->getValues()

$request->request->all() === $_POST
$request->query->all() === $_GET

See in Drupal\Core\Form\FormBuilder::buildForm()

$input = $form_state->isMethodType('get') ? $request->query->all() : $request->request->all();
$form_state->setUserInput($input);

$form_state->getValues()  is already modified data that is formed on the basis of $form_state['input'] and #default_value

See in Drupal\Core\Form\FormBuilder::handleInputElement();

Pay attention to #value_callback it forms the value of the field


Increasing width of Views 3 search form filter I am trying to increase the size of my views search filter form. The form id is views-exposed-form-blog--user-s-tab--page and am trying to use this in code I've used for my search block but its not working.

Here's my search block code -

function Themename_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'search_block_form') {
    $form['search_block_form']['#size'] = 26;
  }
}

Any ideas how I can make this work?

Thanks in advance

Perhaps you can get away with a simple CSS rule in your theme's stylesheet? Something like this:

#views-exposed-form-blog--user-s-tab--page input{width: 200px;}

That width can be anything. In this example, it'd be 200pixels wide.


Detecting user site visits I some working code in hook_user_login() that awards 5 points to users for each day they log into the site.  If they log in twice in one day, points are not awarded the second time.

Originally, I thought users would login each time they visit the site but since users stay logged in between visits, they are not getting points for visiting once per day.  For example, if they log in today, they get 5 points but tomorrow and each day they visit thereafter, they don't receive any.

I would like users to be awarded for each day they visit the site whether they need to log in or not.  I wasn't able to find another hook that could do it.  Does anyone know of one or some other method of tracking user visits?

You could store the last updated timestamp in the session on login, and then check it on each page load to see if it's within your parameters:

function MYMODULE_init() {
  // Only proceed if there's a timestamp in the session. Otherwise defer to
  // hook_user_login() to take care of setting that.
  if (user_is_logged_in() && isset($_SESSION['MYMODULE_point_check_timestamp']) {
    // If the timestamp is more than 24 hours ago, award more points.
    if (REQUEST_TIME - $_SESSION['MYMODULE_point_check_timestamp'] > (60 * 60 * 24)) {
      award_points();
    }
  }
}

function MYMODULE_user_login(&$edit, $account) {
  award_points();

  // Track the time points were awarded.
  $_SESSION['MYMODULE_point_check_timestamp'] = REQUEST_TIME;
}

function MYMODULE_user_logout($account) {
  // Clean up.
  if (isset($_SESSION['MYMODULE_point_check_timestamp'])) {
    unset($_SESSION['MYMODULE_point_check_timestamp']);
  }
}


module_invoke/module_invoke_all with multiple arguments I know enough D7 to be dangerous. I'm stumped, however, as to how to call one module from another. In this case, I want to call the simplenews module's subscribe_user hook from a custom module I'm creating. I'm having difficulty passing the multiple arguments either as a string or an array. Here are the variables the hook accepts:

$mail = 'test@test.com';
$tid = 1;
$confirm = TRUE;
$source = 'unknown';
$preferred_language = NULL;

Can someone please help me call this properly?

module_invoke('simplenews', 'subscribe_user', $args);

use

simplenews_subscribe_user($mail, $tid, $confirm, $source, $preferred_language);

or

module_invoke('simplenews', 'subscribe_user', $mail, $tid, $confirm, $source, $preferred_language);

module invoke is parsing all given arguements and handles them to the called function.

see php documentation regarding passing variables by reference, if that might bug you someday: http://php.net/manual/en/function.call-user-func-array.php#refsect1-function.call-user-func-array-notes


Post form to external URL I need to POST the data in a form to an external URL.

In Drupal 7, you would use

$form['#action'] = url('http://example.com', array('external' => true));

Or maybe this was for GET. Anyway... in Drupal 8, this does not work. I have tried editing the submitForm method:

public function submitForm(array &$form, FormStateInterface $form_state) {
    $response = new TrustedRedirectResponse('http://example.com');
    $response->send();
}

This works, however I have not found a way to submit the values of the form along with the request. I looked at the httpClient class, but it seems that is for sending/requesting data only and does not redirect the user.

Hope someone can help me out. If it comes down to it I am fine with using GET instead.

$form['#action'] works the same, Drupal 7 or Drupal 8. It needs a string, which is what url() returns in Drupal 7. The reason why url() is normally used is because the code has a relative path for a routing item, such as in url('comment/reply/'. $edit['nid']).

In Drupal 8, for example, the Comment module uses the following code.

$form['#action'] = $this->url('comment.reply', array('entity_type' => $entity->getEntityTypeId(), 'entity' => $entity->id(), 'field_name' => $field_name));

UrlGeneratorTrait::url(), the method called in that code, still returns a string, not an object. Also in this case, UrlGeneratorTrait::url() is used because the code has a route name (comment.reply) and it wants to get the URL for that route.

The following code works for Drupal 7 and Drupal 8.

$form['#action'] = 'http://example.com';


Changing automatic URL alias I am populating a new site with my old site's content (i.e copying it) and wanted to make sure all the URLs will be the same. At the momement my old path is name.com/work/sony-folklore and and the new one is: name.building-site.com/content/sony.

NOTE: name.com and name.building-site.com are dummy names that refer to the live and the development version of the site.

What can I change to make the CMS generate the same URLs as they did in the old site?

Thanks

You can set the alias by editing a content. See the screenshot below to edit url alias.


Create custom template for blog How do I go about overriding the default template for content of the blog page (the index page that shows the blog teasers)?

Also I would like the original template code for this content so that I can rewrite my content effectively, is the .tpl.php somewhere within drupal core, that I could copy out into my theme?

Thanks for your time!

I don't think there is separate file for Blog content type. Because for Blog default node.tpl.php is called. If you want to create tpl file for blog, straight away copy file from node.tpl.php and create a tpl like node--blog.tpl.php.

And if you want to create page tpl for blog content type then you can create

page--blog.tpl.php

And you have to add some PHP code in template.php file in THEMENAME_preprocess_page() function

if( !empty($vars['node'])){
    $vars['theme_hook_suggestions'][] = 'page__'. $vars['node']->type;
  }


How can authors choose a different display name? I am looking to add to the create user feature to allow or display a drop down and or a text field that would allow the user to create a custom display name to associate with the post he or she would be creating.

While this doesn't allow for someone to choose their name per post, it does allow for someone to have a username and a "realname" http://drupal.org/project/realname

You could also just add a text field to nodes where they can fill out any name they want. Then plug that field into your theme instead of the username.


Is there a way to restrict access to a calendar page excepting the owner of the content? I'm pretty new to drupal and I hope to get the solution here. Goes like this: I have a content type named "property" and a calendar attached to each node of this content type. In the permissions section the calendar has "Access bookable item's calendar" which controls who has access to the calendar pages. One of the roles "propertyadmin" has this permission set. Now comes the problem - All users having that role has the same permission and can edit all other calendar pages. I think the problem is here in the calendar module because it doesn't have any conditional logic to check whether the user accessing the calendar is the owner of the referenced node.

Can anyone help? Here is the code:

`  function property_calendar_menu() {
  $items = array();

  $items['admin/property/items/%property_item/calendar'] = array(
    'title' => t('Calendar'),
    'page callback' => 'drupal_get_form',
    'page arguments' => array('property_calendar_admin_form', 3, 5, 6),
    'access arguments' => array('access property_item calendar'),
    'type' => MENU_LOCAL_TASK,
    'context' => MENU_CONTEXT_PAGE | MENU_CONTEXT_INLINE,
    'file' => 'includes/property_calendar.admin.inc',
  );

  $items['node/%node/calendar'] = array(
    'title' => t('Calendar'),
    'page callback' => 'property_calendar_overview',
    'page arguments' => array(1, 3, 4),
    'access callback' => 'property_calendar_overview_access',
    'access arguments' => array(1),
    'type' => MENU_LOCAL_TASK,
    'weight' => 4,
    'context' => MENU_CONTEXT_PAGE | MENU_CONTEXT_INLINE,
    'file' => 'includes/property_calendar.admin.inc',
  );

$items['custom_calendar/ajax'] = array(
    'title' => 'AHAH callback',
    'page callback' => 'custom_calendar_status_ajax',
    'page arguments' => array(2, 3, 4),
    'delivery callback' => 'ajax_deliver',
    'access callback' => TRUE,
    'theme callback' => 'ajax_base_page_theme',
    'type' => MENU_CALLBACK,
  );

  return $items;
}

/**
 * Access callback for overview form.
 */
function custom_calendar_overview_access($node) {
  // Foreach field.
  foreach (field_info_fields() as $field) {
    // If field is entityreference, targets a property_item
    // and it belongs to a node.
    if ($field['type'] == 'entityreference' and $field['settings']['target_type'] == 'property_item' and isset($field['bundles']['node'])) {
      // If current node's type has this field.
      if (in_array($node->type, $field['bundles']['node'])) {
        return user_access('access property_item calendar');
      }
    }
  }

  return FALSE;
}
`

$items['node/%node/calendar'] = array( ...

'access callback' => 'node_access',
'access arguments' => array('update', 1),

I manage to solve this part. I still need help for the first URL


Modify article body for one particular article to add data How do I modify an article's body field before the end user sees it for one particular article?

Background: Currently the content editors are updating this data manually twice per week. We want to automatically update it every 8 hours with a cron job instead. We will get data from an external source, it comes to us in JSON format. We process the data into a render array.

When I'm ready to see some output on the page, how do I put it there?

I ended up modifying the node when cron runs.

define("JMT_CLASSES_CLASSES_ED_NODE_ID", 574);
// 60 * 60 * 8 - measured in seconds.
define("JMT_CLASSES_EIGHT_HOURS", 28800);

/**
 * Implements hook_cron().
 */
function jmt_classes_cron() {
  // Check current config for time, if greater than 8hrs check for updates.
  $timeOfLastUpdate = \Drupal::configFactory()
    ->get('jmt_classes.settings')
    ->get('last_run');
  $currentTime = \Drupal::time()
    ->getCurrentTime();
  $intervalSinceLastUpdate = $currentTime - $timeOfLastUpdate;

  if ($intervalSinceLastUpdate >= JMT_CLASSES_EIGHT_HOURS || $timeOfLastUpdate == NULL) {
    // Check for updates.
    $raw = jmt_classes_get_classes('https://example.com/Client.WebApi/api/Route?url=query/get?url=jmt');
    if ($raw) {
      $newBodyValueHtml = jmt_classes_render_html($raw);
      $classesEdNode = Node::load(JMT_CLASSES_CLASSES_ED_NODE_ID);
      jmt_classes_update_class_node($classesEdNode, $newBodyValueHtml);

      \Drupal::configFactory()->getEditable('jmt_classes.settings')
        ->set('last_run', $currentTime)
        ->save();
    }
  }
}

/**
 * Update node with new html for the body field and log that it was updated.
 *
 * @param string $node
 *   The node (output page) that should be updated with new data.
 * @param string $newBodyValueHtml
 *   The HTML to set the body to.
 */
function jmt_classes_update_class_node($node, $newBodyValueHtml) {
  $node->body->value = $newBodyValueHtml;
  $node->save();
  \Drupal::logger('jmt_classes')->notice("Successfully updated body field of articles/upcoming-education-classes-field-days");
}

/**
 * Get raw json output for JMT classes. Log error or success.
 *
 * @param string $uri
 *   JMT api uri: should be something like:
 *   'https://example.com/Client.WebApi/api/Route?url=query/get?url=jmt'.
 *
 * @return string
 *   Raw json data or empty if nothing returned from request.
 *
 * @throws \GuzzleHttp\Exception\GuzzleException
 */
function jmt_classes_get_classes($uri) {

  try {
    $response = \Drupal::httpClient()->request('GET', $uri, ['timeout' => 120]);
  }
  catch (Exception $e) {
    \Drupal::logger('jmt_classes')->error("Attempted to get data
from $uri but failed. $php_errormsg");
    return '';
  }

  $data = (string) $response->getBody();
  $data_array = json_decode($data);

  // If this isn't json data return nothing.
  if (empty($data_array)) {
    return '';
  }
  // Otherwise, return raw json data.
  else {
    \Drupal::logger('jmt_classes')->notice("Successfully got data from $uri");
    return $data;
  }
}

This has the advantage that I don't do any preprocessing. The change happens when the data changes when cron runs, not on every page load. This is important because fetching the data is SLOW!


How can I refer to a table to make a level system? I'm working on a RPG website. Users are awarded userpoints (named XP for the need of the "game") depending on their actions.

I want to make a level system based on these userpoints. I already made a table using Drupal Data, which stores values for each level (level number, minimum XP, maximum XP, and some ratios to apply when a user is earning points).

My question is : How can I refer to this table to check a user level (and all the values attached) depending on the user's amount of XP?

I tried with Rules, but no success.

Give it some thought to replace that table you made with:

a new content type (eg called "XP") and
with custom fields as in your question, such as:

level number.
minimum XP.
maximum XP.
some ratios.

That way you could create 1 node for each row in your table, with field values matching the values in those table rows. If appropriate, use the Feeds module to automatically create 1 node for each row in your table.

After you'd have created such nodes, you could use them in combination with the modules you're already using / considering, such as User Points and Rules.

To implement that "level system" (as in your question), you can probably use the Goals module (disclosure: I'm the maintainer of it). If you're not familar with this module, have a look at "How to implement gamification in a Drupal site and award incentives?".

Bonus tip: since you're thinking of using User Points and Rules already, you may also want to look at the answer to "How to access current amount of earned userpoints in a Rules Condition?" (pretty sure you'll need something like that also).

PS: All this only requires site builder skills (no need for any custom coding).


Programmatically add node translation drupal 7 ( Entity translation ) I need to create multilingual node programmatically in Drupal with entity_translation.

No problem to create the node, but I have no idea how can I create the translation ( + field translated).

I don't want to create another node, just translate it (same nid).

My language is FR , I need translation in EN and DE.

Found the answer ! Thanks to my co worker.

In order to add translation to a node you need to add every translatable field like this in your creation node code :

 $node->field_trailer['fr'][0]['value'] = $movie['link'];
 $node->field_trailer['de'][0]['value'] = $movie['link'];
 $node->field_trailer['en'][0]['value'] = $movie['link'];

And after node_save($node); add

  node->translations->data['de']['entity_type'] = 'node';
  $node->translations->data['de']['entity_id'] = $node->nid;
  $node->translations->data['de']['language'] = 'de';
  $node->translations->data['de']['source'] = 'fr';
  $node->translations->data['de']['uid'] = $node->uid;
  $node->translations->data['de']['status'] = $node->status;
  $node->translations->data['de']['translate'] = 0;
  $node->translations->data['de']['created'] = $node->created;
  $node->translations->data['de']['changed'] = $node->changed;

For each language and the node_save($node) again.


Cannot load module uninstall page - says module does not exist I accidentally deleted the Markdown filter module from the file system while it was still enabled. So I installed it again, via the GUI.

Now I cannot load the module uninstall page - it says "The website encountered an unexpected error. Please try again later", and the message in the log says Drupal\Component\Plugin\Exception\PluginNotFoundException: The "markdown" plugin does not exist. in Drupal\Core\Plugin\DefaultPluginManager->doGetDefinition()

I have cleared caches, run cron, deleted sites/default/files/php ... all to no avail.

Any ideas?

Edit: I have just tried to enable the module again, and got this message: Unable to install Markdown filter, markdown.settings already exists in active configuration. I looked through the config and cache_config tables and cannot find this setting.

It turned out there was a markdown.settings entry in the database (in the config or cache_config table, I forget which). I deleted this row and then it was possible to install and then uninstall the module.


Add a custom id in textarea I need to add an ID into a textarea of body field on my custom "node-form.tpl.php". Now this body field will be rendered like this:

<textarea class="text-full form-textarea" id="edit-body-und-0-value" name="body[und][0][value]" cols="60" rows="20"></textarea>

I want to add a ID redHat into the texarea, that output should be:

<textarea class="text-full form-textarea" id="edit-body-und-0-value redHat" name="body[und][0][value]" cols="60" rows="20"></textarea>

To do this i have used hook_form_alter() in my template.php with no luck!

function bartik_form_alter( &$form, &$form_state, $form_id ) {
if($form_id == "article_node_form"){
    $form['body']['und']['0']['value']['#attributes']['#id'][] = 'redHat';
}
}

what i am missing? Thanks

Each element should have only one ID and it should be unique. You can change the body texarea id with the hook_form_alter()

Example

/**
* Implements hook_form_alter().
*/
function YOURMODULE_form_alter(&$form, &$form_state, $form_id) {

  if (isset($form['#node']) && $form['#node']->type == 'article') {
    // body textarea ID
    $form['body']['und']['0']['#attributes']['id'] = 'redHat';
  }
}

but you cannot add the next one.


Starting a site from scratch after running "drush sql-drop" In drupal 7 I was able to just do a drush sql-drop and then visit the site and it would throw the install screen. But in Drupal 8 I'm getting an error when I do a drush sql-drop when going back to the site. Are there static files I need to also delete in Drupal 8 along with doing a sql-drop?

It looks like your settings.php file is still persisting after the command. Removing it should prompt you for installation on root request.

# Replace with location of settings.php file
settings_file=sites/default/settings.php
drush -y sql-drop && rm "$settings_file"


Why is #field_parents empty in nested, multi-step form? I'm using Webform, Fieldgroup and Multistep with D7.

Ultimately I'd like to create a hierarchically-grouped list of all the submitted values and display on the last step of the multi-step form, with the following format:

Page 1

Question 1 Label

Question 1 Response

Question 2 Label

Question 2 Response

Question 3 Label

Question 3 Response

Page 2

Question 4 Label

Question 4 Response

Question 5 Label

Question 5 Response

Question 6 Label

Question 6 Response

When I inspect the $form object, however, I see the fields each listed, but $form['field_my_question']['und'][0]['#field_parents'] is an empty array.

How can I identify from the $form object which fields belong on which page of my multistep form?

I don't know what exactly #field_parents is for, but the information about field grouping is in $form (which, it turns out, is an array, not an object) several times over, in $form['#groups'], $form['#fieldgroups'], and $form['#group-children'].


cannot see tabs for manage fields etc with administrative toolbars add content bar This must be something new because never seen it before now. There is a grey bar with the add content find content and edit shortcuts links on it which completely obscure the tabs for manage field etc in content types.

How can I keep the administration toolbar but remove that grey bar? AND WHY would anyone want it placed in such a way as to block out important regularly used tabs?

It's an incompatibility between administration toolbar and your theme, and maybe overlay if you are using it. No one placed it like that on purpose, it's just a clash between 3 sets of CSS each written without knowing how other will look.

You can try one or many of the following:

Use Administration menu instead of toolbar.
Use Shiny as admin theme
Toggle overlay - if it's on, maybe without it it'll be OK? If it's off, maybe it'll help?
Create a subtheme and deliver CSS that will position stuff the way it should be for your particular case. Firebug or Chrome are good for fast prototyping your fix.


Transforming system link into a button I have created a "button" class in my style.css file.

I can easily create a button by assigning the "button" class to it. I can do this when I write the html code in, say, a block that I place wherever on the page.

But how do I transform an existing link (like one automatically created by a module) into a button?

Do I need to hack the module?

Any help on this riddle would be greatly appreciated.

Thanks.

:)

I definitely don't recommend hacking the module - it's not good Drupal form, and it limits your ability to get module updates in the future.

I think the answer depends on how the module creates the link in question. That is, how is the link HTML being generated? If it's being generated and printed directly to the screen, then you'd have to do some CSS/JS work to intercept the HTML being generated and alter it. We have done this when necessary on our site to bend certain modules and functionality to suit our display needs. If the link has a specific ID, just alter it with JS in a custom module or custom theme. If not, you may have to get at it via jQuery based on what elements it's contained within, but it can be done.

If you're lucky and the module is well-written, the link will be part of content that's passed through Drupal's theming engine first through a theme() call. In this case, you can write your own function to grab anything being themed, inspect it for whatever markers indicate that it should become a button, and then alter the link code as need be. If you're not familiar with the theme() functionality in Drupal, you'll want to read up on it on Drupal.org first. Hope this helps!


Access to only few fields of a content type for specific user I am using drupal 6. I have created one content type 'video' in which I have many fields like url,language,locations etc. I have created 1 role, Now I just want to give permissions to that particular role so that he can only add fields like url,locations. He shouldn't be able to use other fields.
Any Suggestion,

Field Permissions will let you assign different permissions to a field based on role.

  The Field Permissions module allows site administrators to set
  field-level permissions to edit, view and create fields on any entity.


Multistep user registration using profile2 How can we create a multistep user registration form in drupal 7 using profile2 module.

You can try Field group

  Fieldgroup will, as the name implies, group fields together. All
  fieldable entities will have the possibility to add groups to wrap
  their fields together. Fieldgroup comes with default HTML wrappers
  like vertical tabs, horizontal tabs, accordions, fieldsets or div
  wrappers.

Available group types

Fieldsets
Horizontal tabs
Vertical tabs
Accordions  Divs
Multipage steps: Note: This is only client side.

And i found a nice tut here


key value field for content types I've got a content type which consists of many (arbitrary number) key/value pairs.

What I'm looking for is a module like Options Element, which I can add to my custom content type. Are there any modules like this?

Double field may be used as key/value field.


Is there any other way to create more secure link in a drupal_set_message? Is there any other way to create more secure link in a drupal_set_message??

$loglink = l("bla bla", 'admin/config/services/blabla');
  drupal_set_message(t("You should not have empty or the default fields in $loglink. You have to fill your own information."), 'error');

No, there isn't a more secure way, especially when you are not outputting input coming from the user. Still, you should be using t()-placeholders.

Drupal core uses the following code, when outputting an URL.

// system_requirements()
$requirements ['php'] = array(
  'title' => $t('PHP'),
  'value' => $phpversion,
  'description' => $t('The phpinfo() function has been disabled for security reasons. To see your server\'s phpinfo() information, change your PHP settings or contact your server administrator. For more information, Enabling and disabling phpinfo() handbook page.', array('@phpinfo' => 'http://drupal.org/node/243993')),
  'severity' => REQUIREMENT_INFO,
);

  // action_synchronize()
  $link = l(t('Remove orphaned actions'), 'admin/config/system/actions/orphan');
  $count = count($actions_in_db);
  $orphans = implode(', ', $orphaned);
  watchdog('actions', '@count orphaned actions (%orphans) exist in the actions table. !link', array('@count' => $count, '%orphans' => $orphans, '!link' => $link), WATCHDOG_INFO);

The only difference is that, in the first case, the code is outputting an external URL while, in the other case, the URL is internal to the website.


How to print in twig a Flag Link field I have a views-view-unformatted.html.twig template working fine where I can print fields from a view of nodes.

Example: having i = 3, print row number 3 title

{{ rows[i]['content']['#row']._entity.title.0.value }}

This view has also a working relationship with flag. I see it working in the view preview.

How can I print the flag link inside views-view-unformatted.html.twig?

Not being able to find better solution nor documetation, I built this working hack:

add a fake text field entity. IE: for articles: http://yoursite/admin/structure/types/manage/article/fields  > Add field > Add text plain field
hook the view in a custom module:

function MYMODULE_views_pre_render(ViewExecutable &$view){
  if( $view->id() == 'VIEWID' ){
    foreach($view->result as $r) {
    // from https://www.drupal.org/comment/reply/295383/12504094
    $node = $r->_entity;
    $flag_link = [
      '#lazy_builder' => ['flag.link_builder:build', [
      $node->getEntityTypeId(),
      $node->id(),
      'FLAG',
    ]],
    '#create_placeholder' => TRUE,
  ];
  $flag_link = render($flag_link);
  $r->_entity->set('field_fake_flag_field', $flag_link); //.
    }
  }
}

print (finally) your flag link in the twig template:

{{ rows[i]['content']['#row']._entity.field_fake_flag_field.0.value }}

Twig is cool. It takes a while, sometimes.


How to switch view before render current view? I am using Field Collection Views module which allowed to create field widget as a view.

My requirement is to allow content author to choose widget for output this field (Field Collection). I added select field to article type to choose widget from two Field Collection Views views.

Field Collection is using views_embed_view for rendering this field, so I am trying to use hook_views_pre_view to switch to different view if author choose other than default view (display formatter)

/*
 * Implements hook_views_pre_view()
 */
function wzp_gallery_views_pre_view(&$view, &$display_id, &$args) {
    $node = menu_get_object();
    if (! $node->type == 'article') {
        return;
    }
    $field_name = FIELD_GALLERY_VIEW_FIELD_NAME;
    if (! $node->$field_name) {
        return;
    }
    $value = array_shift($node->$field_name);
    $view_info = explode('#', $value[0]['value']);
    if (! $view_info) {
        return;
    }
    $name = $view_info[0];
    $id = $view_info[1];
    if ($view->name == $name && $display_id == $id) {
        return;
    }
    $display_id = $id;
    if ($view->name == $name) {
        return;
    }
    drupal_set_message('
' . print_r($name, 1) . '
');
    drupal_set_message('
' . print_r($id, 1) . '
');
    $view = views_get_view($name);
    $view->set_display($id);
    $view->preview = TRUE;
}

but I am end up always with default view rendered.

Code form Field Collection Views module:

/**
 * Implements hook_field_formatter_view().
 */
function field_collection_views_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  $element = array();
  $settings = $display['settings'];

  switch ($display['type']) {
    case 'field_collection_views_view':
      //debug($items);
      $args = '';
      $i = 1;
      foreach ($items as $delta => $item) {
        if ($i == 1) {
          $args .= $item['value'];
        }
        else {
          $args .= '+' . $item['value'];
        }
        $i++;
      }
      $view_name = isset($settings['name']) ? $settings['name'] : 'field_collection_view';
      $display_id = isset($settings['display_id']) ? $settings['display_id'] : 'default';
      $content = views_embed_view($view_name, $display_id, $args);
      $element[0] = array(
        '#markup' => $content,
      );
      if (empty($items)) {
        field_collection_field_formatter_links($element, $entity_type, $entity, $field, $instance, $langcode, $items, $display);
      }
      break;
  }
  return $element;
}

Could someone give me any advice?

Answer

You can't switch view during render process but current display id.


How to replace "Enter quantity" text for Production variation? I'm working on Drupal commerce kickstart.

On Product variation, I need to change the text Enter quantity to Enter your quantities and change Add to Cart to Buy Now.

I tried with form alter it works to change Add to Cart to Buy Now but its not working for Enter quantity to Enter your quantities.

Can any one help on this?

I too had the same problem. Because this text is hardcoded and there is no configuration for updating the text.

Ways to change the text

Use String Overrides module.
Do a form_alter and change the text from Add to Cart to Buy Now

Form Alter for Enter quantity

function module_name_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'commerce_cart_add_to_cart_form') {
    $form['quantity']['#title'] = t('Enter your Quantities');
  }
}

Hope this code helps.


overriding submit functions with content types I have created some content types, some are created programmatically, others (including the one I am interested in are where created using the front end GUI.

And this is where my issue starts, I would like to format some of the text that is returned on the form submit.

And to be honest i am unsure how to do this.

in this example I have created a custom content type called 'show_date'

I would think that when the subnit function is caled I can pass the data to a custom fucntion, I would imagine this to being called show_date_submit thus:

function show_date_submit(&$form, &$form_state)
{
    /*
     my custom code would go here
    */

}

Is this right? any help given is as always appreciated and given Thanks for.

Al the best,

Jim

One way to do it is by using hook_form_alter, we can able to define a custom submit handler.

Find the form_id of that form and define a custom submit handler.

hook_form_alter(&$form, &$form_state, $form_id){
  if($form_id == 'custom_add_user_form'){
        $form['actions']['submit']['#submit'][] = 'show_date_submit_handler';
        //for submit $form['actions']['submit']
        //for preview $form['actions']['preview']
    }
}

function show_date_submit_handler(&$form, &$form_state){
    // manipulate the form submitted values over here
   }


Adding comments to user profiles I would like users on my site to write "feedback" of other users.

My thought is to have a content type called Feedback, and create a view of it, to preview at the foot of the user page. I can also put the main display of comments on its own views page.

Well, that's the display of them covered, but how do I enable them to be written? ie, link from the profile to create Feedback, and have it relate to that profile.

Also, Profile2 looks lacking, because you cannot control URL output.

You can use the entity reference field. Entity Reference module provides the autocomplete field for the user reference.

Add an entity reference field on the feedback content type. This field is autocomplete field. So whenever you create a feedback you can select the name of the user for which you want to add the feedback and refer the same.

Still if you are unclear then provide me some more info so i can help you out..

Update: In your case you have to create a link on the user profile page and add the name of the user being viewed in the query string. So if you are viewing the profile of user1 then on the user profile you can generate the link $base_url/node/add/feedback?name = user1

Now when any one clicks on that page you will be redirected on the node creation page and you can get the argument value from the URL. You can set this argument value in the form field using hook_form_alter() hook.

Update 2: I found something like your question here


Create Json from a view I'm trying to create a json from Views, using Views Datasource.

The problem is that if I create a display "page", using Json as style, if I try to go to www.mysite.com/path/to/page the system doesn't return me the Json (as I see in the preview of the view) but an entire classic drupal page with the output of the json in the content region (so I've menus, regions, etc).

Is there a way to obtain the output as a simple json?

The right way is to uncheck the "Views API" flag in display settings.


Can Profile2 present fields on registration? I'm looking at using Profile2 on a D7 site, so that we can have private fields, and different fields per role.

Is it possible to have Profile2 present its fields on the user registration page? New users are going to default to a particular role, so the fields would be that of the default role.

I've looked at the introductory and documentation pages, but they are very sparse. All I could find for configuring Profile2 on a site where it's installed was simply specifying the per-role fields.

I think there is a checkbox in the profile settings if it should be displayed in the user registration form. At Structure > Profile types > edit.


Entity reference or viewfield for Drupal8: How to embedd views output in my node? In Drupal 7 it was possible to include into one node (/node/x/edit) the following lines

Label 1
[view:adresses=block_1=argument1]
Label 2
[view:adresses=block_1=argument2]
Label 3
[view:adresses=block_1=argument3]

Result: Output of the view depending on the argument.

I need the same solution in Drupal 8!
How can I realize this?

Maybe entitity reference can solve this but I am able to use entity reference in Drupal 7 but in Drupal 8 this does not work (or I don't know how).

In Drupal 7 there are other modules like "View reference", "Viewfield" ... to solve this in a similar way.

But how can I solve this in Drupal 8?
The output (e.g. block) of a view should be displayed in the content of one specific node.

How can I create a node field with a reference to my adresses view output?
Thank you.

I solved the problem by myself:

I use the modules Twig tweak and Twig input filter

to solve the problem above in Drupal 8. Works fine.


Remove translation from the title field Is there a way to disable translations from Title field in each content type.

In the /admin/config/regional/content-language, when I remove translations from Title fields it gives Fatal error:  Maximum execution time of 120 seconds exceeded. No matter what time I give in the ini file this always happens. Is there a way to correct this? Or is there a way to remove Title fields translation without going to content-language

Yes, there is another way to do this in configuration. You can change

  translatable: true

in core.base_field_override.node.[content-type].title.yml.

If you don't find this configuration file, then there are no changes made so far for the title field. You can do this for example by modifying "Title field label" in the content type, which is also stored in this configuration and if it doesn't exist it will be created, so that you'll find the yaml in the exported config.

After you've changed the field label, export the configuration, open for each content type the mentioned yaml file, change translatable to false and reimport the configuration again.

See https://www.drupal.org/docs/8/configuration-management/workflow-using-the-drupal-ui or if you have installed drush use these two commands:

drush config-export
drush config-import

see https://www.drupal.org/docs/8/configuration-management/workflow-using-drush.


Create a view block for display of taxonomy term children I am trying to create a View of Taxonomy Terms which lists the child terms for the currently displayed term.  Is this even possible for taxonomy terms or is it only possible for Content Nodes?

yes,you can do this by :
on CONTEXTUAL FILTERS add "Taxonomy term: Parent term" and on once you've chosen it, there's a set of radio buttons entitled When the filter value is NOT available. Set this to provide a default value and then, in this case, choose "Taxonomy term id from url" from the drop-down menu.you are good to go.


Code for unziping file I am creating a module for Drupal 8, in which I want to upload and extract zip file to a root directory. Inside moduleSettingsForm.php file, I have a function submitForm(array &$form, FormStateInterface $form_state). I am getting all the values of uploaded file but I am unable to extract the content of file.

So is there any way to do this in Drupal 8?

Once you have the file uri of the uploaded file, this stops being a Drupal problem and starts being a PHP problem.

You should take a look at SO for a full description.

What you are looking for is this snippet.

$zip = new ZipArchive;
$res = $zip->open('file.zip');
if ($res === TRUE) {
  $zip->extractTo('/myzips/extract_path/');
  $zip->close();
}


Privatemsg through a Multi Site configuration? Is it possible to do such a thing for users in site 1 to message users in site 2 and visa versa? Using the Privatemsg module?

Multi-site is just a way to share code. Different sites are completely separated and know nothing of each other*.

There might be ways to theoretically do this using special recipient types, it would have to use services (or raw SQL queries) to another drupal installation, multi-site or not. And it wouldn't be easy to implement and likely also be very slow.

*With the exception of shared tables, but if you'd share your users, you wouldn't have different users in the first place.


Constructing array of term reference labels in php template? I'm currently trying to set up a simple LMS and have already defined a content type course that contains a term reference field accesstags, which I would like to use for defining view permissions. I.e. the field accesstags will contain multiple terms that will be linked to roles that should have access to the node in question.

To make a long story short: I have created a custom module that contains the function hook_entity_view_mode_alter and I would like to check, whether the term reference field accesstags contains the term "subscription":

function hook_entity_view_mode_alter(&$view_mode, Drupal\Core\Entity\EntityInterface $entity, $context) {
  ...
  if (in_array('subscription', ?????)) {
    ... allow access ...
  }
  ...
}

However, I'm not sure what to put at the spot that I marked with "?????". I know that I can construct the array of referenced terms by using $entity->get('field_accesstags')->referencedEntities()... but this array then contains the whole structure, whereas I only need the array of labels.

Is there an easy way for getting this array? Maybe even a built-in function?

Any help would be much appreciated.

Following @4k4's suggestion to post the final code as an answer myself... here's the code that I'm now using and that seems to work well...

First of all, I defined a simple helper function:

function getTermName($term) {
  return($term->getName());
}

This allowed me to extend my code (see my original question above):

function hook_entity_view_mode_alter(&$view_mode, Drupal\Core\Entity\EntityInterface $entity, $context) {
  ...
  $accesstags = array_map("getTermName", $entity->get('field_accesstags')->referencedEntities());
  if (in_array('subscription', $accesstags)) {
    ... allow access ...
  }
  ...
}

I'm still wondering, if there is a simpler way (without having to iterate over the array of terms), but for now the solution works well. Thanks again for your help, @4k4.


where can I find the login block to modify? I want to modify login block!Where can I see login block ?

I am using danland theme in drupal 7 site. So far I have walked through sites/all/themes/page.tpl.php file, node.tpl.php and template.php file, but I didn't find.

Can anyone help me in this ?

Thanks in advance.

Here are the steps for customizing login block available in Drupal.

1) Go to your template.php file for the theme you're working on. Should be in the root of the theme folder for your theme

2) Now check for the below mentioned function in your template.php file. if its not exist then create it and if its exists then append the below mentioned code in the same.

function yourthemenamehere_theme(&$existing, $type, $theme, $path) {
   $hooks['user_login_block'] = array(
     'template' => 'templates/user-login-block',
     'render element' => 'form',
   );
   return $hooks;
 }
function yourthemenamehere_preprocess_user_login_block(&$vars) {
  $vars['name'] = render($vars['form']['name']);
  $vars['pass'] = render($vars['form']['pass']);
  $vars['submit'] = render($vars['form']['actions']['submit']);
  $vars['rendered'] = drupal_render_children($vars['form']);
}

Now save and close!

3) Now in side your theme directory there will be a folder called "template". if its not there please create it there only and then create a php file inside that folder called: "user-login-block.tpl.php"
Inside this file, put the following code:

    <?php print $name; // Display username ?>
    <?php print $pass; // Display Password ?>
    <?php print $submit; // Display submit ?>
    <?php print $rendered; // Display hidden elements (required for successful login) ?>

    Singup OR Forgot Password

4) IMPORTANT STEP , navigate to "admin/config/development/performance" and click "clear all caches" -- this is critical because only after deleting cache you can able to see the changes in your login block.

Now you can change the stucture of user-login-block.tpl.php as your wish.

I hope this can help you.


Drush stoped working and drush status -v shows Executing: vagrant It's important to say that I don't use vagrant!

For some reason this afternoon drush stoped working, it remains stuck. If I run drush status -v I can see it get stuck at Executing: vagrant.
I may have typed something wrong at some point, maybe installed vagrant instead of varnish module but I can't remember and now I can't use drush anymore.

Does anyone have a clue on how to stop drush from trying to execute vagrant silently?

I just realize that I in the ~/.drush/ folder there is a drush-vagrant folder, after deleting it everything started working again.
The folder is from the drush-vagrant module that I installed by mistake.
See drush folder download answer: How to download directly to ~/.drush folder?


Adding extra parameter to hook function in custom module / get custom variable inside a hook from outside of that hook I would be glad to pass an extra variable that is created outside to the inner function in my custom module. That inner function is a hook. But i can not pass variable as an pareamter of that function, or could I ?

Nice to have ;) :

$foo = 1;
function hook_tapir_table_alter (&$table, $table_id )  {
echo $foo;
}

As a workaround, i can wrap $foo in a function and do i this way

function process_vars () {
    $foo = 1;
return $foo;
}

function hook_tapir_table_alter (&$table, $table_id )  {
    echo process_vars ();
}

How could i go without function call to outside function ? Any clues? Thanx!

You're already doing it the right way. You aren't in control of that particular hook so you can't control how it's invoked, and what parameters are passed.

Couple that with this information from the drupal_alter() docs:

  A maximum of 2 alterable arguments is supported. In case more arguments need to be passed and alterable, modules provide additional variables assigned by reference in the last $context argument:

And that means that in order to make changes to the arguments you'll need to patch the module that provides the hook.

You might want to consider variable_get() and variable_set() if the $foo variable is likely to change at all, or DB storage if it's something major.

But using a helper function to return that data is perfectly good practice; there are dozens of examples of the same in Drupal core itself.

Or....you could use the global keyword (emphasis because I wouldn't personally recommend it, it's not particularly good practice to pollute the global scope).

That would go something like this:

$foo = 1;
function hook_tapir_table_alter (&$table, $table_id )  {
  global $foo;
  echo $foo;
}


create custom template for lightbox2 I have created an override template for the poll content type called "page--type--poll.tpl.php" using a preprocess hook, but now I need to create extra effect on this template so that when people click on the title from the front page the node will show in a lightbox.
I got the lightbox effect to work, but it still shows the whole node, How I can tell drupal that this content type has two templates and that the difference is which link they clicked from the view.

The way I've handled this is by adding a extra $_GET parameter to the end of the lightbox link url-s. For example if the url is http://www.example.com/somepage then you could turn it into http://www.example.com/somepage?lightbox=true. This can be done via javascript if it's troublesome modifying the view - might even be more suitable so that users with javascript turned off will get a better template. Then you can tell Drupal to use a different template for lightbox content this way:

function mytheme_preprocess_page(&$variables) {
  if (isset($_GET['lightbox']) && $_GET['lightbox'] == TRUE) {
    $variables['theme_hook_suggestions'][] = 'page__lightbox'; // page--lightbox.tpl.php
  }
}


user_save adds values to the user, but they aren't "active" I'm taking over a website that had a user import; it has a function that sets the value for some Boolean fields on the user.

$user->field_perm_connexion['und'][0]['value'] = (int)$permissions['perm_connexion'];
user_save($user);

When I edit the user, the value is correctly checked; when I execute code like the following, the value is wrong.

$user_perm = user_load($uid);
// don't judge the ['und'][0]['value']
if(!empty($user_perm->field_perm_connexion) && $user_perm->field_perm_connexion['und'][0]['value'] == 1){
    $is_allowed = TRUE;
}

I need to go to the user page (in the people menu) and save again, to get the correct values.

What could the problem behind this be?

It may be static cache, try:

$user_perm = user_load($uid, TRUE);


How to change search_api_server options via CLI I'm using drupalvm to create my local dev environment, and am writing scripts to automate importing an existing site's db and changing other settings so that it's more like our actual server-hosted sites.

Drupalvm creates a Solr server at /solr/collection1 and uses HTTP, whereas the existing site looks for a Solr server at /solr/live and uses HTTPS. When the db is imported, the local site is looking in the wrong place for the Solr server.

I'd like to check the feasibility of adding another .sh script that changes the db entry for search_api_server so that it uses http and /solr/collection1.

I tried using a sql command to update/set the new value for search_api_server 'options', and it does successfully change the scheme to HTTP but doesn't change the path. Also, when I load the site's search api server admin page, the options seem to be completely empty at first and you have to edit and save them again for it to stick.

P.s. I am also currently testing changing drupalvm's default Solr server so that it uses /solr/live and https, but having some issues with the https part.

This problem was probably specific to Drupal-VM, but here's how I solved it. Rather than write a post-provision script that tried to run the sql command itself, I made a new file containing the sql command and told the post-provision script to use that file.

So instead of the script running this itself

sudo mysql -u root -proot drupal -e "UPDATE search_api_server SET options = 'a:14:{s:9:"clean_ids";b:1;s:9:"site_hash";b:1;s:6:"scheme";s:4:"http";s:4:"host";s:9:"localhost";s:4:"port";s:4:"8983";s:4:"path";s:17:"/solr/collection1";s:9:"http_user";s:0:"";s:9:"http_pass";s:0:"";s:7:"excerpt";i:0;s:13:"retrieve_data";i:0;s:14:"highlight_data";i:0;s:17:"skip_schema_check";i:0;s:12:"solr_version";s:0:"";s:11:"http_method";s:4:"AUTO";}' WHERE id='1'";

It now does this

sudo mysql -u root -proot drupal < $SEARCH_API_SERVER_SETUP_SQL_COMMAND_FILE

(Replace -u root -proot drupal with your sql username, password, and the site db)


Play or Download an Audio file I'm running a radio website on Drupal 7 http://punkrockradio.net/
We have podcast that user can listen with Pushtape Player using  Soundmanager2 API.
I have installed DownloadFile.

I would like to give my user the option to listen to the file or to download it.

Any idea?
Thanks in advance

There are a number of ways you could accomplish this. Some might be better than others depending on your specific requirements.

Since soundmanager2 and downloadfile both provide field formatters the easiest way is probably just to print the field twice, each with a different formatter.

A couple of ways you might do that (this is not an exhaustive list) are:

Create a node view with a contextual filter that takes a node ID. Set the filter to use a default value if no value is present and set the default to be the node ID from URL. Then put the field in question in the view twice with the different formatters. Then either manually print the view in your node template or use the EVA module to show the view on the node.
Set the field up to display as one of the formatters via the node display settings UI and print it manually in the node template like you would any other field. Then also add a node preprocess function to render the field a second time with the other formatter into a custom variable using field_view_field(). Then print that custom field rendering alongside the other field rendering.

I can possibly provide more detail on those solutions if you have further questions.


Fixing bad node that makes search not index, but completes cron Upon updating to the latest version of Drupal 7, the following errors presented themselves in the site:

Warning: Creating default object from empty value in node_build_content() (line 1398 of /var/www/html/modules/node/node.module).
EntityMalformedException: Missing bundle property on entity of type node. in entity_extract_ids() (line 7881 of /var/www/html/includes/common.inc).

These errors don't seem to interfere with much on my site, however, they do seem to stop cron from indexing the website. I've been sitting at 0% of 456 pages with a 500 page max for a week or two now since my first noticing.

I've done a lot of digging trying to resolve this issue and the following link is the closest thing I can find in resolving this issue: http://tappetyclick.com/blog/2013/01/14/how-find-bad-node-makes-search-indexing-cause-drupal-cron-fail#.Vuw1KhIrJTY

The difference between the link above and my issue is that my cron successfully submits, even though right before the success message in the report log, it produces the EntityMalformedException: Missing bundle property listed in the bullets above. Outside of that, its relatively the same story. I've gone through the step-by-step in that link and many others like it without any resolution.

I've also additionally run this through devel_debug and a few other options to better troubleshoot but no other errors produce. Devel_debug actually doesn't list any errors at all in its log.

At this point I'm up for suggestions as I'm running low on ideas of how to remedy what seems to be a relatively multi-possible bug. Any thoughts the community may have or links to previously helpful posts would be appreciated.

Thank you in advanced!

After some additional alterations I was able to isolate 3 nodes that were not presenting as broken, but once I accessed them with PHPmyadmin I was able to delete them from the list. Once I found them and removed them Cron began indexing once again.


Reverse order of view sort Ok so I've got this view, and it has a few dozen items. I want the last 3.

Sort ascending seems to work, however the events are in the opposite order than I want.

Sort descending pulls events back from June.

Is there any way to pull the events, but order them differently with views?

It seems you need to have pages ordered ascending, but inside a page descending. To do that, you need to query database in ascending order. Then reverse order of one page in template that renders it.

<?php

/**
 * @file  views-view-unformatted--yourviewname.tpl.php
 * Default simple view template to display a list of rows.
 *
 * @ingroup views_templates
 */
?>
<?php if (!empty($title)): ?>

<?php print $title; ?>

<?php endif; ?>
<?php /* foreach ($rows as $id => $row): // That's how it looks by default */ ?>
<?php foreach (array_reverse($rows, TRUE) as $id => $row): /* That's what you need */ ?>
  <div<?php if ($classes_array[$id]) { print ' class="' . $classes_array[$id] .'"';  } ?>
    <?php print $row; ?>

<?php endforeach; ?>


Changing column position in rows I've this layout:

This is perfect on large-small screen. But not adapt for what i want to displayed on mobile.
Displayed:

col1 col2 col3

 col4

How can i get this: col3 and col4 reodered on mobile.
Like this:

col1 col2 col4

 col3

So col4 change from row2 -> row1, col3. And cal3 get from row1 -> row2, col4. Just on mobile.
Note: This is to be applied just on mobile/small screen. For the display is fine for midle and large screen.

If you're able to use a flex container for your divs all in the same div, you might try using the order property in a media query for smaller screens. It lets you select the order of elements. I've done a fiddle here.

Here's the CSS I used.

.row1 {
  display: flex;
  flex-wrap: wrap;
  -webkit-flex-wrap: wrap;
  -ms-flex-wrap: wrap;
}
@media (max-width: 767px) {
  #col1 {order: 1;}
  #col2 {order: 2;}
  #col3 {order: 4;}
  #col4 {order: 3;}
}


pass argument through url and use it in exposed filters in views I have  select box with taxonomy term ID's in it and when i change the term the respective content appears. This work well.

I am having the same term id's as click-able links on Left side block. I was thinking if i could pass a argument to a view from the URL and make the view content change as per the argument. Is it possible ?

Yes, you can do this with two views two views.

Create the first view for the the block showing the term ids. It should be possible to change the links the way the second view expects them. May be you need some PHP do achiev this.

With the second view you expect the term id as a filter and show the appropriate information.


Why would my /admin/reports/dblog get "stuck" on only showing "page not found" errors? Edit #2: Ok, I finally logged out of my admin account, restarted the browser, then logged back in. Presto! Works. Now that I've thoroughly embarrassed myself, I'll just bow out and go hide underneath a rock.

Edit: Ok, looks like my question wasn't specific enough - sorry! Let's see if I can word this better. Thanks for your patience and to the people who've already taken a swipe at answering this.

I'm having a problem where, no matter what type I select, /admin/reports/dblog refuses to show any results other than for "page not found" entries. As soon as I hit the "Filter" button, it reverts back to the "page not found" results list.

I've tried clearing caches, rebooting Apache, running update.php ... nothing makes a difference. If I try "Clear Log Messages," I get an error screen saying "The website encountered an unexpected error. Please try again later," which is a remarkably unhelpful message. Any thoughts? Thanks!

I haven't added any new modules recently and the dblog results were working fine up until yesterday afternoon. I had made no changes to the site near that time.

I'm not receiving an Error 500 as far as I can tell, as was suggested; it's a generic error message that appears to be one of Drupal's canned messages. If that's not the case, my bad!

Try having a look in your server error_log file that will probably tell you what's causing the problem. My guess is an unsupported character or something has been recorded in a log message.

You could just try clearing the actual log table in the database. Looks like you're on drupal 7 so you'd want to truncate the watchdog table to remove all logged errors


Is a mailchimp newsletter with an entity view in the content area possible? I am a newbie on emailing solutions and I have to design a newsletter system that allows the customer to create a newsletter with some content + the 3 most recent articles.
I guess it could be possible with simplenews, but mailchimp is a requirement. So I was wondering if anyone has already tried to add an entity of view type in the content part of a mailchimp newsletter like it is possible to add a node entity type. Or by using a module like Insert view or by simply adding a little token like this one:

[view:my_view=my_display]

The context of the project is D8, but a D7 solution might help.

So nope. But there is another way using simplenews and place the view in the template of the newsletter, and then use another smtp instead of Mailchimp, like Mailjet which now has a release on D8.