Database problem after moving the site: unknown server error I just moved my site onto the server and put it under /drupal_test directory. I now have got an error in the browser, but there is no errors in the apache error log:

PDOException: SQLSTATE[HY000] [2005] Unknown MySQL server host 'http://www.mydomain.com' (1)
in lock_may_be_available() (line 167 of /var/www/drupal_test/includes/lock.inc).

I have searched around online, many suggests that this is a problem with settings.php, but I can't see any problem with my settings:

$databases = array (
  'default' =>
  array (
    'default' =>
    array (
      'database' => 'websitedb',
      'username' => 'websitedbusername',
      'password' => 'thepassword',
      'host' => 'http://www.mydomain.com',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
    ),
  ),
);

I tried to use the ip address as the host, I got an error like this:

PDOException: SQLSTATE[HY000] [2013] Lost connection to MySQL server at
'reading initial communication packet', system error: 111 in lock_may_be_available()
(line 167 of /var/www/drupal_test/includes/lock.inc).

Also, my current site www.mydomain.com works fine.

Any help will be very much appreciated! Thanks!

In the above database configuration the problem seems to be with the host, you need to enter the "database hostname", or try entering the static ip "xxx.xxx.xxx.xxx" of the database host.

Aslo check the credentials of your database if they are correct or not. Discussion about the same issue faced be other people is available at: https://drupal.org/node/1315592 .


Description of entity type properties Description of entity type properties in code is very poor and I cannot find alternative resources. Could anyone explain those properties?

For example: "data_table" is described as:

  The name of the entity type's data table.

But it doesn't explain anything.

I created a custom entity based on "examples" module, added "data_table", "revision_table", "revision_data_table", added revision entity key, but after drush updatedb --entity-updates only myentity_revision table was added, and I still cannot see myentity_data_table, and other tables that "node" entity is using for example. Why is that?

Could someone explain those properties, what they are precisely for, and as a bonus - how they relates to "setRevisionable/setTranslatable" methods that we can invoke when creating field definition?

I had to re-install to get it to work, AFAIK.
The data_table is initially empty, but gets filled up as soon as you start creating a few of your custom entities. But the table itself should be there.

What exactly the data_table is for, I'm clueless as well, as pretty much everything worked without declaring it.

I couldn't however get the Entity Autocomplete ( see here for more info/example ) form element to work without declaring the data_table.
As soon as I added the annotation, the autocomplete element worked by declaring #target_type => 'my_custom_entity'


How to warm-up Twig? I would like to warm-up Twig templates after cache rebuild or when needed. By warming-up I mean to process each twig template into php file.

Is this possible without rendering the content first?

The question sounds like coming from a Drupal 7 background :)

If I understand it correctly, you are looking for a way to execute some PHP logic before rendering the content. Just like what we were used to do in the *.tpl.php files.

However, PHPTemplate was removed and replaced by Twig for a reason. For truly separating business and presentation layers - on of the major reason.

This does not mean that you loose on to the control which you had with PHPTemplate files. This only means that you are now forced to follow the best standard practices ;-)

Ideally, in both Drupal 7 and 8 the template functions the rendering should be broken in two steps:

Business logic - The function which is responsible for initializing the data (to be returned to page). This could be a function which calls the theme() function, like the page callback of your hook_menu implementation where you pass the variables into it. These could also be the preprocess functions which could be used to add new and or change existing $variables to the theme element being called.
Presentation logic - These are nothing but the functions or template file responsible for printing the values that it gets from the Business layer into appropriate markup. In D7 we used *.tpl.php, whereas in D8 we use *.twig.

To deal with the issue at hand, you will need to the template_preprocess() function. The *.twig file is responsible to only print the variables, with minimum logical checks.


multistep registration from in drupal 7 need to add a user and role Here is my method

test_two_submit($form, &$form_state) {
  $page_one_values = $form_state['page_values'][1];
  drupal_set_message(t('The form has been submitted'));
  $page_one_values = $form_state['page_values'][1];
  drupal_set_message(t('The form has been submitted. name="@username @email", password=@password', array('@username' => $page_one_values['username'], '@email' => $page_one_values['email'], '@password' => $page_one_values['password'])));
}

What i am trying to do is to add a user to my multi-step form.

I guess my two questions are how to add a user and also assign that particular user to a role.

Would it be possible for someone to give a short example.

// Register this new user.
    $roles = user_roles();
    $userinfo = array(
      'name' => $name,
      'pass' => user_password(),
      'init' => $name,
      'status' => 1,
      'access' => REQUEST_TIME,
      // This is where we are different from the default function.
      'roles'        => array(array_search('campus_student', $roles) => 1),
      // the field_* values come from custom columns added through
      // thhe admin ui under manage fields for users.
      'field_first_name'   => array(LANGUAGE_NONE => array( 0 => array('value' => $get_ldap_details['first_name']))),
      'field_last_name'    => array(LANGUAGE_NONE => array( 0 => array('value' => $get_ldap_details['last_name']))),
      'field_perm_number'  => array(LANGUAGE_NONE => array( 0 => array('value' => $get_ldap_details['campus_perm_number']))),
      'mail' => $get_ldap_details['mail'],
    );
    $account = user_save(drupal_anonymous_user(), $userinfo);

EDIT: You can see how drupal itself typically creates in a user via drupal_external_login_register(). The above example uses some API calls to get all Roles and assigns very clearly X additional roles, it also sets up additional drupal Fields tied to the user entity.


Page not found when there are clean extra parameters in URL alias- I have a working site which has PathAuto with SubPath setting properly configured. When I try to access the site from localhost in XAMPP, it gives 404 not found at several pages where the clean URL has extra parameters.

For example,  this goes perfect: subdomain.example.com/url-friendly/extra-parameters

This, in local PC: www.example2.com/url-friendly/ goes right
This, in local PC. fails www.example2.com/url-friendly/extra-parameters

Is there some known issue with XAMPP and Drupal url alias?

I have discovered the problem and the solution. When you change domain, or you add a domain to the list in Domain Access, you later have to switch off SubPath, save, and later turn on SubPath again. In that way, it refresh "something", and everything works perfectly.

So if you have free parameters passed on the clean friendly URLs, you need to make those steps in order to assure that the site will work with the changed or added domains.


Tokens for Webform Component Is there a way to set up a Webform such that I can turn component field submissions into tokens for use in the submission email?

For example, I want to include "Message from [email address]" in the email subject line. The default options only allow for including only the component field in the email (subject: [email]), or only custom text.

Is there a way I can turn the component field submission into a token for use in the email? Looks like there's a module for turning webform items into tokens, but it's not for use within webform.


Get the value of a custom user field I have a custom form that needs to display a default value from a custom user field. The field was created under /admin/config/people/accounts/fields and its machine name is field_r_period_length_sec.

//get user
$userCurrent = \Drupal::currentUser();
$uid = $userCurrent->id();
$r_period = $userCurrent->field_r_period_length_sec;

However, the value doesn't show and I get this error:

  Notice: Undefined property: Drupal\Core\Session\AccountProxy::$field_r_period_length_sec

What am I doing wrong?

Berdir's answer gave me a search term that got me this:

$user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());

After a bit of trial and error, this is the code that works, in case anyone else needs:

$user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());
$r_period = $user->field_r_period_length_sec->value;

For multiple values, use

$r_period = $user->get('field_r_period_length_sec')->getValue();


jquery hover function in views template (drupal 6) I have a views template called: views-view-fields--video--block-1.tpl.php

Inside that file i have:

<?php

print '
';

print '
'. $fields['field_video_embed']->content.'
';

print '
'. $fields['title']->content .'
';

$hover_play = l('', 'node/' . $row->nid, array('attributes' => array('class' => 'play_button', 'style' => 'display: none'), 'html' => true));

print $hover_play;

print '
'; // vgrid

?>

As you can see in my JS code at the top of the template, i'm printing $hover_play when user hovers over .last-vid-block .imagecache object, so it fades In then fades Out, that works, yeah.

But the problem is -> i have in that views block 4 nodes with that markup, so when i hover over just one .last-vid-block .imagecache that $hover_play shows on all 4 objects... How to separate them - if i hover just 1st object $hover_play shows only at 1st object etc...
Thanks in advance!

ATTENTION! Edited js code at the top! It works as intended, is there any erros in that code?

The original issue was that you were targeting all play buttons at once with your JS, the second problem that came up in the comments below is that your play button is on top of your .imagecache object and your .play_button is taking away the mouse focus, thus firing "hover out"

Try this:

The downside to this, however, is that if you hover over the title on the right side (outside of the .imagecache) object, your still going to get the fade in/out effect triggered...

If that is not what you want then you could try altering the template:

<?php

print '
';

print '
';

print $fields['field_video_embed']->content;

$hover_play = l('', 'node/' . $row->nid, array('attributes' => array('class' => 'play_button', 'style' => 'display: none'), 'html' => true));

print $hover_play;

print '
';

print '
'. $fields['title']->content .'
';

print '
'; // vgrid

?>


Could not locate PHPMailer library I am running a Drupal 6 site using the SMTP (6.x-1.0-beta5) and the PHPMailer (6.x-2.2) modules for messaging. I configured SMTP and PHP  messages, successfully sent and received test messages.
I am using the Organic Groups module and trying to utilize the messaging functions in it, for example receiving notifications for administrator users regarding membership approval.
Drupal isn't sending any mail. When I checked the recent log entries, it reports this error.

Could not locate PHPMailer library

In /admin/messaging/settings I use HTML Mail (PHPMailer) as the default sending method.
Please help me to resolve this issue.

The module relies on the PHPMailer class to send HTML mail.  So to send HTML e-mails using Messaging you first need to install PHPMailer.

Check the README.txt file at /messaging/messaging_phpmailer/ for PHPMailer installation instructions.


How to copy current user'id to a custom field when adding a new entity? I have a custom content entity 'service' created with Drupal Console (drupal generate:entity:content).
I added my own fields to the standard ones created by DC. Of which 'seliste_id':

$fields['seliste_id'] = BaseFieldDefinition::create('entity_reference')
  ->setLabel(t('SEListe'))
  ->setSetting('target_type', 'person')
  ->setSetting('handler', 'default');

By default, the code generated by DC handles the owner of any new entity, owner_id being the id of the current user.
By design, seliste_id is the id of the other entity 'person' which is linked 1 <-> 1 to Drupal's 'user'.
So when a new 'service' is created, I'd like to "copy" its owner (i.e. the current user's id) to 'seliste_id'.
I know that I can do that in mymodule_entity_presave().
Is there a way to do that in the definition of 'seliste_id' field?
With ->setDefaultValue() or ->setDefaultValueCallback() maybe?
Any idea?

You probably want to use the setValue() function, like this:

$user = \Drupal::currentUser();
$node->FIELD_NAME->setValue(['value' => $user->id());


How can I programmatically change the view mode? In Drupal 7 I did something like:

  function mymodule_views_pre_render(&$view) {
    //dpm($view);
    if ($view->name == 'services') {
      $view->style_plugin->row_plugin->options['view_mode'] = variable_get('services_teaser');
    }
    else if ($view->name == 'portfolio') {
      $view->style_plugin->row_plugin->options['view_mode'] = variable_get('portfolio_teaser');
    }
  }

I don't know how to set the view mode on the fly, in Drupal 8. The idea is to be able to select the view mode for the view from a configuration form, instead of doing it from the view form.

How do I achieve this?

You can select VIew Mode as:

function YOUR_MODULE_entity_view_mode_alter(&$view_mode, Drupal\Core\Entity\EntityInterface $entity, $context) {
  if ($entity->getEntityTypeId() == 'taxonomy_term' && $entity->bundle() == 'tag' && $view_mode == 'full') {
    $view_mode = 'CUSTOM VIEW MODE';
  }
}


Drupal 8 HTML markup and semantics When building a bespoke site a pet hate is that you start with a front-end layout that is semantically sound and robust, but when you try and create said layout as a theme in Drupal, by default the system adds <div> markup around whatever node, field or general piece of information it can find.

The result is that I usually begin with Mothership as a base theme to reduce the noise of excess markup.

Will Drupal 8 (both core modules and shipped themes) adopt cleaner HTML semantics? If so, how might the new front end HTML compare to its Drupal 7 predecessor?

HTML5 is an obvious assumption. The game is no longer "wrap it in a div" as HTML 5 empowers front end developers to a wealth of possible tags in order to best convey meaning  (e.g. aside, header, navigation). How will Drupal change to allow this new level of semantics choice to be controlled by developers?

Why should it change (drastically) -- it embraces a base of HTML5 markup; anything beyond that essentially becomes business need, accessibility requirements or simply put designer preference on what clean and simple means to them.

Mobile Initiative
Design Initiaive
HTML5 Initiative

From HTML5 Initiative page

  We want to ensure we're spending our time implementing features that will directly benefit Drupal's user base the most. As part of this initiative we'll focus mostly on:

  Adding support for the new form elements to Drupal's Form API.
  Adding new semantic elements in core templates in an appropriate way.
  Adding ARIA roles to markup to improve accessibility.
  Simplifying style and script elements.
  Ensuring input filters and functions accept HTML5
  elements.

Does the above goals mean that Drupal 8 HTML markup will be as lean turning on Fences in Drupal 7 and nuking all built-in markup? No, will the base markup be too complex, hardly. It will be designed to meet most peoples needs.


Page Argument in Title How can I have the page argument appear in the page title?

    $items['path/path/%'] = array(
    'title'            => t('Dynamic Title %1'),
    'page callback'    => 'pagecallback',
    'page arguments' => array(2),
     'type'             => MENU_CALLBACK,
    'access arguments' => array('access content'),
  );

Is there some kind of text replacement or something you can use in there, or is what I'm asking impossible?

You can use a title callback function along with title arguments:

$items['path/path/%'] = array(
  'title callback' => 'MYMODULE_page_title',
  'title arguments' => array(2),
  'page callback'    => 'pagecallback',
  'page arguments' => array(2),
  'type'             => MENU_CALLBACK,
  'access arguments' => array('access content'),
);

function MYMODULE_page_title($arg) {
  return t('Arg is: @arg', array('@arg' => $arg));
}

The default title callback is t(), so if you just need the argument to be passed straight through as the title you can get away with just using title arguments.

See hook_menu() for more details.


How do I synchronize sites/default/files wtith a AmazonS3 bucket? I need to sync sites/defalut/files with a amazons3 bucket. I found the AmazonS3 module, which replaces the storage location, while I still want to use the files at sites/defalut/files.

I want to use AmazonS3 as a sort of backup, and not as a storage solution. The files will not be served from it.

How can I do this?

I also found the Storage API module.

If the need is to occasionally copy files from a directory to a corresponding directory on S3, you can use S3 CLI from AWS.

It provides a recursive copy:
aws s3 cp /tmp/foo s3://bucket/ --recursive

Reference: s3 — AWS CLI 1.2.13 documentation : http://docs.aws.amazon.com/cli/latest/reference/s3/

I programatically called this once using the shell-exec from python and invoking the CLI commands.

The long route require the use of AWS S3 REST API (or one of the client SDKs). I havent done this myself, but it is possible since the CLI itself is implemented this way. May be you can take a look at the CLI code on github


How can I show the user login block on the 403 page? With D8, I have a node (content type: basic page) that I use as a custom 403 (access denied) page.

I set this as the custom 403 page on: /admin/config/system/site-information.  The path is /node/21, and the alias is /error/403.

On the block admin page, I added the user login block to the content region.  I added the restriction "show only on certain pages":

/error/*
/view/*
/node/21

I have a view that requires "add content type ABC permission" to access.  The path to the view is /view/abc.  The anonymous user does NOT have this permission.

So, as an anonymous user, I go to /view/abc and am shown the content of /node/21.  BUT, the user login block is not shown.

If I go to the block administration screen and remove the "show only on certain pages" restriction, then I see the block as the anonymous user on /view/abc, but I don't want to show the login block on every single page; I only want to show it on the pages that are 403s.

What is the "path" to use for the user login block to only show it on a custom 403 page?

One approach is to add page templates to your theme registry:

function MYMODULE_theme_suggestions_page_alter(array &$suggestions, array $variables) {

  //Allow theming the site error pages
  $route_name = \Drupal::routeMatch()->getRouteName();

  switch ($route_name) {
    case 'system.401':
    // Unauthorized Access.
    $error = 401;
    break;

    case 'system.403':
    // Access Denied.
    $error = 403;
    break;

    case 'system.404':
    // Page Not Found.
    $error = 404;
    break;
  }

  if (isset($error)) {
    $suggestions[] = 'page__' . $error;
  }

}

Then in page--403.html.twig you can render a specific block with Twig. See: How to embed a view in a specific node? and Programatically print blocks in twig

*A reason I like this approach is that the Login block is a Drupal core block, not a custom one. You can just carry around a nice 403 template file and always know it will render out this block. The preprocess function above seems like the least invasive and time consuming (from looking at different approaches), plus it gives the ability to theme these error pages. I think it is ideal to utilize template files for error pages.


Create node from custom form using ajax How do I add a node from a custom form using ajax? I want it to be submitted in the backend. How will it be if there are custom fields?

in drupal you can create node using node_save function as below

$node = new StdClass();//creating a bare node
$node->type = 'answer';//giving it type
$node->status = 1;//give it a published staus
$node->title = "Step up to the FLava";//gives title
$node->body = "Body Body body"; //gives body

node_save($node);
//save it and give it the rest of the attributes`


Ubercart with Panels I would like to know if anyone is experienced with ubercart with panels.
I am making a website with these two modules, the ubercart is for the online store, the panels is for the layout. And the site headers and footers are within the mini panels of the panels module.

I would like to make the mini panels also appear on the ubercart checkout, cart pages but i dont know if it is possible, since the checkout , cart pages are generated by the ubercart modules and they are not nodes, views, and seems it is not possible to assign them info mini panels in panel module.

Is there any way to make a page generated by module appear as mini panels, and so that i can create a new page by using the mini panels. Thanks!

You can use the Context module to conditionally show blocks in certain regions.

So, in your case, you can create a context that is activated on the /cart and /cart/checkout paths, and add the minipanels blocks that you want to the header and footer.


My server ignores the .htaccess file I have a terrible problem: I have written rubbish within the .htaccess file, in order to break my web site, and cause an error 500. Result: nothing, nothing happens, the web site continues to be online.

That is, the .htaccess file is ignored completely. Why does this happen? I understand that this only has an answer: the Apache server is misconfigured. This is absolutely correct? Or are there other possible causes?

My file system: image 1 and image 2.

Originally the website was hosted on a folder within a server (mydomain.com/folder), and everything worked fine. Now I am migrating the website to another server, but within a subdomain. The features of the new server:

Subdomain: domain.company.com
Apache: 2.4.7 (Ubuntu)
Port: 80
phpinfo: Open phpinfo

UPDATE.

1) DNS. I checked my subdomain with http://whois.domaintools.com/ and http://mxtoolbox.com/SuperTool.aspx. I found no problems.

2) .htaccess. The file contains RewriteEngine on. RewriteBase is commented, because I don't know what to put when a subdomain. Anyway, no matter what I put in the file, it is completely ignored.

3) My settings.php has:

$ Base_url = 'http://domain.company.com'; // NO trailing slash!
There is not $base_path. Does not exist.

I cleared the cache Drupal. I cleared the browser cache. I truncate all tables that start with cache_.

It does not work. The file .htaccess remains ignored. This, I can not enable friendly URLs.

This generally happens when your web server does not have access to make the overrides to your webroot.

Check if your httpd.conf file has something of the following format

<Directory "/Applications/MAMP/htdocs">
    #
    # AllowOverride controls what directives may be placed in .htaccess files.
    # It can be "All", "None", or any combination of the keywords:
    #   Options FileInfo AuthConfig Limit
    #
    AllowOverride All

    #
    # Controls who can get stuff from this server.
    #
    Order allow,deny
    Allow from all

</Directory>

The important piece above is AllowOverride All, which will make possible for your .htaccess file to override the settings.

If you cannot change the settings in this file, I would recommend you to create a .conf file specific to your site (e.g. mysite.conf using the default file 000-default) in on of /etc/apache2/sites-enabled or /etc/apache2/sites-available, and modify the <Directory> tag to point to the root of your site.

Restart Apache in order to make this change visible. The site should now be able to pick up your .htaccess file.


How to generate the function stack trace of the last request made? Is there a module that can essentially show you the function stack trace of the last request made?

Say I have a form that I submit.  After the page loads with the result from the request, I would like to see a list of all the functions that were called, start to finish, that resulted in the currently loaded page.

A function trace will only show you the function calls that lead directly to that piece of code.

PHP provides the functions debug_print_backtrace() for that, which is however not very readable but it will result a huge amount of text. devel.module provides a ddebug_backtrace()function, which us much easier to read.

To see all function calls of a single page, you need to install a profiler like XhProf.


New DB field won't appear in Views I am trying to hack a crowdfunding module for Ubercart so that it lets certain vital pieces of information, such as funding goals and the amount already contributed, be displayed on the project pages.

I figured that a good way to do this would be to create a view that would display this information, and then make that the default view for the relevant node-type. Unfortunately, I can't get any fields from the uc_crowdfunding table to appear in the view editor. I even followed this guide should do the trick, as was suggested in this answer.

My added code is as follows:

uc_crowdfunding.module

/**
 * Implements hook_views_api()
 */
function uc_crowdfunding_views_api() {
  return array(
    'api' => '3.0',
    'path' => drupal_get_path('module', 'uc_crowdfunding') . '/views',
  );
}

uc_crowdfunding.views.inc

    /**
     * @file
     * Views hooks for UC crowdfunding projects.
     */

    /**
     * Implements hook_views_data().
     */
    function uc_crowdfunding_views_data() {
      $data['uc_crowdfunding_products'] = array(
        'table' => array(
          'group' => 'Crowdfunding: Crowdfunding products',
          'base' => array(),
        ),
        'cfid' => array(),
        'pfid' => array(),
        'dateline' => array(),
        'target' => array(),
        'type' => array(),
      );
      $data['uc_crowdfunding_products']['table']['base'] = array(
        'field' => 'cfid',
        'title' => t('Crowdfunding product'),
        'help' => t('Data for each crowdfunding product.'),
      );

      // Let's join some tables, eh?
      $data['uc_product_features'] = array(
        'pfid' => array(),
        'nid' => array(),
        'fid' => array(),
        'description' => array(),
      );
      $data['uc_product_features']['join']['uc_crowdfunding_products'] = array(
        'left_field' => 'nid',
        'field' => 'nid',
      );

      // Here are some fields
      $data['uc_crowdfunding_products']['target'] = array(
        'title' => t('Fundraising goal'),
        'help' => t('I guess that this is the amount of money that you\'re supposed to raise, huh?'),
        'field' => array(
          'handler' => 'views_handler_field_numeric',
          'click sortable' => TRUE,
        ),
        'sort' => array(
          'handler' => 'views_handler_sort_group_by_numeric',
        ),
        'filter' => array(
          'handler' => 'views_handler_filter_numeric',
        ),
      );

      return $data;
    }

EDIT: There was also this piece of code, which I had commented out earlier for some reason:

$data['uc_products']['join']['uc_crowdfunding_products'] = array(
  'left_table' => 'uc_product_features',
  'left_field' => 'nid',
  'field' => 'nid',
);

You might want to go about this in a different way, like adding a views handler to the module, but I took the question as how to get data from "uc_crowdfunding_products" table into Views. It also seems like the tables mentioned had Node IDs so I made a relationship there. You were pretty close with your code.

Before getting too fancy with relationships and joins, make sure the following basic code works. It adds the ability to list the target field from the products table and some field from the features table with any node associated with them. You'll want to add the node revisions tables if you have revisions on your site. You can also look at the Data project to give you an idea of how to adopt database tables into Drupal.

/**
 * @file
 * Views hooks for UC crowdfunding projects.
 */

/**
 * Implements hook_views_data().
 */
function uc_crowdfunding_views_data() {
  $data['uc_crowdfunding_products'] = array(
    'table' => array(
      'group' => 'Crowdfunding',
      'base' => array(
        'field' => 'nid',
        'title' => t('Crowdfunding Products'),
        'help' => t('Data for each crowdfunding product.'),
        ),
      'join' => array(
        'node' => array(
        'left_field' => 'nid',
        'field' => 'nid',
         ),
      ),
    ),
  );

  $data['uc_crowdfunding_products']['nid'] = array(
    'title' => t('Example content'),
    'help' => t('Some example content that references a node.'),
    'relationship' => array(
      'base' => 'node',
      'field' => 'nid',
      'handler' => 'views_handler_relationship',
      'label' => t('Example node'),
    ),
  );

  $data['uc_crowdfunding_products']['target'] = array(
    'title' => t('Crowdfunding Target'),
    'help' => t('Just a numeric field.'),
    'field' => array(
      'handler' => 'views_handler_field_numeric',
      'click sortable' => TRUE,
    ),
    'filter' => array(
      'handler' => 'views_handler_filter_numeric',
    ),
    'sort' => array(
      'handler' => 'views_handler_sort',
    ),
  );

  $data['uc_product_features'] = array(
    'table' => array(
      'group' => 'Crowdfunding',
      'base' => array(
        'field' => 'nid',
        'title' => t('Crowdfunding something'),
        'help' => t('Data for each crowdfunding product.'),
        ),
      'join' => array(
        'node' => array(
        'left_field' => 'nid',
        'field' => 'nid',
         ),
      ),
    ),
  );

  $data['uc_product_features']['nid'] = array(
    'title' => t('Example content'),
    'help' => t('Some example content that references a node.'),
    'relationship' => array(
      'base' => 'node',
      'field' => 'nid',
      'handler' => 'views_handler_relationship',
      'label' => t('Example node'),
    ),
  );

  $data['uc_product_features']['some_field'] = array(
    'title' => t('Crowdfunding field'),
    'help' => t('Just a numeric field.'),
    'field' => array(
      'handler' => 'views_handler_field_numeric',
      'click sortable' => TRUE,
    ),
    'filter' => array(
      'handler' => 'views_handler_filter_numeric',
    ),
    'sort' => array(
      'handler' => 'views_handler_sort',
    ),
  );

  return $data;
}


Render field values in node template Hello I'm working on a module,
I currently have an array with Node objects (custom content types),
I am passing this array to a custom template (twig) but I can not render it with the values of its fields.

For example:

The dump object of the data that is coming to the template

array:2 [▼
  0 => Node {#564 ▼
    +in_preview: null
    #values: array:24 [▶]
    #fields: array:2 [▶]
    #fieldDefinitions: array:32 [▶]
    #languages: null
    #langcodeKey: "langcode"
    #defaultLangcodeKey: "default_langcode"
    #activeLangcode: "x-default"
    #defaultLangcode: "es"
    #translations: array:1 [▶]
    #translationInitialize: false
    #newRevision: false
    #isDefaultRevision: "1"
    #entityKeys: array:4 [▶]
    #translatableEntityKeys: array:7 [▶]
    #validated: false
    #validationRequired: false
    #loadedRevisionId: "9"
    #revisionTranslationAffectedKey: "revision_translation_affected"
    #enforceRevisionTranslationAffected: []
    #entityTypeId: "node"
    #enforceIsNew: null
    #typedData: EntityAdapter {#1065 ▶}
    #cacheContexts: []
    #cacheTags: []
    #cacheMaxAge: -1
    #_serviceIds: []
  }
  1 => Node {#562 ▼
    +in_preview: null
    #values: array:24 [▶]
    #fields: array:2 [▶]
    #fieldDefinitions: array:32 [▶]
    #languages: null
    #langcodeKey: "langcode"
    #defaultLangcodeKey: "default_langcode"
    #activeLangcode: "x-default"
    #defaultLangcode: "es"
    #translations: array:1 [▶]
    #translationInitialize: false
    #newRevision: false
    #isDefaultRevision: "1"
    #entityKeys: array:4 [▶]
    #translatableEntityKeys: array:7 [▶]
    #validated: false
    #validationRequired: false
    #loadedRevisionId: "10"
    #revisionTranslationAffectedKey: "revision_translation_affected"
    #enforceRevisionTranslationAffected: []
    #entityTypeId: "node"
    #enforceIsNew: null
    #typedData: EntityAdapter {#1198 ▶}
    #cacheContexts: []
    #cacheTags: []
    #cacheMaxAge: -1
    #_serviceIds: []
  }
]

As you can see, the data is inside the key #values

#values: array:24 [▼
      "vid" => array:1 [▶]
      "langcode" => array:1 [▶]
      "revision_uid" => array:1 [▶]
      "revision_timestamp" => array:1 [▶]
      "revision_log" => array:1 [▶]
      "revision_default" => array:1 [▶]
      "nid" => array:1 [▶]
      "type" => array:1 [▶]
      "uuid" => array:1 [▶]
      "isDefaultRevision" => array:1 [▶]
      "status" => array:1 [▶]
      "title" => array:1 [▶]
      "uid" => array:1 [▶]
      "created" => array:1 [▶]
      "changed" => array:1 [▶]
      "promote" => array:1 [▶]
      "sticky" => array:1 [▶]
      "default_langcode" => array:1 [▶]
      "revision_translation_affected" => array:1 [▶]
      "field_custom_title" => array:1 [▶]

    ]

The twig template:

    {% for node in nodos %}

{{ node.field_custom_title}}
 #not work
    {% endfor %}

How do I get the values of the fields from twig?

The solution was simpler than I thought, it was simply using

{{ node.field_custom_title.value }}


Creating a site with Drush doesn't work Trying to install Drupal 8 using drush.

drush dl drupal --drupal-project-rename=example
cd example

So far, so good.

However, when I get to this part:

drush site-install standard --db-url='mysql://root:my+Password@localhost/db_name' --site-name=Example

I've also tried:

drush site-install standard --db-url='mysql://root:my+Password@127.0.0.1/db_name' --site-name=Example

But I get the following error:

  Failed to connect to your database server. The server reports the following message: SQLSTATE[HY000] [1045] Access denied for user root@localhost (using
      password: YES) Is the database server running? Does the database exist or does the database user have sufficient privileges to create the
      database? Have you entered the correct database name? Have you entered the correct username and password? Have you entered the correct database hostname?

All of the answers are "Yes," so the install should work. Is it something wrong with my syntax? I have other Drupal sites on this server that I've installed manually, it's just the Drush install I can't get to work. What am I doing wrong?

It is probably because you do not have a setting for the super user (user/1). You need to set the account user name and password, so you can login to Drupal.

drush site-install standard --account-name=admin --account-pass=12345 --db-url=mysql://dbusername:dbpass@localhost/db_name --site-name=Example


Can I create a block that shows custom node types but in a specific order? For example, I have custom block made with Views that shows some block icons that are links to modules.

I would like to rearrange them.

For example, I would like to say "Put node 3 first, then node 5, then node 1".

Thanks!

You can use Node Queue module, it may solve your problem.

  The Nodequeue module allows users to collect nodes in an arbitrarily ordered list. The order in the list can be used for a any purpose, such as:

  A block listing teasers for the five top news stories on a site
  A user’s favorite music albums
  A group of favorite from which one is randomly displayed

  Nodequeue provides a simple drag-and-drop interface to manually order any queue. Additionally, it allows nodes to be added and removed from queues without needing edit permissions to the node. Nodes can be added to queues either from a queue management tab or by links on the node teaser.


What is difference between #value and #markup? I had gone through drupal link which contains something as shown below
https://drupal.org/node/224333

Use '#markup' not '#value' for markup

(Issue) The new default type for items in forms or other structured array data (e.g. node content) passed to drupal_render() is '#type' => 'markup'. In Drupal 6 and earlier, the HTML content was added to the array using the #value attribute. In Drupal 7, this needs to be changed to #markup. This change also applies to those form elements of '#type' => 'item'. This change reduces the confusion between form values and markup and allows the code in drupal_render() to be simplified.

Example 1, from system.admin.inc
In Drupal 6:

<?php
  $screenshot = $screenshot ? theme('image', $screenshot, t('Screenshot for %theme theme', array('%theme' => $theme->info['name'])), '', array('class' => 'screenshot'), FALSE) : t('no screenshot');

  $form[$theme->name]['screenshot'] = array('#value' => $screenshot);
?>

In Drupal 7:

<?php
  $screenshot = $screenshot ? theme('image', array('path' => $screenshot, 'alt' => t('Screenshot for %theme theme', array('%theme' => $theme->info['name'])), 'attributes' => array('class' => 'screenshot'))) : t('no screenshot');

  $form[$theme->name]['screenshot'] = array('#markup' => $screenshot);
?>

I have a code in drupal 6 which is as shown below :

$form['in_title'] = array(
  '#type' => 'button',
  '#value' => t('ort'),
  '#executes_submit_callback' => false,
  '#attributes' => array('class' => 'hide-submit-exclude'),
);

I want to convert this code to D7 .
So When and where should I use #markup and #value ?
I just want to know the difference between #markup and #value

#markup is

  Used to set HTML that will be output on the form.

#value is

  Used to set values that cannot be edited by the user. Should NOT be confused with #default_value, which is for form inputs where users can override the default value.

For #value this might include submit buttons, hidden elements, etc. - basically anything that needs a value for the form submission, but where that value should not come from the user.

The only change you need to make in your sample code is to allow for the fact that classes in the attributes array must now be in an array themselves:

$form['in_title'] = array(
  '#type' => 'button',
  '#value' => t('ort'),
  '#executes_submit_callback' => false,
  '#attributes' => array('class' => array('hide-submit-exclude')),
);


How to enable a field programmatically I've created a field programmatically :
$field_storage = FieldStorageConfig::create(
  array('entity_type' => 'node', 'field_name' => 'field_desc', 'type' => 'string'));
$field_storage->save();
$field = FieldConfig::create(
  array('entity_type' => 'node', 'field_name' => 'field_desc', 'bundle' => 'mybundle', 'settings' => array('handler' => 'default', 'handler_settings' => array())));
$field->save();

But the field is disabled by default when I access to "manage form display".
My question is : how can I enable the field programatically?
thanks :)

You enable the field by adding a widget to the default form display mode:
$display_repository = \Drupal::service('entity_display.repository');

// Assign widget settings for the default form mode.
$display_repository->getFormDisplay('node', 'mybundle')
  ->setComponent('field_desc', [
    'type' => 'string_textfield',
  ])
  ->save();

See Add content type field programmatically


Long form links in an "overview page" I have a drupal project with a hierarchical page structure. On each category page (top level), I'd like to have a blurb about the category, and then a series of links to subpages, where each link has a title, an image, and a sentence or two, laid out in a box.

I've looked into modules such as "Menu Node Views" and "Node Hierarchy" but I'm not certain that those are the best way to go about doing this. (Right now, as a temporary solution, I've just defined a bunch of blocks each containing an individual link/image/blurb and attached them to the overview pages using contexts).

Can someone suggest a good way to do this? Ideally it could be attached to the menu system in some way so that changes to the menu would be reflected in the appropriate overview page.

(See http://www.freethechildren.com/aboutus/index.php for an idea of the kind of navigation structure I want to display in the page content, although there will be actual content above the link blocks).

I would simply use content types (cck if you're in d6), views in blocks, taxonomy and some theming. I'm sure there are other ways to do it, but this would maybe be one.

Create a taxonomy 'category' and add all the 'categories' to it.

Create the content types category_page and category_sub_page (or something along those lines).

Create the fields you need for each content type:
For the category_page add a taxonomy tag field (to add the category from your 'category' taxonomy vocab) and if you wish to have images as headers different on each cat page add an image field etc ..

For the sub_page you need 2 or 3 image fields (depending on how many different images you wish to show (1 on the teaser, 1 or 2 on the main page?) and another taxonomy field.

Create your category overview page - tag it.
Create your subpages pages for that cat - tag them too.

Create a .tpl file for your node type:
In d7, copy the node.tpl.php file in your theme/template/ directory twice and name them node--category_page.tpl.php and node--category_sub_page.tpl.php (that's if you used naming conventions like above).

Create a node view that displays node type = category_sub_page and filter them by category, so only display category = 'SOMETHING' - or go even further and use arguments to get tax term of page and show only subpages with the same term (this way you could only use 1 view for multiple category pages). Create a block view from that showing teasers, add it to the content reagion using the blocks page. It should be displayed below the actual page content - if you don't have a region there you will need to add a block region. You'll have to add it to your theme in the page.tpl.php and the theme.info file. Read up about it.

Now edit your theme files for sub_pages .. node--category_sub_page.tpl.php - start it with

<?php if (!$page): ?>

anything in  between here will be shown as the teaser - that's you're menu block with text image - then

<?php endif; ?>
<?php if ($page): ?>

now anything in between is your sub_page full view.

To help you add items use to display the different items called.

 <?php dsm($node); ?>

then add them with php, defining your layout and style classes. Now theme it using css to get your desired look

Now you've create a node that displays sub-nodes in a block below the content.


Batch operation keeps looping after completion The batch operation I created works fine, until it's done.  Once it's done it just loops back and does it again.  It will loop through until the VM runs out of resources.

I am fairly certain this has to do with my completeImport method.  If I throw a syntax error in there it will finish the import successfully but then error out once it gets to that method.

The controller for the batch op: (I ommited methods that had nothing to do with the batch itself.  They were for CRUD or building URLs.)

class MyModuleController {

  public function import() {
    $endpoints = array(
      'courses' => $this->getEndPoint('courses', NULL),
    );

    foreach ($endpoints as $data_type => $endpoint) {
      $response = $this->getResponse($endpoint);
      $operations = MyModuleController::processResponse($response, $data_type);

      $batch = array(
        'title' => 'Importing ' . $data_type,
        'operations' => $operations,
        'finished' => 'mymodule_complete_import',
        'init_message' => t('Importing...'),
        'progress_message' => t('Operation @current out of @total.'),
        'error_message' => t('Batch failed.'),
        'file' => drupal_get_path('module', 'mymodule') . '/mymodule.import.inc',
      );

      batch_set($batch);

      return batch_process('academy/courses/import');
    }

    return array(
      '#type' => 'markup',
      'value' => t('Imported?'),
    );
  }

  public static function processResponse($response_data, $data_type) {
    $operations = array();

    foreach ($response_data as $data) {
      switch ($data_type) {
        case 'courses':
          // Used to look up if a course was already imported.
          $id = (string) $data->Id;

          $data_array = array(
            'Name'                      => (string) $data->Name,
            'Active'                    => ((string) $data->Active == 'true' ? 1 : 0),
            'CourseCodeForBulkImport'   => (string) $data->CourseCodeForBulkImport,
            'EcommerceLongDescription'  => (string) $data->EcommerceLongDescription,
            'EcommerceShortDescription' => (string) $data->EcommerceShortDescription,
            'ForSale'                   => ((string) $data->ForSale == 'true' ? 1 : 0),
            'Code'                      => (string) $data->Code,
            'Id'                        => $id,
            'OriginalId'                => (string) $data->OriginalId,
            'Price'                     => (string) $data->Price,
            'Description'               => (string) $data->Description,
          );

          break;
      }

      $operations[] = array(
        'mymodule_response_importer',
        array($id, $data_array, $data_type),
      );
    }

    return $operations;
  }

  public static function completeImport() {
    return new RedirectResponse(Url::fromRoute('system.admin_content'));
  }

}

mymodule.import.inc:

function mymodule_response_importer($id, $data, $data_type, &$context) {
  $entity = MyModuleController::findExisting($data_type, $id);

  switch ($data_type) {
    case 'courses':
      if ($entity === FALSE) {
        MyModuleController::createNode($data);
      }
      else {
        MyModuleController::updateNode($data, NULL, $entity);
      }

      break;
  }
}

function mymodule_complete_import() {
  MyModuleController::completeImport();
}

I was able to fix it by using the magic send() method for RedirectResponse class and building a full URL (mostly) manually.

  public static function completeImport() {

    $url = $GLOBALS['base_secure_url'];
    $url .= $GLOBALS['base_path'];
    $url .= Url::fromRoute('system.admin_content')->getInternalPath();
    $url .= '?status=All&type=academy_webinar&title=&langcode=All';

    $redirect = new RedirectResponse($url);

    $redirect->send();
  }


Generate installed modules into a composer.json for existing site: I need to manage via Composer, not via UI I have a Drupal 8 site up and running with modules that were manually installed. I want to generate an appropriate composer.json file to manage these using Composer.

The closest I could find to achieve this is an old Drupal 7 module, Composer Generate, mentioned in how to install package via composer? but that only works with Drupal 7 and it isn't any longer developed.

How to move Composer created folder of drupal-8.x.x up one level to html? suggests that third-party modules can/should be handled with Composer, but I would like to not have to manually rewrite the composer.json file to achieve this.

Is there a Drupal 8 / Composer / Drush way to accomplish this, or is manually updating the composer.json the only option?

Composer Generate is a Drush extension. It can be used either with Drupal 7 or Drupal 8. Considering that the latest release available on drupal.org is dated Febrary 25, 2016, it's probable it is not compatible with the Drush version you would be use on your site.

The project page for Composer Generate suggests using the Composerize module, which is available for Drupal 8.

  This module can generate a composer.json from your installed Drupal code base, which can be used to regenerate that code base by running composer install.

Be careful of the warning reported in the project page.

  This module is still in development. It supports very basic Drupal 8 setups, but there are many necessary features it still lacks (e.g., support for patches, JavaScript libraries, distributions, etc). We're working on all that stuff, but this module is definitely not ready for prime time.

The module is supported by Acquia, and the development version has been updated on March 20, 2018.

Alternatively, as the project page suggests, you could use Composerize Drupal, a Composer plugin for converting a non-Composer-managed Drupal site to a Composer-managed Drupal site.


is memcache slowing down my website? Hi I have a brand new website, the upload time was around 2 seconds and after installing Memcache it s around 10 seconds, what coulds be causing this issue?
website is in drupal6

I can not post an comment?

Anyway, there is not much information given about the hardware, settings etc. so from that point off its hard to say.

You might wanna retrace your steps if you are sure the uploadtime increased with 500 percent. Then you know if Memcache caused any problems, what ever the result is please update the question with more specific information.


Video upload via FTP The Video module for Drupal 6 allows for video files uploaded via ftp to be played.  Does this module's Drupal 7 version have this feature?  If not what is the work around for large files?

You can add this feature using the FileField Sources module. This module adds FTP (and more) upload to any FileField upload field, including the Video FileField upload field.


How to grant "edit any file" permission only to files attached to a certain node type? The same question in other words:

How a file can inherit edit permission from node permission which is attached to?

Hi all,

I have 2 node types: articles and cars.

A file entity field is attached to both so users, through media module, can attach images to articles and cars.

Now I want a moderator role that can edit files attached to cars ONLY.

How to accomplish this?

Granting "Edit any files" to Moderator allow him to edit every files, articles attached files also, but I don't want this.

Thank you for any help

Maybe I've found a workaround.

Files editing is accessible in a general direct way (bypassing their nodes) by the following url:

www.mysite.com/file/[fid]/edit

So only through this link a Moderator can have access and edit ANY file (please tell me if this is correct).

So, doing:

/**
 * Implementation of hook_menu_alter()
 */
function helper_menu_alter(&$items) {
  // Provide custom access callback for direct files edit url
  $items['file/%file/edit']['access callback'] = 'helper_direct_file_edit_url_access_callback';
}

/**
 * Custom access callback
 */
function helper_direct_file_edit_url_access_callback() {
  // Disallow direct files edit url to everyone but superadmin
  if (!_helper_is_user_superadmin()) {
    return FALSE;
  }
  return TRUE;
}

Moderators with "Edit any file" permission (and everyone in anycase) cannot directly access to edit files, but they can edit files with media module through nodes they have edit access to (e.g. cars)

Do you think guys this could be a good workaround?

There is a better way to accomplish this?

Thank you very much


How do I set the custom upload directory for a plupload from field? My module uses a plupload form field. I'm trying to define a custom directory for my plupload uploads.

A normal upload form for a managed file looks something like this:

$form['managed_file'] = array(
    '#title' => t('Managed file example'),
    '#type' => 'managed_file',
    '#upload_validators' => array(
        'file_validate_extensions' => array('jpeg jpg png gif'),
        'MODULENAME_validate_not_filename' => array('test.')),
    '#upload_location' => 'public://imagebank',
    '#progress_indicator' => 'bar',
    '#progress_message' => 'One moment while we save your file...',);

Plupload integrations module suggests using following code to integrate an Plupload form in a custom module:

$form['my_element'] = array(
    '#type' => 'plupload',
    '#title' => t('Upload files'),
    '#description' => t('This multi-upload widget uses Plupload library.'),
    '#upload_validators' => array(
    'file_validate_extensions' => array(
        'jpg jpeg gif png txt doc xls pdf ppt pps odt ods odp'),
        'my_custom_file_validator' => array('some validation criteria'),
    ),
    '#plupload_settings' => array(
        'runtimes' => 'html5',
        'chunk_size' => '1mb',
    ),
);

In a managed file form there is this parameter to set upload location uri:

'#upload_location' => 'public://imagebank',

In the plupload form I see no such parameter.

I'm still learning custom module development so the answer might be obvious, but it isn't for me atleast. Could someone please point me in the right direction? The files should be uploaded to public://imagebank

I eventualy found the solution in the plupload.module file itself. In there there is a page that can be found on folowing url: /plupload-test.

The form has a submit callback function:

/**
 * Submit callback for plupload_test form.
 */
function plupload_test_submit($form, &$form_state) {
  $saved_files = array();
  $scheme = variable_get('file_default_scheme', 'public') . '://';
  // We can't use file_save_upload() because of
  // http://www.jacobsingh.name/content/tight-coupling-no-not
  // file_uri_to_object();
  foreach ($form_state['values']['pud'] as $uploaded_file) {
    if ($uploaded_file['status'] == 'done') {
      $source = $uploaded_file['tmppath'];
      $destination = file_stream_wrapper_uri_normalize($scheme . $uploaded_file['name']);
      // Rename it to its original name, and put it in its final home.
      // Note - not using file_move here because if we call file_get_mime
      // (in file_uri_to_object) while it has a .tmp extension, it horks.
      $destination = file_unmanaged_move($source, $destination, FILE_EXISTS_RENAME);
      $file = plupload_file_uri_to_object($destination);
      file_save($file);
      $saved_files[] = $file;
    }
    else {
      // @todo: move this to element validate or something and clean up t().
      form_set_error('pud', "Upload of {$uploaded_file['name']} failed");
    }
  }
}

I ended up using the same function in my custom module but adding my custom directory to the $destination the function now looks like this:

function plupload_files_submit($form, &$form_state) {
  $saved_files = array(); //Array to capture file objects
  $scheme = variable_get('file_default_scheme', 'public') . '://';
  $directoryname = 'imagebank'; // Directory where images are collected
  $imagebankpath = $scheme . $directoryname;
  file_prepare_directory($imagebankpath, FILE_CREATE_DIRECTORY); // Create the folder if it doesn't exist
  // We can't use file_save_upload() because of
  // http://www.jacobsingh.name/content/tight-coupling-no-not
  // file_uri_to_object();
  foreach ($form_state['values']['uploadfiles'] as $uploaded_file) {
    if ($uploaded_file['status'] == 'done') {
      $source = $uploaded_file['tmppath'];
      $destination = file_stream_wrapper_uri_normalize($imagebankpath .'/'. $uploaded_file['name']);
      // Rename it to its original name, and put it in its final home.
      // Note - not using file_move here because if we call file_get_mime
      // (in file_uri_to_object) while it has a .tmp extension, it horks.
      $destination = file_unmanaged_move($source, $destination, FILE_EXISTS_RENAME);
      $file = plupload_file_uri_to_object($destination);
      file_save($file);
      $saved_files[] = $file;
    }
    else {
      form_set_error('uploadfiles', "Upload of {$uploaded_file['name']} failed");
    }
  }


Drupal 7 views: Get NID in views using contextual filters Does anybody know how to get the nid from a node using contextual filters or filter criteria in views

WITHOUT using "Get id from url"?  I was thinking about using PHP or getting it from a node-field.

My view is a block of comments that is to be placed together with a node. The comments needs to belong to the node and linked by node ID. In this case the "Get ID from url" wont work since the node itself is listed in another view.

It is a view-block (containing comments) inside of a node that is listed in a view.

If you are loading and displaying your view in the node.tpl or node--<content-type>.tpl file, you could supply the current node nid as an argument to your block view, then you can setup a contextual filter for Content: Nid. I would do something like this:

 // get view
 $view = views_get_view('YOUR_VIEW_NAME');
 // set display for view
 $view->set_display('YOUR_VIEW_BLOCK_NAME');
 // set current node nid as argument to view
 $view->set_arguments(array($node->nid));
 // execute view
 $view->execute();
 // render view
 print $view->render();

You could also try to use views_embed_view() which I think would be the preferred way to do this. It takes two parameters, name and display_id, any additional parameters will be passed as arguments to the view:

print views_embed_view('YOUR_VIEW_NAME', 'YOUR_VIEW_BLOCK_NAME', $node->nid);

I'm not sure that this helps, the question is a little vague=)


SelectQuery row_number won't work with PDO I'm working on a project that needs to query a MySQL database and select the row number (among other columns) for each row. To be more specific, I have the table test and want to get the table result:

test        result
a | b     a | b |counter
1 | 1     1 | 1 |  1
1 | 3     1 | 3 |  2
1 | 5     1 | 5 |  3
2 | 1     2 | 1 |  1
2 | 2     2 | 2 |  2
3 | 1     3 | 1 |  1
3 | 3     3 | 3 |  2

where column counter counts the number of occurences of a with different b

I have found the solution for MySQL in a post, using variables inside the query:

SELECT
  o.a AS a,
  o.b AS b,
  @num := IF(@a = a, @num + 1, 1) AS counter,
  @a := a AS dummy
FROM
(
  SELECT
    t.a AS a,
    t.b AS b
  FROM test t
  ORDER BY a ASC
) o

which gives me the exact result (with the addition of one dummy column).

The problem arises when I try to implement it in Drupal 7 using the following code:

$tq = db_select('test', 't')
  ->fields('t', array('a', 'b'));
// Order rows for correct numbering
$tq->orderBy('a');
$t2q = db_select($tq, 'o')
  ->fields('o', array('a', 'b'));
// Add counter
$t2q->addExpression('@num := IF(@a = a, @num + 1, 1)', 'counter');
// Add dummy column
$t2q->addExpression('@a := a', 'dummy');
// Store results
$r = array();
foreach($t2q->execute() as $row)
  $r[] = (array)$row;
dpm($r, $t2q->__toString());

The prepared query is correct and exactly the same as the above query:

SELECT o.a AS a, o.b AS b, @num := IF(@a = a, @num + 1, 1) AS counter, @a := a AS dummy FROM (SELECT t.a AS a, t.b AS b FROM {test} t ORDER BY a ASC) o

but the result is:

test        result
a | b     a | b |counter
1 | 1     1 | 1 |  1
1 | 3     1 | 3 |  1
1 | 5     1 | 5 |  1
2 | 1     2 | 1 |  1
2 | 2     2 | 2 |  1
3 | 1     3 | 1 |  1
3 | 3     3 | 3 |  1

I have no idea of the internals of PDO and the reason why variables inside SELECT statements won't work.

If I try with db_query feeding it the prepared query (as in the following code) I get the same results.

$tq3 = db_query($t2q->__toString());
while($row = $tq3->fetchAssoc())
  $r[] = $row;
dpm($r);

But if I first call execute on the query I get the correct results (but can not use extend on DatabaseStatementInterface).

$tq3 = db_query($t2q->__toString());
$tq3->execute();
while($row = $tq3->fetchAssoc())
  $r[] = $row;
dpm($r);

Does anyone have any helpfull idea?

In order to count the number of occurence you can use groupBy and having cluases but as you mention above your format is completely different. So it is not feasible to you. Try this one may be it'll helpful to you.

$query = db_select('temp', 't');
$query->fields('t',array('a','b'));
$query->orderBy('t.a');
$result = $query->execute();

$field_sum = 1;
$prev = NULL;
foreach ($result as $record) {
   if ($prev ==  $record->a) {
      $field_sum++;
   }
   else {
   $field_sum = 1;
   }

   echo "\n a " . $record->a . " | b " . $record->b . " | Counter ". $field_sum;
   $prev = $record->a;
}

Also ensure that these list of function can't be chained:

addExpression()
addField()
addJoin()
extend()
innerJoin()
join()
leftJoin()
rightJoin()


PHPUnit Checking file exists failing I'm using a Kernel test in Drupal to add a new instance of my custom entity. In the postSave() method of my entity, I generate a PDF using TCPDF. In the browser, this all works well and I can see the generated PDF in my file system. My issue is that when I run PHPUnit from the CLI, it produces my entity fine but it can't assert that the file exists.

class CustomEntityAddTest extends EntityKernelTestBase
{

  /**
   * A list of modules to be enabled to run this test
   *
   * @var array
   */
  public static $modules = ['block', 'datetime', 'custom_entity', 'entity_reference', 'file', 'migrate', 'options', 'system', 'taxonomy', 'text'];

  /**
   * The Directory where generated PDFs are stored
   */
  const FILES_DIRECTORY = \Drupal\custom_entity\Entity\CustomEntity::DP_DIRECTORY_BASE;

  public function setUp() {

    parent::setUp();
  }

  /**
   * Undocumented function
   *
   * @return void
   */
  public function testAdd() {

    $custom_entity = CustomEntity::create([
      'user_id' => 1,
      'status' => 0,
      'title' => 'First Test!',
      'inventco' => CustomEntity::generateSubmissionID(),
      'abstract' => 'Test abstract',
      'created' => time(),
      'changed' => time(),
    ]);

    $this->assertInstanceOf(CustomEntity::class, $custom_entity, "An entity was not created");

    $inventco = $custom_entity->get('inventco')->getString();

    // debugging
    $path = "/var/www/drupalvm/docroot/sites/default/files/private/{$inventco}/{$inventco}_frontpage.pdf";
    print_r(scandir("/var/www/drupalvm/docroot/sites/default/files/private/{$inventco}"));
    print($path);
    // Assert DP files exist
    $this->assertFileExists($path, "Generated PDF does not exist");
  }
}

How can I assert that the file was produced? I've checked that the filepath is correct.

It was because I hadn't called the save method on the $custom_entity object.

Credit and thanks to Andy


Why do I get "Type does not correspond to an entity on this site" when POSTing to REST api behind an Apache Reverse proxy? I have the REST api configured to allow POSTing new users to /entity/user. On my local machine, it works just fine. Once I push up to my remote host, it stops working.

The key difference is that on my local machine, my site is running in a docker container bound to port 6050, so all rest calls go to localhost:6050.

On my remote host, I have docker configured behind an Apache 2.4 reverse proxy. So the docker container is still bound to 127.0.0.1:6050, but all requests should go to https://sub.example.tld/.

To summarize, posting a new user to http://localhost:6050/entity/user?_format=hal_json, with the appropriate X-CSRF-Token and Content-Type headers set, works. It returns 200.

Posting to https://sub.example.tld/entity/user?_format=hal_json, with the appropriate X-CSRF-Token and Content-Type headers set, does not. It returns 422 Unprocessable Entity.

{"message":"Type https:\/\/sub.example.tld\/rest\/type\/user\/user?_format=hal_json does not correspond to an entity on this site."}

In the recent log messages, I see:

Symfony\Component\HttpKernel\Exception\UnprocessableEntityHttpException: Type http://sub.example.tld/rest/type/user/user?_format=hal_json does not correspond to an entity on this site. in Drupal\rest\RequestHandler->deserialize() (line 201 of /var/www/html/web/core/modules/rest/src/RequestHandler.php).

I do manually set the user's "_links" array:

"_links": {
        "type": {
          "href": "https://sub.example.tld/rest/type/user/user?_format=hal_json"
        }
      },

I know that authentication isn't the issue. My code is successfully accessing views that require authentication.

Since I think it might be something to do with these settings, I do have the following set:

$settings['trusted_host_patterns'] = ["$sub\.example\.tld$"]
$settings['reverse_proxy'] = TRUE;
$settings['reverse_proxy_addresses'] = ["internal network ip","172.18.0.1","127.0.0.1"];

I'm running Drupal 8.7.3.

My docker image is based on php:7.1-apache.

Any ideas what I'm doing wrong?

The solution is to remember set the base url of any _links href values to use http if Drupal expects it, and https if Drupal, instead, expects that.

In my case, I was using https, but the https connection was terminated at the Apache reverse proxy, so Drupal wanted http.

Using a REST extension to test with let me manually change the links array to reflect that, and the user was created just fine.

Also, the "type" href should not have the _format=hal_json on it.


Place two text fields within a single  class I have assigned class names to both user name & password text fields in user login block separately like this and it's working.

function mymodule_form_alter(&$form, &$form_state, $form_id, $element) {
   if ( TRUE === in_array( $form_id, array( 'user_login', 'user_login_block') ) ) {
       $form['name']['#attributes']['class'] = array('mgnB10', 'fntXL', 'drkFg1');
       $form['pass']['#attributes']['class'] = array('fntXL', 'drkFg1');
   }
}

I want to include these fields inside a single '' and assign class name for design purpose, like this.

  username field
  password field

I am using the following code but I didn't get the expected output.

function mymodule_form_alter(&$form, &$form_state, $form_id, $element) {
   if ( TRUE === in_array( $form_id, array( 'user_login', 'user_login_block') ) ) {
       $form['user_login']['#attributes']['class'] = array('#prefix' => 'myclass');
       $form['name']['#attributes']['class'] = array('mgnB10', 'fntXL', 'drkFg1');
       $form['pass']['#attributes']['class'] = array('fntXL', 'drkFg1');
       $form['user_login'] = array('#suffix' => '
');
   }
}

Hope this will help you,

In Drupal 7 you can achieve it by using the #prefix and #suffix properties in hook_form_alter().

   /**
    * Implements hook_form_alter().
    */
    function hook_form_alter(&$form, &$form_state, $form_id) {
      switch ($form_id) {
        case 'user_login':
        case 'user_login_block':
          $form['name']['#prefix'] = '&#60;div class="username-password-wrapper"&#62;';
          $form['pass']['#suffix'] = '&#60;/div&#62;';
          break;
      }
    }


Change CKEditor config.js without modifying module code? I'm using the CKEditor module and I need to adjust config.js in the module's root.  The problem is I don't want to make changes to any files part of the module because all those changes will get blasted when I do a code update.

How can I apply changes to CKEditor's config.js without modifying the module's copy of config.js?

Can you add the setting inside the Custom JavaScript configuration field of the Advanced Options for a particular profile?

There's also the ability to load your own custom config.js file in the 'Load ckeditor.config.js from the theme path' setting under the 'Advanced' section in the CKEditor profile settings.


Should I use different content types or tags? I am working on my first Drupal site and I am worried about building things that will cause me trouble down the road.

The site is a move from a custom CMS to something more manageable. I didn't build the old CMS either.

I have several items under labels like news, press release, announcements, etc. As I'm building out the content types I realize they could all be the same thing except they are considered something different by end users.

Would something like this be a candidate for separate content types or one content type and I could tag each piece of content as "news" or "press release" etc. ?

I'm hoping I can learn from someone else's mistake and get some hindsight on the topic.

I'd go for content types. That way you can easilly filter the content for the specific types when needed later.

It's easier to display all different content types at once, then to hide specific ones by their tags.


How do I correct error: Contained fields field is required in Commerce Index Filters Commerce Kickstart 2. I noticed that unpublished Products were still visible to users who are not logged in or have editing permissions.

I saw this topic: https://www.drupal.org/node/1899326 which states that one must check the 'Exclude unpublished nodes' box as well as the 'Exclude unpublished products' box in the Filters tab of

/admin/config/search/search_api/index/product_display/workflow

...but when I click 'Save' I get the error:

Contained fields field is required

...five times.

What is causing this? How do I correct?

I am not sure if you found the solution for this error, but here is what i did.

on the /admin/config/search/search_api/index/product_display/workflow, the aggragated field settings, remove the fields that you don't need or have "unchecked" on the fields tab.

Hope this helps

Karim


How to avoid "header already sent" warning when loading a pdf In drupal 7, when I load a pdf page in a new tab, and after reloading the initial page, I have this warning:

Warning : Cannot modify header information - headers already sent in invoices_callback() (line 1093 in C:\xampp\htdocs\drupal\sites\all\modules\custom_profile\custom_profile.module).
Warning : Cannot modify header information - headers already sent in drupal_send_headers() (line 1221 in C:\xampp\htdocs\drupal\includes\bootstrap.inc).

Actually, I have a link in my initial page (named 'my-account/invoices') which redirects to a PDF page named 'my-account/invoices/%invoice_number'.
This last one is loaded by a 'page callback' function :

function invoices_callback($var){
require_once('sites/all/libraries/dompdf/dompdf_config.inc.php');

$filename = 'Invoice n°' . $var . '.pdf';
$dompdf = new DOMPDF();
    $dompdf->load_html('
Test n° : ' . $var . '
');
    $dompdf->render();
    $dompdf->stream($filename, array('Attachment'=>0));
    header('Content-type: application/pdf');

}

As you see, I didn't use a pdf module, like printer, which is too heavy. I use a custom module which implement a page callback function, and inside I use dompdf library.
The pdf is displayed normally, but when I come back to initial page I have these warnings.

I have tried several things:

I removed the header function. Effect: the first warning is gone but I still have the second. It seems like the stream method of DOMPDF class wants to sent a header...
I have added a charset utf-8 to the header function
I used ob_start() and ob_end_flush() functions at the beginning and at the end of the code. Surprisingly doesn't work.
I lastly use drupal_add_http_header function. Doesn't remove warnings.

What i can do is to call a script in an external link, because my test work when i call a php script located elsewhere. But for the UX, i try to have all my scripts managed by drupal, and i want the invoices to be called by a simple alias url (my-account/invoices/%invoice_number).

So my question is simple: How to avoid these warnings without moving my script to an external location?

So, this question is very specific. The problem of 'headers already sent' warning is common, and each situation is specific, but here...

I don't need to send header-content-pdf, it is redundant, because the stream method of dompdf object sent it. So I had to erase this line.

Secondly, the most important thing is that: My code is in a page callback function, which is executed by drupal at a moment of the page generation process. After a page callback function is executed, the http headers are not sent yet, it is the job of the delivery callback function which is by default drupal_deliver_html_page. We can override this default behavior by adding in the hook_menu item the delivery callback property:

  "delivery callback": The function to call to package the result of the page callback function and send it to the browser. Defaults to drupal_deliver_html_page() unless a value is inherited from a parent menu item. Note that this function is called even if the access checks fail, so any custom delivery callback function should take that into account. See drupal_deliver_html_page() for an example.

Implementing our custom delivery callback function should work... But I didn't try it... Because, in my research, i found this function: drupal_exit()

  Performs end-of-request tasks.
  In some cases page requests need to end without calling drupal_page_footer(). In these cases, call drupal_exit() instead. There should rarely be a reason to call exit instead of drupal_exit();

But here, for me there is a reason to end the request roughly: The stream method of the dompdf object render the page as i want, ie a pdf page. So to be clear, here is my new code:

function invoices_callback($var){
require_once('sites/all/libraries/dompdf/dompdf_config.inc.php');

$filename = 'Invoice n°' . $var . '.pdf';
$dompdf = new DOMPDF();
$dompdf->load_html('
Test n° : ' . $var . '
');
$dompdf->render();
$dompdf->stream($filename, array('Attachment'=>0));
drupal_exit();

}

The stream method sends the http header and renders the page, we don't need anything else, so we exit. It takes me a lot of time, i know how drupal generates a page now. Hope this helps.


How to merge two different pages on one page I am using profile 2 module to manage users profile related information.
so far I am having two tabs

My Accounts
Customize the tabs takes me to two different URLs i.e
(mydomain.com/users/user-name/edit/Customize)(mydomain.com/users/user-name/edit/MyAccounts)

My question is,
can I make this into one tab and make these two different pages to display in one single page?

Thanks alot

Hide the tab on the user account page.

function MY_MODULE_menu_alter(&$items) {
  $items['user/%user_category/edit/profile']['access callback'] = FALSE;
}

Then, merge the profile2 form with the user account form itself :

/**
 * Implements hook_form_FORM_ID_alter() for the user edit form.
 */
function MY_MODULE_form_user_profile_form_alter(&$form, &$form_state) {
  if (($type = profile2_get_types('profile')) && $type->userCategory) {
    if (empty($form_state['profiles'])) {
      $profile = profile2_load_by_user($form['#user'], 'profile');
      if (empty($profile)) {
        $profile = profile_create(array('type' => 'profile', 'uid' => $form['#user']->uid));
      }
      $form_state['profiles'][$profile->type] = $profile;
    }
    profile2_attach_form($form, $form_state);
  }
}

From http://www.jide.fr/english/add-profile2-form-directly-on-the-user-edit-form


How to redirect before page processing along with all the sent data? I have a link on my Drupal page. This link points to the page "\node\23423". When user clicks on this link, the user should get redirect to another path "\node\45644".

But this should happen before Drupal starts processing the original path. Also any POST data that is being sent to the original page should be passed to the next redirect page.

Is there a possible way to do this?

My suggestion (experimental) is something like this (but NOT RECOMMENDED):

function MY_THEME_preprocess_page(&$variables) {
  if(arg(0) == 'node' && is_numeric(arg(1))) {
    $nid = arg(1);
    if($nid == '23423') {
      drupal_goto('node\45644');
    }
  }
}

function MY_THEME_node_view($node, $view_mode, $langcode) {
  if($node->nid == 45644) {
    $old_node = node_load(23423);
    $old_node_view = node_view($old_node);

    $node->content['body'] = $old_node_view['body'];
  }
}


8 - How to programmatically add terms to an existing Node After loading a node with Node::load with an existing taxonomy field abc do I add a new term and save? Something like?

  $term = Term::load(123);
  $node->get('abc')->appendItem($term );

This is the correct long form, as in the comment of mradcliffe:

$node->get('abc')->appendItem(['target_id' => 123]);

You don't need to load the term, use the term id.

You can use shorter versions:

$node->abc->appendItem(['target_id' => 123]);
$node->abc[] = ['target_id' => 123];
$node->abc[] = '123';


Unable to import due to "Field 'sourceid2' doesn't have a default value" I am using the awesome module Migrate, but I have problem, which I am unable to solve. I try to migrate articles from custom PHP site with MySQL DB to D7 with MySQL. The generated SQL query from my migration is ok when I run it in my MySQL DB using MySQL CLI. But when I try to migrate it using the Migrate UI, I get an error:

  An AJAX HTTP error occurred. HTTP Result Code: 500 Debugging
  information follows. Path: /batch?id=113&op=do StatusText: Service
  unavailable (with message) ResponseText: PDOException:
  SQLSTATE[HY000]: General error: 1364 Field 'sourceid2' doesn't have a
  default value: INSERT INTO {migrate_map_geografbgarticlenode}
  (sourceid1, needs_update, rollback_action, hash) VALUES
  (:db_insert_placeholder_0, :db_insert_placeholder_1,
  :db_insert_placeholder_2, :db_insert_placeholder_3); Array (
  [:db_insert_placeholder_0] => 2 [:db_insert_placeholder_1] => 3
  [:db_insert_placeholder_2] => 0 [:db_insert_placeholder_3] => ) in
  MigrateSQLMap->saveIDMapping() (line 434 of
  ~/drupal/dev/sites/all/modules/migrate/plugins/sources/sqlmap.inc).

It seems the problem is with my MigrateSQLMap function, looks like N.id is NULL when the query is run by Drupal. But I triple checked it before posting, it's not nullable field in DB and in the generate query result. Any idea how can I fix it?

$query = Database::getConnection('default', 'legacy')
      ->select('news', 'N')
      ->fields('N', array('id', 'category_id', 'createdon', 'updatedon', 'createdby', 'updatedby'))
      ->fields('L', array('code'))
      ->fields('NT', array('name', 'short_description', 'description'))
      ->fields('G', array('id', 'description'));
    $query->leftJoin('news_translations', 'NT', 'NT.target_id = N.id');
    $query->leftJoin('languages', 'L', 'NT.language_id = L.id');
    $query->leftJoin('tags', 'T', 'T.news_id = N.id');
    $query->leftJoin('gallery', 'G', 'G.target_id = N.id');
    $query->addExpression('GROUP_CONCAT(LOWER(T.tag))', 'tags');
    $query->groupBy('N.id');
    $query->orderBy('N.id', 'ASC');

    $this->source = new MigrateSourceSQL($query);
    $this->destination = new MigrateDestinationNode('article');

    $this->map = new MigrateSQLMap($this->machineName,
        array(
          'id' => array(
            'type' => 'int',
            'unsigned' => TRUE,
            'not null' => TRUE,
            'description' => t('Article Source ID'),
            'alias' => 'N',
          ),
        ),
        MigrateDestinationNode::getKeySchema()
      );

    //... not relevant

Ok, I resolved this issue. I am new to Migrate module and I think the message was not clear enough.

First I have mapped to complex foreign key with two columns:

<?php
    $this->map = new MigrateSQLMap($this->machineName,
        array(
          'id' => array(
            'type' => 'int',
            'description' => t('Article Source ID'),
            'alias' => 'N',
          ),
          'id2' => array( // no longer exists in my code
            'type' => 'int',
            'description' => t('Article Source ID'),
            'alias' => 'N',
          ),
        ),
        MigrateDestinationNode::getKeySchema()
      );
?>

But then I used only the first foreign key. The database table storing the mapping between source and destination had two columns sourceId, because of first attempt to run migration, but hasn't updated with the new migration in the code.

I dropped the migration_map table and everything was freshly rebuild and works like a charm.


filter fields of type date with the view module filters I have a field in my database of type: timestamp in this format: yyyy-mm-dd hh:mm:ss , with the view module I would like to filter this field so for example I want to select an interval: dispaly only date from x to y. I taked a look in the view module code and there is a date filter that handel data of type date or time in this format, but when I tired to create a new view with view module and set up this kind of filter I didnt found it in the exposed filter list, the availble filters works only with int or string type: like is equal to, starts with...so how to get the time filter from the view module user interface.

You need to enable the Date Views module (part of the Date project) to be able to filter using interval operators such as "Is between":

Take a look at the upvoted answer to this question for details: How do I add a date field that can be filtered by a relative value?


Store Products and Store Orders issues of Commerce_marketplace module I want to create a marketplace site(where multiple merchants/ stores will add their products to our site.) using Drupal Commerce and commerce_marketplace module. But i am having issues with this. Store owner is unable to find his/her added products.

Is there alternative way to do this.

If you go to user/%/store(or by clicking the stores tab in your user page), you will be able to see the stores of the particular user. On clicking the store name, you will be re-directed to a page commerce_store/store/%storeid.
In this page, there will be diffrerent tabs View, Edit, Delete, "Storename"'s products, Memebers and Sales tab.

On clicking the tab "Storename"'s products, you will be able to see the products added to your store.

Also please double check that you have enabled correct permissions.

One thing though, admin will not be able to see the products of another user via the above method. He will have to naviagate to structure->Entity type -> commerce store ->store and click on a particular store name to view that store's details.

Let me know how that goes.


Programatically adding new CKeditor instance What is the trick to ckeditor in D8? It's woefully under documented and CKEDITOR / CKEDITOR.instances seemingly return nothing, despite showing multiple instances of ckeditor instances available. CKEDITOR.replace() seems to give a config error (missing 404 js files) when you try to target an element.

I can target and get data back for CKEDITOR.dom.element.get('edit-comment-body-0-value') but once try to use getEditor(), it automatically returns NULL.

You're not supposed to use the CKEditor API directly. You could do that if you want to use CKEditor on something you control. But your DOM ID (edit-comment-body-0) indicates you're trying to do this for a "Formatted text" field in Drupal 8, which uses the filter system.
If you'd want to attach CKEditor manually, use the JS API provided by core/modules/editor/js/editor.js.

The integration between Drupal 8 and CKEditor is very solid/deep, in that Drupal 8 automatically configures CKEditor to match the text format's filter settings. And that integration is not tightly coupled to CKEditor: there's the Text Editor (editor) module that allows any text editor to integrate in a similarly deep way. But it means you should always use the APIs that editor provides.

For API docs, see:

https://www.drupal.org/developing/api/8/editor
https://www.drupal.org/developing/api/8/ckeditor
https://www.drupal.org/developing/api/8/filter

For the concrete relevant code, see TextFormat, editor_element_info_alter() and \Drupal\Editor\Element::preRenderTextFormat.


D7 Search Form Template override Ok so this is my first D7 project. Im stuck with the Search Block. First there is no way of customizing the search form block template to make the the search form input field and button inline to be displayed in one row. Ok i can live with that. But i cant live with not at all being able to overwrite the search result template. Neither does the preprocess_search_results() work nor do i find a way to overwrite the template for the search results. All i find is suggestions for D6 which all do not work.

Can please somebody tell me how to override theses templates and i am not talking about the form_ hooks like form_alter. I do not want to design forms by endless PHP Arrays. I want to template.

Thanks

Go to /modules/search/ to find the templates you want to override. Copy/paste them to the 'template' folder inside your 'theme' folder. Make sure you clear the caches so Drupal knows what you have done. Thats all there is to it.


Show all the upload fields Is there any way to show all the upload fields on a node?
Right now a user has to upload a single file and then get another field and so forth. Instead I would like to show the max number of permitted upload fields.

The add another option only appear if you choose unlimited in field settings.
If you choose an exact number say 5, it will display 5 image upload fields always.
Its the default property.


How to set the default language in code? I want to set the default language during install to something other than English.
How?

A profile install hook that enables and sets Swedish.

/**
 * Implements hook_install().
 */
function hook_install() {
  // Enable swedish.
  locale_add_language('sv');
  $languages = language_list();
  variable_set('language_default', $languages['sv']);
}

Since language_default is a variable, it could also be Strongarm managed.


Can't Update Contrib Modules via Admin UI I'm having a problem with a new Drupal site I'm working on.  I installed Drupal 7.36 and am able to install contributed modules via the admin UI and Drush.  However, I cannot update any contributed modules via the admin UI.  I can update via Drush however.

The error I'm getting is as follows.

  An AJAX HTTP error occurred. HTTP Result Code: 500 Debugging
  information follows. Path: /wcbvi/batch?id=9&op=do StatusText:
  Internal Server Error ResponseText:

I'm running Ubuntu Server 14.04.2 (32-bit) in VirtualBox with Apache 2.4.7 and PHP 5.5.9.  I've also installed Curl, Composer, and Drush.

No guarantee it will help, but I think it's worth trying (inspired by some of the suggestions in this comment in issue nr 1022558):

Increase the php memory limits by editing the following lines in the php.ini file as:

max_execution_time = 30 --> 60 ;
memory_limit = 32 --> 128, or even 256M ;

Add the following lines to the end of .htaccess file:

php_value auto_append_file none
php_value memory_limit 128M


Can I OR views filter criteria I'm sure this should be simple and I'm missing something because I'm tired on a Friday afternoon.

I have a Content Type (which I didn't design!) with fields "Start Date" and "Start Month". I want to show items in the View if EITHER "Start Date" OR "Start Month" are non-empty. However it seems that multiple Filter Criteria in the View are AND-ed ?

Any help much appreciated.

Thanks,

MB

You can simply create new filter group and OR them. Just use And/Or, Rearrange from drop-down Filter criteria. Use filter groups as per your needs. Hope this helps.


Need to change node's path to CCK value I have a content type that has been turned into a Feature named "Earth News".  It includes an optional CCK field called "Source URL".  When that CCK field is not blank I want the site visitor to be able to click on the teaser and go straight to that URL.

I've added the following preprocess function to the .module file for this feature:

function earth_news_preprocess_node(&$vars) {
  $path = drupal_lookup_path('alias','node/' . $vars['nid']);
  $url = $vars['node']->field_se_news_source['und'][0]['url'];

  path_save(array($path,$url));
}

The path_save is throwing a fatal error:

Only variables can be passed by reference

Am I on the right path?  What's that error all about?

Thanks.

I think what you should be doing is something along the lines of the following:

  $node=$vars['node']; // or however you get the node object

  $source = 'node/' . $node->nid;
  $alias = $node->field_se_news_source['und'][0]['url'];

  if (!empty($alias) {
    $paths=array('source' => $source, 'alias' => $alias);
    path_save($paths);
  }

but I would do in it hook_node_presave() instead.

Also be aware that I imagine this won't work if the url in your CCK field is not local to the host system.

More info:

http://api.drupal.org/api/drupal/modules%21node%21node.api.php/function/hook_node_presave/7

http://api.drupal.org/api/drupal/includes!path.inc/function/path_save/7

And oh, the error is because you were passing path_save() the return value of the array() constructor and not an actual variable.


Display specific profile type in Views Hi I'm trying to setup a View with the following criteria.

Select style: 1) Yellow 2) Green 3) Blue

I created an exposed filter for that. Easy so far.

I have created a Color content type that contains each color style in a different View Mode. Let's say the user picks Yellow. Now i want all the Color nodes to be displayed with only the Yellow View Mode.

It's probably a simple solution but i can't figure it out. Thanks in advance!

Add a filter on the relevant "style-field".
Change it's settings to be "Exposed"

And that's all you need. See Taming the beast: Learn Views with NodeOne for a good intro to the Views module.


change entityform value via function before save I have an entityform with a field call "IP" (field_ip is its machine name). Now I need to set a value before that the entityform is saved. I have thinked to use hook_entity_presave() in this way:

function mymodule_entity_presave($entity, $type) {
      if ($type == 'entityform') {
        if ($entity->is_new === true || 1==1) {
          $entity->field_ip = array('LANGUAGE_NONE' => array(0 => array('value' => $_SERVER["REMOTE_ADDR"],'format' => '','safe_value' => $_SERVER["REMOTE_ADDR"])));
          $entity->original->field_ip = $entity->field_ip;   //Try this, too.
        };
      }
    }

(1==1 is only for test/debug).

Via "devel" module I can see that the new value of field_ip is correctly set, but when I see the new version of the entityform entry (after the save action) I see the default value of that field and not my new value.
And infact if I re-edit the same entyform (id) I see the old value and not the new one. Where is my error ?

OK I now see what the problem is. LANGUAGE_NONE should not have quotes around it. It's a constant. Been there, done that. :)


How to programmatically add a link to an image field in a view I have a view with an image field and other fields, and I need to link the rendered image, not the content which is one of the configuration choice, but on another computed filtered view.
I think that I should use my_theme_preprocess_views_view_field_myviewname to catch this field, using it's name as selector then wrap it with the computed link, but didn't find how to do it.

To clarify my question, the image in this view is normally displayed, and I "dynamically" create a link to another view which is not related to the image. I wrote a function (in my template) to compute this link, and I need to know how to add this link to the image field within my_theme_preprocess_views_view_field_myviewname(&vars).
The preprocess function is executed several times to build the view, I tried to use var_dump(vars) to see where is the image field, but it generates a too huge amount of data.

As per your question, I assume that you want the image link to open the image in existing/new tab. For this you can add a relationship of 'File Usage : File'.Post that you get the file path field in the fields section of the view.
Add that file path field and in the rewrite result section or in template file you can create  tag with the required image.
PS: In field image setting select noting in link image to setting.


Edit content before publishing How do I give an authenticate user the permission to edit some contents before publishing it. So currently he has the permission to edit it, but he has to publish it first and then he gets the edit button. I tried going to the edit url which is node/nid/edit, but it didn't work before publishing the content.

Any help?

I think you need try this module: Workflow


Drupal 7 Remove field suffix from search index On my Drupal 7 installation I have many different custom fields with different suffixes. Drupal inserts the suffixes into the search_index table which I need to avoid. I could change the output, so that the suffixes are hardcoded on the template side and only shown if the specific fields are printed, but I don't like this solution.

Is there any other way to tell Drupal which fields to add to search_index and which fields to skip? Any hook I could use?

I'm not sure if I really want to use the Search API Module...

You can exclude fields from being added to the search index under the settings for you content type.

Go to the settings for you content type and Manage display. Click on the view mode Search index and drag the fields you don't want to index to Hidden.


Drupal database connection Is it necessary to connect to drupal database in order to fetch something from database? OR no if I have drupal installed so no need to make connection in any template file in order to fetch data?

The database connection is handled elsewhere, you do not need to write a new connection function in your template file.

You can use this:
https://api.drupal.org/api/drupal/includes!database!database.inc/function/db_query/7


Assign user survey created by webform I've created a survey using the webform module. I now want to assign a set of users to take the survey. Does anyone have any recommendation on how I should go about doing this.

Create a Role and assign set of users to that Role. Now go to your Webform configuration settings (Form Settings) >> Submission Access and assign newly created role to it.

For example in the following example I've created a 'moderator' rule and assigned users (those I want to assign users to take survey).

That's it. Now users under "Moderator" role only can access the form.


How do I update an entity? I have defined my own entity: 'game'; created some 'games' with entity_create; and loaded one of these 'games' into a form for editing. Now, I want to update the entity with my submit handler. Here is the relevant code inside the handler:

$game = entity_load_single('game', $form_state['values']['game_id']);
$wrapper = entity_metadata_wrapper('game', $game);
$wrapper->some_property->set($form_state['values']['some_value']);
$wrapper->save();

This throws:

  Error

  EntityMetadataWrapperException: Entity property some_property doesn't
  support writing. in EntityStructureWrapper->setProperty() (line 493 of
  /.../sites/all/modules/contrib/entity/includes/entity.wrapper.inc).

I was looking for a function like entity_update, but it doesn't seem to exist. How can I update my 'game' entities? Thanks.

You're probably looking for entity_save().

If you want to use a metadata wrapper for a custom entity properties you need to implement hook_entity_property_info() to describe them to the entity module, especially setter callbacks which are used to set the value of the property.


How to show Taxonomy menu on Page View? I would like to show Taxonomy menu on Page view ,so i could select different taxonomy terms to show related items with it.It has to exactly like following  link www.techmusicschool.co.uk/courses/index.php

I used Quick tab module to made taxonomy terms as tabs then i have created different views for each tabs and yes its working ...Thanks..


How to add multiple panel nodes to a panel page What I need to achieve is essentially a panel page of panel nodes.

I have contact information for various divisions of a company. Then I used panel node to override the layout of these nodes. Now I need to maintain that layout and add them to a panel page or view.

Any help is much appreciated. Thank you in advance.

Panel nodes was once totally awesome.

They could only do so much though, largely because of limitations in the underlying nodes.

With D7, Panelizer can what panel nodes could, but on any entity. I would strongly recommend you switch to panelize. Not only will you be able to easily use any regular method to list, but panel nodes have effectively been abandoned for years now.


How to determine the route for the add node page of a custom entity type? I have a node type question that I want users to be able to create rapidly.  So, after adding a question, I want them to be redirected to /node/add/question to immediately do it again.
This is my code so far:
function MYMODULE_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  switch ($form_id) {
    case 'node_question_form':
      foreach (array_keys($form['actions']) as $action) {
        if ($action != 'preview' && isset($form['actions'][$action]['#type']) && $form['actions'][$action]['#type'] === 'submit') {
          $form['actions'][$action]['#submit'][] = 'MYMODULE_node_form_submit';
        }
      }
      break;
  }
}

function MYMODULE_node_form_submit(array &$form, FormStateInterface &$form_state) {
  // https://drupal.stackexchange.com/a/250474/5147
  \Drupal::request()->query->remove('destination');
  $form_state->setRedirect('node.add_page');
}

This redirects to /node/add, but I want to redirect to /node/add/question.  I tried digging through the route options in PHPStorm but I couldn't find anything that gets to the create page for a custom content type.

You're looking for the node.add route, which has a node_type parameter.
$form_state->setRedirect('node.add', ['node_type' => 'question']);