How to duplicate a node into an external database in Drupal 8 What I am trying to do is to save a copy of a node object after it is inserted into another Drupal database.

As it can be seen in the following piece of code, my idea is to change the database after a node is inserted. Make a copy of the node and save it. Then, return to the default database.

However, seems like entity storage manager is set to default database in node save function. Therefore, the node is getting saved inside the default database again.

//... mymodule_node_insert

$node = Node::load($id);
\Drupal\Core\Database\Database::setActiveConnection('external');
$db = \Drupal\Core\Database\Database::getConnection();

// save the node in the shared database
// Create node object with attached file.
$sharedNode = Node::create([
    'type'        => $node->getType();,
    'title'       => $node->getTitle();,
    'body_text'   => $node->get('body')->value,
]);
$sharedNode->save();

\Drupal\Core\Database\Database::setActiveConnection();

How can I make this work? Am I following a correct logic?

Any helps would be appreciated.
Thanks

This seems similar to Database::setActiveConnection not working as expected?. Perhaps the Node object you've instantiated before switching the connection is still going to hold on to the old db settings as the source to save.

The DatabaseSwitcher class (found in the above posted question, just under the accepted answer by the original poster) may be an effective way for you to switch the container context in a way that will allow your already instantiated Node object to save in your external DB:

//... mymodule_node_insert

$node = Node::load($id);
$db_switcher = new DatabaseSwitcher();
$db_switcher->changeToDifferentDb('external');

// save the node in the shared database
// Create node object with attached file.
$sharedNode = Node::create([
    'type'        => $node->getType();,
    'title'       => $node->getTitle();,
    'body_text'   => $node->get('body')->value,
]);
$sharedNode->save();

$db_switcher->changeToDefaultDb();

Hope this works for you!


Move menu code to the template.php with the associate hook I have created a region (called menuCustom) .info file in my template, I created a custom menu and I'm showing in the previously created region.

I created a file called block--menuCustom.tpl.php to show it as a block.

My question:
How I can move code from the .tpl file to the file template.php?

I have managed to show the links with the structure needed with the following code:

<?php
    $contenidoDesple = $elements['#content'];

    $templateMenu = '
';

    foreach ($contenidoDesple as $key => $item) {

        if ($key != '#sorted' && $key != '#theme_wrappers') {

            $enlace = $contenidoDesple[$key]['#href'];
            $nombreEnlace = $contenidoDesple[$key]['#title'];

            $templateMenu .= '
';
            $templateMenu .= '' . $nombreEnlace . '';

            if (count($contenidoDesple[$key]['#below']) != 0) {

                $templateMenu .= '
';

                foreach ($contenidoDesple[$key]['#below'] as $newKey => $newItem) {

                    if ($newKey != '#sorted' && $newKey != '#theme_wrappers') {
                        $enlace2 = $contenidoDesple[$key]['#below'][$newKey]['#href'];
                        $nombreEnlace2 = $contenidoDesple[$key]['#below'][$newKey]['#title'];

                        $templateMenu .= '
';
                        $templateMenu .= '' . $nombreEnlace2 . '
';
                }
            }

            $templateMenu .= "
";

        }

        $templateMenu .= "
";

    }

}
$templateMenu .= "
";

print $templateMenu;

?>

You can add your code to custom module as custom block:

/**
 * Implements hook_block_info().
 */
function custom_block_block_info() {
  $blocks = array();
  $blocks['my_block'] = array(
    'info' => t('My Custom Block'),
  );
  return $blocks;
}
/**
 * Implements hook_block_view().
 */
function custom_block_block_view($delta = '') {
  $block = array();
  switch($delta) {
    case 'my_block' :
      $block['content'] = my_block_view();
      break;
  }
  return $block;
}

/**
 * Custom function to assemble renderable array for block content.
 */
function my_block_view() {
  $output = '';
  $menu_array = menu_tree_all_data('main-menu');
  // Prepare your $output variable from $menu_array (like in your code).
  $block = array(
    'menu' => array(
      '#type' => 'markup',
      '#markup' => $output,
    )
  );
  return $block;
}

Then show this block in created region.


Adding Information to Maintenance mode message I'm trying to setup my maintenance mode message so that it will display a twitter feed and a facebook like box to my sites facebook page. I want to do this so I have a place to send information to the people who need it or want to keep up to date while I do something that could have the site in maintenance for an extended period of time. I'm just wondering how I would set that up and if it's possible in the default maintenance mode settings of if I have to do something else, like a separate page or module.

If you just wanted to add some text I'd say go into the admin settings of /admin/config/development/maintenance and update the text but if you want to add dynamic code like a facebook Iframe like button you're probably better off adding the code to a custom maintenance-page.tpl.php in your theme. Grab the code from Facebook and twitter and paste.

Just add it below the line that reads

<?php print $content; ?>

Drupal api reference - https://api.drupal.org/api/drupal/modules!system!maintenance-page.tpl.php/7


How to make menu link show for certain roles? I want to add "Login" and "Logout" to the same menu but only for the right role. In previous versions of Drupal, you would just add /user/login and /user/logout to a menu and it would only render one or the other based on if they actually were logged in or not.

However in D8, it looks like the Logout link shows regardless... is there a way to replicate this without creating multiple menus?

In D8 this is a menu link class, which you can add to a menu in *.links.menu.yml:

mymodule.links.menu.yml

mymodule.logout:
  weight: 10
  menu_name: mymenu
  class: Drupal\user\Plugin\Menu\LoginLogoutMenuLink

This class shows Log in or Log out for user roles authenticated or not:

  public function getTitle() {
    if ($this->currentUser->isAuthenticated()) {
      return $this->t('Log out');
    }
    else {
      return $this->t('Log in');
    }
  }

and links it to the corresponding route:

  public function getRouteName() {
    if ($this->currentUser->isAuthenticated()) {
      return 'user.logout';
    }
    else {
      return 'user.login';
    }
  }


How to change the output of a multiple image field for a node? I have a content type (called Gallery)  with a image field  (called field_gallery) which allows to upload and show 10 images.

Now I create a node and upload the images. The output shows those images wrapped with a div tag. Like:

Instead of this I need it to be something like:

How can I accomplish this. Should I use an alter function? How?
thanks

You can overwrite the field output template, e.g. field--field-name.tpl.php, or a module template, if that's the case. See http://drupal.org/node/1089656.
You can overwrite the node template for this content type (node--type.tpl.php). Type in
<?php print_r($node); ?>
 to find the element you want. For template information, see http://drupal.org/node/1089656.
You can create a page in Views.


Implementing a secure confirmation page for an entity form (D8) I have a custom entity that is used for user submissions. Anonymous users will be able to submit confidential information using the entity add form. After submission I want to show some kind of confirmation page (Thank you for submitting etc.), but I'm not sure what is the best way to achieve this. The user should also receive a similar confirmation by email.

I was thinking of simply adding a view mode confirmation to the entity and have the form redirect to that page on submit, but I am concerned about access control here: visitors would be able to view other user's submissions, if they simply try random entity ids. Is there a way to restrict access to visitors who just submitted the form?

In drupal there are several way to do the same thing.
What I suggest in this case (certainly different for another person) use a small custom module with Cookies or Session.

Create a custom module.
Add an extra submitter.

Save the new USER ID on session, cookie ...
Redirect to the page (Ex : $form_state->setRedirect('your.module.route.name');)

Create a small dynamic custom page (Like : http://www.drupal8.ovh/en/tutoriels/5/create-a-simple-module-for-drupal-8-step-2-create-simple-page)

Get the USER ID from session, cookie ...

You can change the confirmation mail template from back office.


Is there a tpl.php file generated by Drupal 7 for custom content types I seem to remember it being mentioned somewhere in the past that when you create a new content type in Drupal 7 that there is a corresponding node--[content-type].tpl.php file created somewhere by Drupal core. I may be wrong. However, if there is such a file created, how do I find it so I can copy it in to my theme?

Maybe it defaults to the node.tpl.php file, but I thought a new file for the custom content was created. Just don't know where to find it if it is created.

TIA

No; Drupal doesn't ever create template files dynamically.

For new content types the default node.tpl.php, or the one provided by the enabled theme, will be used.


How can I add a progress bar to Managed File upload? How can I add a progress bar to my Managed File form field? Here's my field code:

    $form['file'] = array(
  '#type' => 'managed_file',
  '#title' => t('Logo image'),
  '#description' => t('Replace/upload a new logo for this sponsor.'),
  '#upload_location' => 'public://',
  '#upload_validators' => array(
    'file_validate_extensions' => array('gif png jpg jpeg'),
  ),
);

I have searched for a while now, and the closest info I could find was this post but I can't quite figure out how I can add the AJAX to make this happen. Any pointers would be appreciated!

managed_file fapi elements are already progress bar capable by default.

managed_file

  Description: Provides a complete ajax/progress aware widget for
  uploading a file and saving it to the {file_managed} table.

  By default a simple upload button is provided for choosing the file to
  upload. Once a file has been chosen it can be explicitly uploaded via
  the "Upload" button. The upload is via AJAX and a progress meter is
  displayed.
  ....

  Non-standard form element properties:

  #progress_indicator: options are 'none', 'bar', and 'throbber', default is 'throbber'.
  #progress_message: (string) Progress message to display along with progress meter while a file is being uploaded. Defaults to NULL.

It may be possible that your server doesn't support file progress, in which case you should check and verify if the server settings are correct.

More info:

https://drupal.org/node/793262
https://drupal.org/node/793264
https://drupal.org/node/654732


How to change the default images path and direct it to the external directory I just want to know if there is anyway set drupal to upload images to the directory outside the drupal installation like loc*lhost/site-name/image-upload/... rather than
loc*lhost/site-name/drupal/sites/all/default/.... My drupal installation directory is loc*lhost/site-name/drupal/

Thank you
JOnas

Use Private File System, go to admin/config/media/file-system and provide the private file system path. After saving it, select  Private local files served by Drupal as Default download method. After that edit your image field and choose Private Files as Upload Destination

Note : It should be writable by Drupal and not accessible over the web.


Installing on IIS 7/Windows Server 2008 R2/MSSQL 2008 I am having difficulty connecting to my MSSQL database (locally installed) while proceeding through the Drupal Install. I do not get any errors during the Verify Requirements portion, but not matter what info I put into the Database configuration page, it cannot connect. It does not throw an error like "phpmssql library missing"

This is what I have installed so far.

Windows 2008 Server R2
Internet Information Server IIS 7.5
SQL Server 10.0
Microsoft Drivers for PHP for SQL Server 3.2
php-5.6.21-nts-Win32-VC11-x86
php_pdo_sql_srv_56_nts.dll
php_wincache-1.3.7.9-5.6-nts-vc11-x86
sqlsrv-8.x-1.x-dev
wincachedrupal-7.x-1.10

Should I be putting something besides "localhost" and "1433" in the "Advanced Options" panel?

Thanks in advance for any help!

phpmssql library missing

You are using the 8.x-2.x branch of the driver, that relies on a paid external library phpmssl:

http://www.drupalonwindows.com/en/content/phpmssql

You can use the "free" 8.x-1.x branch - that has no dependencies - for evaluation purposes. I say evaluation because it's a non supported half-broken branch I used to work on during the first D8 port attempt of the driver.

You can find full discussiones of this issue here:

http://www.drupalonwindows.com/en/blog/installing-drupal-8-windows

Disclaimer: I'm the maintainer for the SQL Server driver, PHP Mssql and Wincache.


Taxonomy terms with a scale? Not quite sure how I should even google this. I've got a Content Type "Trips", the image shows what I want to see in my trips node page. Adventurus, relaxing, educational etc are my taxonomy term categories. It seems to me like each taxonomy term should have a scale of 0-5. Which is the better way to achieve this? Any module around? (using drupal 7)

I used Star Rating module. Exactly what I was looking for. In contrast with Fivestar module, it is intended for rating only by the author of the node. Plus no dependencies.
[Thanks to @jimajamma]


How to configure relationships created by the User relationships module I've managed to get my UR module setup. My users can now add each other. However, the only problem am faced with is that when Alice adds Bob and Bob accepts the friend request, only Bob can see Alice's name in their current relationship list; in Alice's current relationship list Bob does not appear.

Furthermore, Alice does not get a confirmation when their friend request is accepted. How can i go about fixing this problem?

I am using Drupal 7 and the zen sub theme.

User Relationships supports bi-directional relationships unless you have checked the "This is a one-way relationship" checkbox.

However, there is a bug in the current 7.x-1.0-alpha2 version, make sure you use 7.x-1.x-dev instead.

If the Relations module works for you, fine. But the main thing that UR provides is various user interfaces to request relationships, see/administer them in listings, approve them, see your relationships with other users when visiting their profile and tons of additional modules like integration with Privatemsg.

In fact, we plan on making UR just a fancy UI on top of the Relations project, but that's quite a way to go.


Print custom field in user edit form in block Following code prints user edit form in block:

function notifikacie_custom_block_info() {
 $blocks['user_profile'] = array(
   'info' => t('User profile edit'),
   'cache' => DRUPAL_NO_CACHE,
 );

 return $blocks;
}

function notifikacie_custom_block_view($delta = '') {
  $block = array();

      global $user;
      module_load_include('inc', 'user', 'user.pages');
      $block['subject'] = t('Fill your profile');
      $block['content'] = drupal_get_form('user_profile_form', $user);

  return $block;
}

But it does not print custom fields created in admin/config/people/accounts/fields. How do I print those custom fields?

I've just run your code and it works fine. Maybe it is permission related problem.

<?php
function user_profile_block_info() {
 $blocks['user_profile'] = array(
   'info' => t('User profile edit'),
   'cache' => DRUPAL_NO_CACHE,
 );

 return $blocks;
}

function user_profile_block_view($delta = '') {
  $block = array();

      global $user;
      module_load_include('inc', 'user', 'user.pages');
      $block['subject'] = t('Fill your profile');
      $block['content'] = drupal_get_form('user_profile_form', $user);

  return $block;
}

Output/result:
Here Birth Date is custom field, created form admin/config/people/accounts/fields.


Keep getting "Bad request" messages in browser after adding JS I have added this script in my Drupal 7 site to make the site remember the last clicked Quicktab and then open that tab on page reload:

// JavaScript Document
(function($) {

    Drupal.behaviors.quicktabsTabMemory = {
      attach: function(context, settings) {
        // The .each() is in case there is more than one quicktab on a page.
        $('.quicktabs-wrapper', context).each(function () {

          var $this = $(this);
          var wrapperID = $this.attr('id');

                var nid = settings.nordtec_klister['currentNid']; // getting the nid on the client side

          var $activeTabLink = $('.quicktabs-tabs li.active a', context);
          var activeTabLinkID = $activeTabLink.attr('id');

          // Use a unique cookie namespace for each set of Quicktabs, which
          // should allow for more than one set on a page.
          var cookieName = 'Drupal-quicktabs-active-tab-id-' + wrapperID + 'nid='+ nid;
          // Default cookie options.
          var cookieOptions = {path: '/'};

          // Click the tab ID if a cookie exists otherwise set a cookie for
          // the default active tab.
          var $cookieValue = $.cookie(cookieName);
          if ($cookieValue) {
            $('#' + $cookieValue).click();
          }
          else {
            $.cookie(cookieName, activeTabLinkID, cookieOptions);
          }

          // Set the click handler for all tabs, this updates the cookie on every
          // tab click.
          $this.find('ul.quicktabs-tabs a').click(function quicktabsCookieClickHandler() {
            $activeTabLink = $this.find('.quicktabs-tabs li.active a', context);
            activeTabLinkID = $activeTabLink.attr('id');
            $.cookie(cookieName, activeTabLinkID, cookieOptions);
          });
        });
      }
    };

})(jQuery);

This works as a charm, BUT ever since I added this I keep getting this message in the browser (Chrome)...

Bad Request
Your browser sent a request that this server could not understand.
Size of a request header field exceeds server limit.

...after maybe 1 or 2 working days of browsing the site, adding and editing content (many tabs open with different pages etc). I can only assume that it's not a coincidence that those error messages began to show soon after I added this script.

So my question is: What should I do in order to avoid those messages? Clear out all cookies after a certain time? I have tried to limit the cookie life time to 28800 seconds and also the garbage collector life time to that same value in settings.php:

ini_set('session.gc_maxlifetime', 28800);
ini_set('session.cookie_lifetime', 28800);

This helped some, the messages does not occur as often after this, but they do still happen once a week or so.

Finally found the solution to my problem, in case anyone else makes the same mistake.

The problem with my cookie is this line from the code above:

var cookieName = 'Drupal-quicktabs-active-tab-id-' + wrapperID + 'nid='+ nid;

Cookie names cannot contain equal characters (or spaces, commas, semi-colons etc). That will create errors. So i simply changed "=" to "-" in my code line above, and the errors went away.


Show referenced nodes as links if they have content in a field Nodes of content type A are attached to nodes of content type B with an entity reference. Im listing Nodes of type A on Node B with a view.

Now I need the list of Node As to be links if their node's body has content. If their node's body doesnt have content then I need it to not be a link.

This can be done in Views with no PHP or templating.

Add 2 title fields, one that is a link to the content and one that isnt.

Exclude both fields from display.

Add a body field and rewrite the output of the field. Use a replacement pattern thats the node title which is a link.

Under no results behavior add the token thats the node title which isnt a link. Make sure 'Hide rewriting if empty' is not checked.


Show form after youtube video ends I am having a watch video button which shows a YouTube video in color box. I want to show a form (webform/custom form) to appear after the video ends in the same color box itself. If users fill the form and submit it, the form should disappear, showing only the video that was ended in the colorbox. I am trying to achieve it using  using the Youtube player API but not able to achieve my objective.

Is there some other way to achieve it?

That looks doable by youtube-api.

What you can do is have the form loaded already when you should the color box, with display: none on form block.

Now with help of youtube api you can detect video end and can toggle visibility to display: block;

Refer here for youtube api example:-

source https://stackoverflow.com/questions/7853904/how-to-detect-when-a-youtube-video-finishes-playing


Drupal 7 Themeing - template.tpl.php vs template.php - variables I am interested in learning what disadvantage, if any, there are in calling variable fields directly within the template.tpl.php files.

Is it ok to place a field variable within the template.tpl.php file if doing it as simply as:

<?php
//--------------------------------
// COLOR
if(!empty($content['product:title']['#product']->field_taxonomy_color['und'][0]['taxonomy_term']->name)): ?>

    <?php
        $max_length = count($content['product:title']['#product']->field_taxonomy_color['und'])-1;
        for($x = 0; $x <= $max_length; $x++){
            echo '
'. $content['product:title']['#product']->field_taxonomy_color['und'][$x]['taxonomy_term']->name .'
';
        }
    ?>

<?php endif; ?>

My understanding is that this code should be placed a preprocess function and called into the tpl.php file such as:

TEMPLATE.PHP

function theme_preprocess_node(&$variables) { $variables['color'] = ... }

TEMPLATE.TPL.PHP

<?php echo $color; ?>

If this is the case, how would i return all values of the loop from template.php into template.tpl.php?

---------EDIT---------
Should I create complex logic within its own field--template.tpl.php file, set the field to a variable in template.php and call upon the variable inside the node--template.tpl.php?  Would there be a problem with creating over a hundred field--template.tpl.php files?

The disadvantage is you leak a lot of PHP code processing Drupal inner structures to the template file.

I would preprocess $content in template.php to expose a simple array of strings as a custom variable:

$colors = $content['product:title']['#product']->field_taxonomy_color['und'];
$colorNames = Array();
for ($x = 0; $x < count($max_length); $x++) {
  $colorNames[$x] = $colors[$x]['taxonomy_term']->name;
}
$variables['color_names'] = $colorNames;

Then the template code could be:

<?php if ($color_names): ?>

  <?php foreach ($color_names as $cn)
    print '
' . $cn  . '
'; ?>

<?php endif; ?>


View comments in admin area before approval How can I view posted comments in admin area before approval?

I mean previewing comment INSIDE admin area not node's page.

Default comment administration page does not show you the entire comment. But it shows author and some other helpful information that should be helpful for most users to decide anther delete it or not.

You can replicate this form using Views and Views Bulk Operations module.

Just install both modules and create a new View on comment entity.
You can add a new page with a path like admin/content/comment2 (so you are not overriding the default page - if you want to do so, enter same path as core comment admin page).

Add necessary fields and set style as table. You can add a VBO checkbox and actions by adding a checkbox field.

There is an action "delete comment" that you can use to delete comments via VBO.
hooks will work without a problem.


Detecting a form change. Is jQuery the way to go? I have got a form with quite a lot of checkboxes (can go up to the 100's) in a table and I would like to detect if a checkbox has been clicked by the user.  If they have, I would like to automatically display a warning in the form informing the user that they need to save the form if they want the changes to take effect.  Similar to how the draggable tables in Drupal work.  Anytime, a form element changes, then, show a warning.

My question is, will using jQuery to attach a change event on each checkbox take a major performance-hit?  Is there a faster Drupal way to do it?  Will using the Drupal way, make performance faster?

Will using jQuery to attach a change event on each checkbox take a major performance-hit?

Probably, but it depends on the client's configuration. I have a form with around 3 hundred of controls, half of them hidden, some of them auto-copying content using jQuery, and sometimes FireFox has it's problems with it.

  Is there a faster Drupal way to do it?

Nope, Drupal way is to use Behaviors, or states, and Behaviors & states thou shalt use... but they are merely Drupal's way to initiate jQuery-based code.

  Will using the Drupal way, make performance faster?

Nope, as Drupal way is basically jQuery way too. But it will merely allow you to be reasonably sure that other modules will not interfere with your code (without any significant slowdown).


show uploaded image in page.tpl I created a content type and added an image filed (machine name: field_theme_image).
Then, I've added a new content in this content type and uploaded an image. Now, I want this image to be shown in "page.tpl.php", so that this can be seen in all the pages. Please let me know how this can be done done.

I would have rather used a block and put it in a region, so to show up on all pages. This would keep my tpl fiels clean and also will allow me show/hide block on some pages.


How do I update a multi-dimensional commerce product field with Views Bulk Operation? I'm converting from an old UPS module to the newer Commerce UPS. The old module used integer fields for height, length, width. The Commerce UPS module demands a multi-dimensional field 'Product_Dimensions'. So I want to update the Product_Dimensions field with the old data.

I created a View with a VBO column and I selected Execute Arbitrary PHP Script as my operation. Here is my code:

$product = commerce_product_load($entity->product_id);
$product->field_package_dimensions = array( "und" => array(0 => array( length=>"91", width=>"22", height=>"11", unit=>"in") ) );
commerce_product_save($product);
// dpm($product->field_package_dimensions);

...the product_dimensions field is being updated BUT each dimension of the array is being assigned a single character '9'. ie. the length, width and height are all '9'. So clearly there is something wrong with my array assignment?

Can someone tell me what I'm doing wrong? I'm sure it's an obvious mistake... or there is a 'proper' procedure for programmatically updating commerce product fields that I'm missing.

TIA.

For any future travelers.

This may be my ignorance but it seems like you -must- use commerce_product_load(), even thought it kinda looks like the $entity object is the same as the $product object.

$product = commerce_product_load($entity->product_id);
$product->field_package_dimensions = array( LANGUAGE_NONE => array( 0 =>
    array('length'=>  $entity->field_length['und'][0]['value'],
          'width'=>   $entity->field_width['und'][0]['value'],
          'height' => $entity->field_height['und'][0]['value'],
          'unit'=>"in") ) );
commerce_product_save($product);


How to create block with custom embed code in D7? I am trying to create a custom block with the following embed code in D7:

<form style="border:1px solid #ccc;padding:3px;text-align:center;"     action="http://tinyletter.com/pumpbeat" method="post" target="popupwindow" onsubmit="window.open('http://tinyletter.com/pumpbeat', 'popupwindow', 'scrollbars=yes,width=800,height=600');return true">

Enter your email address:

<input type="text" style="width:140px" name="emailaddress"/>

  <input type="hidden" value="1" name="embed"/>
  <input type="submit" value="Subscribe" />

A TinyLetter Email Newsletter

</form>

In D7 I go to Structure > Blocks > Add block, then paste the embed code into the Body field, and choose PhP code as the text format (I have also tried plain text and full html, without success).

However, rather than displaying the desired widget the new block displays the embed code above.

Please note that I also have the WYSIWYG module installed (with CK editor).

I would really appreciate any help in solving this problem. Thanks!

WYSIWYG editor sees this code as a normal text.You should copy this text in source(There is a source or html button in WYSIWYG toolbar) or disable rich text box and then copy it to your text area.

Also you should use drupal form api to insert forms to your pages.


How do I determine a page's content type for non-node pages? I’m trying to modify my theme’s page.tpl.php to not show certain regions when I’m displaying content from the core forum module.

<?php if (!$node->type == 'forum'): ?>

<?php print $sidebar; ?>

<?php endif; ?>

This works fine when I display actual forum nodes, but not when I show pages with the forum listings (/forum, /forum/1, etc.), since those pages aren't actually nodes.

How can I determine if a page will be a certain content type, so I can use conditional statements in page.tpl.php?

Edit: Some quick clarification. Working with $node->type is easy for pages that actually use nodes. However, when working with Views, or in the case of the forum module, the content is not node-based (it is called with forum-topic-list.tpl.php and $node is null). Because of this, it's impossible to programmatically determine if the page is really a forum (since it's not really a node). I'm trying to figure out a way around that.

Edit 2: Possible (kludgy?) solution: Putting this in theme_preprocess_page works. Is it the best way to do it though?

// Determine if page is a forum
$node = $vars['node'];
$template = $vars['template_files'][0];

if ($template == 'page-forum' || $node->type == 'forum') {
    $vars['is_forum'] = TRUE;
}

Use template_preprocess() for detecting node on page and pass additional variable as flag to template file, like:

$variables['display_region'] = TRUE;

Maybe Panels can help you too.


Unable to set field collection field value on form validation The question might look similar to How to form_alter fields attached to an unlimited field collection? but I am more concerned about "values not saved after custom validation"

I have a field collection "field_assignments" consists of:

field_check_user: A user reference field
field_assigned_booklets: An integer field
field_total_cost: A hidden field (used in validation handler for calculation)

I have content type "marking" having this field collection (unlimited values) along with a field_rate. I have alter node editing form and defined a custom validation which is working fine. The problem is that I cannot update the field collection item "field_total_cost" value in custom validation function. The validation function is

function _additional_validate($form, &$form_state) {
   // If rate is set to 100 and assigned booklets are 5; this should result 500
   $tc = $form_state['values']['field_assignments']['und'][0]
         ['field_assigned_booklets']['und'][0]['value'] * $form_state['values']['field_rate']['und'][0]['value'];

   $form_state['values']['field_assignments']['und'][0]['field_total_cost']['und'][0]['value'] = $tc;
}

If I dpm $form_state, I can see that the ['field_total_cost']['und'][0]['value'] is updated (see image below) but when the node is submitted, it does not show that value in node view and does not save that value in the database. How can I save a value in field collection field?

I tried form_set_value() but couldn't understand how to set value for compounded fields (field collection in this case, I'll be thankful if someone can show how can I construct that "#parent" stuff with these fields). The code with form_set_value() I tried:

 // testing on a single field - works perfectly
 form_set_value($form['field_rate']['und'][0]['value'], $tc, $form_state);

 // does not update the value
 form_set_value($form['field_assignments']['und'][0]['field_total_cost']['und'][0]['value'], $tc, $form_state);

P.S: I have written 'und' instead LANGUAGE_NONE for ease

Use Computed field instead of doing it yourself! Don't use _validate, just use _compute.

Change field_total_cost to a computed field, saving as decimal.
Create a custom module and add the following (much clearer than using Computed Fields settings inputs - yuk)

Do something like the following :

/**
 * Computed field for - field_total_cost
 */
function computed_field_field_total_cost_compute(&$entity_field, $entity_type, $entity, $field, $instance, $langcode, $items) {
  $tot   = 0;
  $books = 0;
  $rate  = 0;
  if (isset($entity->field_assigned_booklets[LANGUAGE_NONE][0]['value'])) {
    $books = $entity->field_assigned_booklets[LANGUAGE_NONE][0]['value'];
  }
  if (isset($entity->field_rate[LANGUAGE_NONE][0]['value'])) {
    $rate = $entity->field_rate[LANGUAGE_NONE][0]['value'];
  }
  $tot = $books * $rate;
  $entity_field[0]['value'] = number_format((float) $tot, 2, '.', '');
}

/**
 * Display for - field_total_cost
 */
function computed_field_field_total_cost_display($field, $entity_field_item, $entity_lang, $langcode, $entity) {
  return '£' . number_format($entity_field_item['value'], 2);
}

I obviously don't know what your calculations are like but you get the idea.
This will calculate and populate the Total Cost field per field collection.

OR

If you still want to do it on validate you (afaict) can't do it on node_validate but you can on a field validate. So you need to add a custom validate function to your Field Collection field, then it should work as you think.

Add a custom validate callback on hook_field_widget_form_alter

/**
 * Implements hook_field_widget_form_alter().
 */
function MYMODULE_field_widget_form_alter(&$element, &$form_state, $context) {
  // Add custom validation hooks for Field Collections.
  if ($context['field']['field_name'] == 'field_assignments') {
    array_unshift($element['#element_validate'], 'MYMODULE_field_assignments_validate');
  }
}

Create the custom validate function and set the value similar to how you suggested

/**
 * Custom validate function for field_assignments.
 *
 *  @see MYMODULE_field_widget_form_alter()
 */
function MYMODULE_field_assignments_validate($element, &$form_state, $form) {
  form_set_value($form["field_assignments"][LANGUAGE_NONE][0]['field_total_cost'], array(LANGUAGE_NONE => array(0 => array('value' => 123.456))), $form_state);
}

I obliviously left out any logic in this example, but you get the idea :)


Turn off cron and hook_cron for every module in Drupal How can I turn off cron and disable implement of hook_crons in every modules in Drupal
my site is Drupal 6
Thanks

It is a good practice to run cron on your site. You might decide upon the frequency, keep it a high value but it is necessary to run cron to keep your site in healthy state.

If you are worried about loosing the caches when cron is run, you can install Cache Lifetime Options module and set Minimum Cache Lifetime to a very high value. This will make sure that your caches are not cleared on cron runs. Then you can Expire module for your cache invalidation strategy.

If you do not want to run all the hook_cron implementations but only a selected ones then you should consider using Elysia Cron module. It lets you run cron for selected modules at selective frequences.


SSL setup on BOA 2.2.5 I am trying to use https for my website hosted using BOA 2.2.5, I am following this documentation:

http://community.aegirproject.org/content/content/administrator/post-install-configuration/using-ssl

The problem is after following the steps for Configure Your Aegir Server, I can't find the directory that it said would be created:

/var/aegir/config/ssl.d

/var/aegir/config/server_master/ssl.d

We don't recommend the built-in Aegir SSL feature (yet), as explained in BOA docs.

Anyway, on BOA/Octopus, the directory you are looking for is located in the /data/disk/USER/config/ tree.


Flush cache in case of WSOD without Drush on shared host I have installed Drupal from using build-in scripts on runcloud.io, but I have noticed that Drush is not available. They have replied:

  Sorry, it is not possible to install drush into Runcloud. Because the
  installation leads to php crash as it will erase cerain php modules

I get used to using Drush, especially when Drupal 8 website encountered an unexpected error, without this option I don't see the way how to clear the cache without UI, restore from backup etc.

Are there any other options to rebuild caches without Drush to recover the website from an unexpected error?

I get used to using Drush, especially when Drupal 8 website
  encountered an unexpected error, without this option I don't see the
  way how to clear the cache without UI.

Run www.mysite.com/update.php. This clears the cache, even when no updates are to run.

If you don't have access set $settings['update_free_access'] = TRUE; temporarily in settings.php.


Can I aggregate all stylesheets core, contrib and custom into one single stylesheet? Is there any way to avoid Drupal from serving multiple stylesheets and instead bundle them together? I am going to look into https://www.drupal.org/project/webpack

I want to avoid all the multiple @imports if possible that get created by the modules. Reason I want to do this is I am archiving my site with wget and I want to have less stylesheet links to monitor.

Enable aggregation of css by going to admin/config/development/performance

This is the best Drupal 7 can do without the need for any contrib module

You can also try Advanced CSS/JS Aggregation which gives some more advanced aggregation.


HTML is being printed in the output The output from the below code is printing HTML. How can I make the "p" tags disappear?

answer 1

{% block paragraph %}

    {% block content %}

{{ content.field_accordion_title.0}}

      {% for grid_item in paragraph.field_accordion %}
        <button class="accordion">{{ grid_item.entity.field_accordion_list_item_headin.value }}</button>

        {{ grid_item.entity.field_accordion_list_item_text.value }}

      {% endfor %}
    {% endblock %}

{% endblock paragraph %}

Note:  I don't want to trim the HTML tags but actually render them. Perhaps drupal_entity() will help to render the output of {{ grid_item.entity.field_accordion_list_item_text.value }}. How can this be done?
Note: I don't want to trim the HTML tags but actually render them. Perhaps drupal_entity() will help to render the output of {{ grid_item.entity.field_accordion_list_item_text.value }}. How can this be done?

Try
{{ grid_item.entity.field_accordion_list_item_text.processed }} instead of {{ grid_item.entity.field_accordion_list_item_text.value }}
i.e. replace value with processed


Missing Fields When Adding Content When going to node/add/my-content-type there is only a field for editing the title. There are body and FileFields attached to this content type but they are not being displayed until after I click save.

The content type is an OG content type though I am not sure this has anything to do with the issue. I tried toggling strict node access but it didn't help.

Preview is disabled.

I disabled the Organic Groups Field Access module and the missing fields appeared.

Related to the OG issue: https://drupal.org/node/1743332

In summary, for some users, disabling/re-enabling this module while clearing the cache resolved the issue.


Display nested relationships on a single view Context

I have three custom node types (Batch, Item, Order) that I use to track orders (I don't need the power of full-blown Commerce). These are linked through the following entity reference fields:

Batch->Item through field_items on Batch

Order->Item through field_items on Order

I have a table view set up which shows Items by Batch.

The Question

Is there a way I can display, on the same view, the Order name (if any) that each Item is allocated to?

Okay, so I've largely solved this one as follows:

The View is set to a table showing content of type Batch
I've added two relationships. The first is to items referenced by the content which are of type = Item (and which does not use any relationship). The second is to items having a reference to the content, are of type Order, and use the first relationship
I've then added fields from all three content types (using the appropriate relationships) to create the flat table I'm looking for.


getting error from path breadcrumbs I have some breadcrumbs created with Path Breadcrumbs, and they used to work on an old site. I transfered them over (using the Configuration Manager module) and now they don't show and instead print out the following error:

  Warning: implode(): Invalid arguments passed in _path_breadcrumbs_build_breadcrumbs() (line 107 of /var/www/mca-marines.org/htdocs/sites/all/modules/path_breadcrumbs/path_breadcrumbs.module).

Why should have happened?

EDIT:
I just tried to create a new one, that didn't work either, so its not as if the other ones got corrupted.

Try changing the following:

<?php
print theme('breadcumb', $breadcrumb);
?>

to:

<?php
print $breadcrumb;
?>

in your page.tpl.php

Source: https://drupal.org/node/481704


Right way to create Yes/No boolean fields I want to add fields in my node which will contain boolean values only : Yes/No. Selecting boolean as field type will cause the field to show up as single check box and in the node edit form I've difficulty in locating boolean type field.

Currently I'm using List(Text) and giving values as 1|Yes & 0|No.

What is the right way to use boolean values?

As follows:

Field type: List (integer) & Widget: Check boxes/radio buttons
Values: 1|Yes
Number of values: unlimited

See drupal.org


ThemeKey: Use main theme for Node/edit and user/edit By default, Drupal uses the "main theme" for the main site, and the "admin theme" for the admin pages.

I want to use my "main theme" for the user/edit pages and node/edit & node/add pages of the "journal" content type only.
For all other administration pages (including the node/edit & node/add pages of other content types) , I want to use the "admin theme".

How can I do this? In Theme Key there doesn't seem to be options to select node/edit & node add pages of a particular content type (or options to select user/edit pages).

you will need to create a hierarchical set up:

In this example set up, it checks for user:1 (admin), that the node type (content type) is article, and that the path meets the relevant criteria. You will need to adjust accordingly. Simply drag and drop the sub-elements into place.


Adding a radio buttons in views exposed filters for published and unpublished drupal 7 The above view shows articles content type, which is exposed filter.I want to add a radio buttons as i have shown in image for published and unpublished,can I get this functionality programmaticaly and how

This can be achieved using Better Exposed Filters module. If you need to do this programmaticaly then you may need to look at the code of this module. You need to implement the hook_theme as done in better_exposed_filters.module and implement the code to display as radio button as done in better_exposed_filters.theme(Function: theme_select_as_radios)

I would suggest using the module directly if that is an option.


#attached css in render array not working I am trying to render a block with a custom css with it. I have obtained a render array for the block and now I add to it:

$render_array['#attached']['css'] = array(
   base_path() . 'path/to/module/css/abcd.css',
);

return drupal_render($render_array);

The path to the css file is correct, I am able to access it in the browser. However, the css styles are not applied to the block. What are the proper steps to take now to debug this problem?

Thanks in advance!

Edit:
I have tried out Option 1, this is the result of dpm($block) in in the hook_block_view.

subject (String, 15 characters ) Correct subject
content (Array, 2 elements)

  #markup (String, 45 characters ) <span class="testtest"> Red text </span>
  #attached (Array, 1 element)
    css (Array, 1 element)
        0 (String, 58 characters ) /path/to/css

And the contents in the css file:

.testtest {
  color: #C43C55;
}

Could it be a site configuration? Thanks!

You are saying, you have already rendered content array for the block and after that you are adding css to this block. If block array is already rendered then where you are applying this css because array is already rendered for you. Now you have two options here.

Option 1: Add custom CSS to your block
It should be something like this.

function foo_block_view($delta = '')
{
  if($delta == 'foo_delta')
  {
    $block = array
    (
      'subject' => t('Foo title'),
      'content' => array
      (
        '#markup' => '<p>' . t('Lorem ipsum text.') . '</p>',
        '#attached' => array
        (
           'css' => array('path/to/my.css'),
        ),
      ),
    );
    return $block;
  }
}

Option 2: Add custom CSS to your page before this block rendered (Not a great option for your case).

$content = array();
$content['#attached']['css'] = array(
  $path . 'my.css' => array(
      'group' => CSS_AGGREGATE_THEME,
      'weight' => 999
    ),
  );
return $content;


Is there a solution which could keep information about actions and updating of data on the site? For example, there is a site. And it's necessary to create a news feed on the site. Approximately, like on the Facebook.

Thas is, if someone added a new forum topic, article or page of another content type, this event should be added to the news feed. Also if someone changed any page, information about it also should be added to the news feed. Also, if someone commented or liked something. Also if a new used added to the site. And so on.

I need to clarify, is there a solution, which could perform it ? And this solution should have opportunity to customize, which data should be added to the news feed and which data shouldn't. And I need to have possibility to customize its output design.

I don't want to try to use the dblog module for it. Moreover, the data on the dblog module can be deleted.

P.S. In my opinion, it's not possible to perform it using the views module only. Because views doesn't allow to use different types of entity, such as nodes, comments, users and so on in the same view. Therefore, I see the way to put it together using some entity, which keeps information about actions and which can be outputed using views.

By using the Message module (which already has a beta version for D8), you can create your own custom "Events logging" (to register things that happened in a site).

A great sample of this you can find in (the D7 version of) Commerce Kickstart, which uses the Commerce Message module, to create such "Events logging". In this case in the format of an Order History, as shown in this screenprint (from this module's project page).

The Message module is an amazing module, though there is not a lot of documentation about it. It is fully entity based, which implies that it perfectly (out of the box) integrates with modules such as Views and (only for D7 for now, not yet for D8) Rules.

Additional info

For more details about the Message module, refer to some interesting Use Cases detailed within its Community Documentation. And/or checkout the video introduction "Your Drupal site can talk" (if you want you can fast forward to about 03:30 where it really starts).


Provide default site uuid on install Can I provide default site's uuid static in Drupal 8. I am using docker with Drupal 8 and during configurations import the site is rebuild with docker resulting in different uuid each time. After that I am not able to import configurations.

Thanks

You can set the site uuid variable with drush, but a better solution is to use the "config_installer" module.

See https://www.drupal.org/node/2583113 for related discussions.


Getting two errors when trying to click Extend and Config tabs I'm getting the following errors:

  Drupal\Core\Extension\Exception\UnknownExtensionException: The profile does not exist or is not installed. in Drupal\Core\Extension\ExtensionList->getExtensionInfo() (line 346 of /app/drupal/core/lib/Drupal/Core/Extension/ExtensionList.php).
  Drupal\Core\Extension\Exception\UnknownExtensionException: The module does not exist or is not installed. in Drupal\Core\Extension\ExtensionList->getExtensionInfo() (line 346 of /app/drupal/core/lib/Drupal/Core/Extension/ExtensionList.php).

These errors are not telling me what module is missing.  I have not installed any modules. The only thing that I've done is update core from 8.7 to 8.8.1
The only thing that I've done is update from Drupal 8.7 to 8.8.1.  Is there anything I can do to find what module is causing the issue?

I found this Gist about Fixing a Drupal 8 site with an empty install profile related to your problem (which I also have). The guide solved the problems, but created another.

  Drupal\Core\Extension\Exception\UnknownExtensionException: The module minimal does not exist or is not installed. in Drupal\Core\Extension\ExtensionList->getExtensionInfo() (linea 346 di /var/www/html/web/core/lib/Drupal/Core/Extension/ExtensionList.php).

Looking for the second problem, I found this issue and patch #112 should solve all your problems without using the first guide I mentioned.

If instead you want to follow the guide, which I think is the best way to go, to solve the new problem do what comment #110 says.
By adding the line minimal: 1000 to the core.extension.yml file


How can I apply different templates based on taxonomy hierarchy? I'm new to Drupal and I don't have extensive knowledge so I'm hoping I can get this question answered.
I want the taxonomy pages of lower hierarchy to be displayed differently from the higher by applying a different tmeplate.
Is there a way in Drupal 8 to do this other than giving each term its own template?

What template exactly? taxonomy-term.html.twig, I guess?

You're looking for template suggestions. See Working with template suggestions on Drupal 8 for a similar question.

You can implement hook_template_suggestions_TEMPLATE() and then provide alternative file names for whatever condition you can think of.


User Files Download w/o Upload I am trying to figure out a clean way to do this in drupal 7 but can't find a clean way.

Problem: A user needs to be able to download files without the need to upload any files. Files are placed in private dir or uploaded by admin.

Scenario: A file will be placed in /private/userx directory by non-drupal way (cp file), a user needs access to download the files in own dir?

Requirements:
1. A user doesn't upload files.
2. A user can download his subdir files only.
3. A user can't download other users files.

I searched for solution but none found. I tried EntityForm file but that requires user upload and admin can't upload for a user as per other discussions.

One option is to place the file in a private dir and insert file object in the database with userid, but couldn't find example how to do that.

Any insight will be great help.

I would use the organic groups module. The idea is to create a content type lets say "userprivatedir" make this a og group and a allow users to create one or more nodes of this type. By default the creator of a og group is the owner of this group. Then i would create another content type lets say "userfile" and make this a og content. Then you may configure og so only the members of the group (i.e. the user that created it has access into it). The "userfile" content type should have a file field that stores files in the drupal private filesystem (so files are not accessible just by hotlinking but only through their node page.

Also if you dont want user to be able to upload at his own  "userprivatedir" (i.e. og group node) then create the group node by another manager user and then add only this user (or maybe some more that should see this directory's files) to this node group so they have access.


Adding a product field to cart summary in views I have a product image and product description as fields in the product entity. I want to add them to the cart summary displayed in the checkout, specifically it's the view "Shopping cart summary"

I added a relationship to the view: (Line items referenced by commerce_line_items) Commerce Line item: Product

And I added the two fields to the view.

When I preview it with an order number it works perfectly. the 2 fields are displayed as expected. But on the checkout page, the cart summary is blank...

What am I missing? How can i possibly debug this situation?

If anyone is interested, I found the answer here: https://drupalcommerce.org/discussions/1128/product-image-cart-form

It is a permissions issue. The solution was to enable the permission "view any product of any type" for anonymous users.


db_select get all results count when also using a pager Is it possilbe to get the count of all rows, when using a pager in a db_select query?
 My pager is the following:

$query = $query->extend('PagerDefault')->limit(20);

Yes you can use setCountQuery if you need to define a count query to return the total number of rows in your resultset.

See the docs for PagerDefault::setCountQuery()


Make all user profile pictures round I am trying to figure out how to apply a class to user profile pictures in Drupal 8 to make the pictures round.

Since I am using Bootstrap 3 I can just apply image-round class in this case, but I am not sure how to add the class to the profile image.

I tried adding a class with the Field Class module, but it didn't work.

In your file of your theme: "MYTHEME.theme"

Create hook_preprocess_image

/**
 * Implements hook_preprocess_image() to add classes to the search form.
 */
function MYTHEME_preprocess_image(&$variables) {
  ksm ($variables);
    if ($variables['style_name'] == 'thumbnail') {
        $variables['attributes']['class'][] = 'image-rounded';
    }
}


Page id based on file path? My page structure looks a little something like this:

www.site.com/sub-directory-1/page-1
www.site.com/sub-directory-1/page-2
www.site.com/sub-directory-1/page-3
www.site.com/sub-directory-2/page-1
www.site.com/sub-directory-2/sub-sub-directory-1/page-1
www.site.com/sub-directory-2/page-2
www.site.com/sub-directory-2/page-3

What is the easiest way to make the page's ID the name of the first subdirectory it's stored in?

For example, in the first case, the <body> tag should be like the following.

<body id="sub-directory-1">

You need to edit your page.tpl.php file, and add this where you have the <body> tag.

<body class="<?php
   print arg(0, request_path());
?>

This will print the first part of $_SERVER['REQUEST_URI'] delimited by a slash.
arg() and request_path() are Drupal functions.


Git with Drupal 7 multi-site, naming directories I have been working in a single installation of Drupal 7, which has two sites built upon it.

In Drupal 7 multiple sites are served by naming a directory for each site to be served under /sites and include settings, themes and modules specific to that site.

sites
|
|__ 8888.website-one.dev
|   |__ settings.php
|   |__ files
|   |__ themes
|
|__ 8888.website-two.dev
    |__ settings.php
    |__ files
    |__ themes

So the system identifies the site based upon the domain (in my case the preceding 8888 is the port number I use to work internally).

When I push this installation to a remote dev server using Git, the domains I use to access the installation will need to change, and so the directory names would have to change too; which means that I wouldn't be able to have the installation working on both my local and remote development boxes.

Is it possible, with Git, to change a directory name on the remote server, and keep it the same on my local server, while still tracking the files inside those folders?

Many thanks!

You don't need to consider a whacky git-based solution to this, Drupal has you covered.

Just uses aliases in sites.php, and use whatever method you like (assume-unchanged in the index, .gitignore, whatever) to keep sites.php out of the repo.

So on your local machine your sites.php might contain

$sites['website-one.dev'] = 'website-one';
$sites['website-two.dev'] = 'website-two';

And on a remote server:

$sites['website-one.staging'] = 'website-one';
$sites['website-two.staging'] = 'website-two';

And prod:

$sites['website-one.com'] = 'website-one';
$sites['website-two.com'] = 'website-two';

All the while, your sites live in 'website-one' and 'website-two' respectively; no need for tricks.

If you don't want to consider a Drupal-based solution, and still want to use git, I'd advise taking this over to Stack Overflow where such a question would be on-topic.


Persistent Audio Player Is there a way to have a persistent audio player between page navigations? HOw do you prevent the player from restarting on a page refresh.

The only way to do that is to actually NOT refresh the page each time but rather use ajax or something similar to refresh only certain areas of the page while leaving the player area intact.

An example of this is pitchfork.com.  It has a player in the upper right gutter.  When you click on a link, what happens is the main content area of the page is reloaded but the page stays the same, so the player keeps on playing.

But, if you hit the reload button on your browser, it stops and starts all over again because the page itself was reloaded.

Of course, you could always put the player in a pop-up/under window and then you wouldn't have to worry about it as much.


Ajax User login failing with "Username field is required", "Password field is required" I am trying to set up an AJAX login box for a site, using the following code:

function THEME_form_user_login_alter (&$form, &$form_state) {
   $form['actions']['submit']['#ajax'] = array(

        'callback' => 'user_login_submit',
        'wrapper' => 'user-login',
        'effect' => 'fade',
        'speed' => 'fast',
        'method' => 'replace',
    );
}

I get an Ajax error on form validation, I am thinking I am using the wrong callback but I can't figure out which one would work, and I couldn't find any example out there.. Any suggestion?

This is the error message:

  An AJAX HTTP error occurred. HTTP Result Code: 200
  Debugging information follows.
  Path: /parce/system/ajax
  StatusText: OK
  ResponseText: [{"command":"settings","settings":{"basePath":"/parce/","pathPrefix":"","ajaxPageState":{"theme":"parce","theme_token":"PFPo8K2w-7tUSndM3muIGW4Gpq-X8TT4-fR4ZmVcxD0","css":[]}},"merge":true}]
  Uncaught exception thrown in session handler.
  PDOException: SQLSTATE[23000]: Integrity constraint violation: 1048
  Column "uid" cannot be null:
  INSERT INTO {sessions} (sid, ssid, uid, cache, hostname, session, timestamp) VALUES
  (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2, :db_insert_placeholder_3, :db_insert_placeholder_4, :db_insert_placeholder_5, :db_insert_placeholder_6);
  Array(
   [:db_insert_placeholder_0] => -nLyLCVNED-8LSAd6NoZ8znhzZAoUVMNutGmi7ObAQ8
   [:db_insert_placeholder_1] =>
   [:db_insert_placeholder_2] =>
   [:db_insert_placeholder_3] => 0
   [:db_insert_placeholder_4] => 183.16.201.97
   [:db_insert_placeholder_5] => messages|a:1:{s:5:"error";a:2:{i:0;s:27:"Username field is required.";i:1;s:27:"Password field is required.";}}
   [:db_insert_placeholder_6] => 1308899744
  ) in
   _drupal_session_write() (line 203 of /home/sites/parce/includes/session.inc).

It looks like user_login_submit doesn't work well when called as an AJAX callback. The error you receive is because Drupal tries to create a session for the user that should be logged in, but no values for uid is present, which is required.

I believe that Drupal will call the form submit hooks when the form is submitted by ajax, so you might be able to simply add an empty callback function.

Alternatively you will need to call the form submit functions yourself, which should fix the problem.


Issue uploading Images I have a Drupal 7 site that runs on Windows 7 and SQLServer.

Recently, when users try to upload pictures or files they get an error message:

  File could not be saved. An unknown error has occurred. The file was unable to be uploaded.

I have a development and a test site. The site was on Drupal 7.20, then upgraded to 7.23 and it worked for the development and the test sites. However, it did not work in production.

In production I upgraded to 7.23 and verified the elfinder is using library files 1.2.

I am not sure why this is happening: No code was changed before the Drupal core update, and the error is sporadic.

The problem ended up being a server space issue. Increased space and the images were able to load.


Why Role::getPermissions() method return an empty array for admin users? Searching the answer for How to get user permissions for the role Administrator? I found that if you try to get the permissions for the admin user you will get an empty array.

From Role::getPermissions():

  /**
   * Returns a list of permissions assigned to the role.
   *
   * @return array
   *   The permissions assigned to the role.
   */
  public function getPermissions() {
    if ($this->isAdmin()) {
      return [];
    }
    return $this->permissions;
  }

But if the admin user have all the permissions why Drupal just return an empty array?

That is because a role that is marked with is_admin (which from the UI is possible for just a single role) has all the permissions. Consider it as an extension of the user #1 concept; the difference is that there is just a user #1, but there could be many users assigned to the role marked as is_admin.
In fact, the code does the same it does for the user #1: It explicitly checks for the role being is_admin. So, returning an array of permissions that will never be used doesn't make sense. See Role::hasPermission().

  if ($this->isAdmin()) {
    return TRUE;
  }
  return in_array($permission, $this->permissions);

Similar code is present in other functions/methods, for example Role::revokePermission().

  if ($this->isAdmin()) {
    return $this;
  }
  $this->permissions = array_diff($this->permissions, array($permission));
  return $this;

As for why Drupal uses that code, it is because from the UI it is possible to change which role is marked as is_admin, including one for which permissions were already set. Once it is marked is_admin, the permissions explicitly set can be ignored, but they are kept, just in case you change from the UI the role marked as is_admin. In such case, you would not want to set again the permissions you set for the old is_admin role.


Is it possible to use jQuery's modal dialog instead of the browser-standard alert when using ajax_command_alert()? I'd like to have a simple feedback form that is submitted via AJAX, using Drupal 7. Upon receipt of the form, I want a simple jQuery modal dialog to appear that will say something along the lines of "Thank you for your submission, etc.". The browser standard alert does accomplish this, but my client feels that this looks unprofessional, hence the desire for the more nicely styled jQuery dialog.

Using ajax_command_alert() causes the browser to use a simple alert() function. Is there any way to force usage of the jQuery modal dialog? For reference, my code is below:

function feedback_form($form, &$form_state) {

    $form['first_name'] = array(
        '#type' => 'textfield',
        '#title' => 'First Name',
    );

    $form['last_name'] = array(
        '#type' => 'textfield',
        '#title' => 'Last Name'
    );

    $form['email'] = array(
        '#type' => 'textfield',
        '#title' => 'Email'
    );

    $form['comments'] = array(
        '#type' => 'textarea',
        '#title' => 'Comments'
    );

    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => 'Submit Feedback',
        '#ajax' => array(
            'callback' => 'feedback_form_submit'
        )
    );

    return $form;
}

function feedback_form_submit($form, &$form_state) {
    $commands = array();
    $commands[] = ajax_command_alert("Form received");
    return array('#type' => 'ajax', '#commands' => $commands);
}

EDIT: I see that the alert function is defined in misc/ajax.js, under Drupal.ajax.prototype.commands. If I were to alter the JS file's implementation of alert, this would work - but that would be considered hacking core, I believe. How else could I alter this function?

I solved this problem in two ways - first, I added my own JS file which adds a modal option to Drupal's AJAX commands with the following JS code:

jQuery(function() {

    // Add modal dialog option to Drupal AJAX
    Drupal.ajax.prototype.commands.modal = function(ajax, response, status) {
        // Code to create a modal dialog goes here
    }

});

Then, in my AJAX callback on the server, I used the following code:

function feedback_form_submit($form, &$form_state) {
    return array(
        '#type' => 'ajax',
        '#commands' => array(
            array(
                'command' => 'modal',
                'text' => "Form submission successful!"
            )
        )
    );
}


How to format multi value field as a grid? I created content type "photo gallery" that have multi-value field of images - for user convenience. I would like to create a view, that would show all that kind of galleries with their titles on one page, formatted as grid. How is this possible?

We had a similar type of requirement to display in a grid/table layout multiple "Related" nodes rendered with a particular view mode (added with Display Suite), referenced through an Entity Reference field.
We came up with the following module: Grid Field Formatter, which is now available with a stable release.

If you look at the screenshots on the project page or the description in the content you should be able to find that it would seem to correspond to the initial requirements you described.

Feel free to let us know if I missed something, this doesn't work, or if you would have any more questions, comments or issues related with this requirement or module, I would be glad to provide more information or explain in more details.

Any more feedback, reporting, testing, comments or questions would be highly appreciated.
Thanks in advance!


How can I best display code examples on my site? I'm doing some PHP code examples for a class in a fancy Drupal site.

I have a "Code" content type.
I have a "field_php" that gets processed on the actual node.
I have a view that uses "node/%/code" to display the code formatted via Geshi:

View PHP Body: Link back to node/1
View PHP footer: PHP code to pull geshi formatted "field_php"

<?php
  include_once('sites/all/libraries/geshi/geshi.php');

  $page = $view->args[0];
  $node = menu_get_item("node/$page");

  $source = $node['page_arguments'][0]->field_php['und'][0]['value'];
  $language = 'php';
  $geshi = new GeSHi($source, $language);

  echo $geshi->parse_code();
?>

LASTLY I have a node--code.tpl.php edited to include a "View Code" link at the top of each "code" page. The include_once/echo at the top is the following:

<div class="<?php print $classes; ?> clearfix"<?php print $attributes; ?>>
  <?php
    include_once('sites/wernercd.php/public/~functions.php');
    echo "Code For You!";
  ?>
  <?php if (!$label_hidden) : ?>
    <div class="field-label"<?php print $title_attributes; ?>><?php print $label ?>:&nbsp;

  <?php endif; ?>
  <div class="field-items"<?php print $content_attributes; ?>>
    <div class="field-item even"<?php print $item_attributes[0]; ?>><?php print render($items[0]); ?>

http://mysite.com/node/1

http://mysite.com/node/1/code

I don't know why, but I feel like I'm doing it wrong. It works like I want it, but I just feel like its the "wrong" way to go about doing it.

What would the "recommended" way of getting this desired output be? How could I change this to catch issues unforseen by my naivete?

I would set up an input format for code and set the field_php to use that. The code input format could use a filter like this http://drupal.org/project/codefilter


Relationships between content types and views I am new to drupal, but have decent knowledge of WordPress & PHP. I am currently building a drupal site where I need to link two content types together and display them on the front end accordingly.

I have one content type called Vehicle Range, which contains a list of Vehicle ranged (e.g. BMW 1 Series, BMW 3 Series)

I have another content type called Vehicle Models, which lists the vehicle models (e.g. 1 Series 118i, 1 Series 118d, 3 Series 335d).

What I want to achieve is a menu that lists all of the Vehicle Ranges with the relevant models as dropdowns.

Example:

1 Series           3 Series

   118i                335d

   118d

I have created a reference between the two content types using the Entity Reference Module. The reference field is attached to the Range content type so that you tick all of the relevant models that belong to that range.

I am trying to create a view using this relationship, but my lack of experience with Drupal and views is causing me to fail. Whilst creating a view, the closest I can get is either a list of all of the models, displaying all of their fields, but they are not 'categorised' under the relevant range, or a list of the ranges with the model labels, which is close, but I need the full content / all of the fields attached to each model rather than just the label.

How can I make a view that will give me the output I need as shown in the example above using the two content types and reference field? Any help would be massively appreciated as I'm brand new to Drupal!

I don't think you need to create content types to do what you need.

You have a content type of car and then I would use taxonomy to select the series and models.  You can add fields/images etc to taxonomy and pull those into your view if you need to.


Nodes display links to shared document(s) Summary

Nodes display links to shared document(s)

Example

PDFs to upload only once before I create the workshops:

Booking Form Primary School
Booking Form Secondary Schoool
Risk Assessment for Primary School
Risk Assessment for Secondary School

Then I would like to be able to be able to create a workshop node using a custom content type and while creating this node, be able to click check boxes of some of the forms above.
When viewing the node of the workshop, for the ticked forms to be displayed as Links to download the PDFs.

This is so that when creating lots of Workshops, I can just tick the boxes for the form downloads to be displayed on each workshop page.

My Attempt

I created a taxonomy called: Forms.
For this vocabulary I added a file field: field_form
Then I added the terms and uploaded a document for each
Then in the Content Type adding a term reference field linking to the vocabulary.
This is where I get stuck. In the Content Type Display it only shows links to the term page and not the File download.

How would I setup the ability to upload some PDFs and then be able to then create some nodes that display links to these PDFs as downloads?

Create a block views of terms to display the links to term files;
add a filter/contextual filter in the view to show only the files of the terms of the current node;
set the block to show up on node pages (except node edit pages).


How can I add a wrapper to a group by in Drupal 8 views? I have a (drupal 8.3) view using group by that outputs html like:

Category 1

Category 2

I would like to hook or template the group by to use a wrapper and achieve:

Category 1

Category 2

Any ideas how I can accomplish this using Bootstrap theme?

You can accomplish this by customizing the views-view-unformatted.html.twig file:

Use Twig debugging to determine which version of this template is currently being used. Most likely, it's views-view-unformatted.html.twig in /core/modules/views/templates
Copy that file to your theme's templates folder.
Rename the template to this: views-view-unformatted--your-view--your-display.html.twig where your-view is the machine name of your view and your-display is the machine name of your view display.
Add this code to the template file you created:

  {% for row in rows %}
    {%
    set row_classes = [
    default_row_class ? 'views-row',
    ]
    %}

    {% if loop.first and title  %}

{{ title }}

        {% endif %}
        {{ row.content }}

  {% endfor %}

Flush your site's caches

Please note that spaces in your machine name are repalced with dashes in the name of the template file.


how to delete a node programitically in drupal 6? I want to add delete permission for a specific node id programitically. I try calling 'node_delete' but it doesn't work.

how can I do it ?

The node_delete() function requires to have the delete permission for the current logged user.
If you run the node_delete() function as anon user, is probably that doesn't work


How to programmatically remove a user from an organic group I have found many examples about how to add a user to an organic group but I can't find any info on how to remove a user from an organic group programmatically. Does anyone have an example of how to do this?

Part of me thinks that og_membership_delete would be a good option, you can pass the entity ID in as a parameter (and by "can", I really mean "need to"). Also, og_ungroup seems useful as well.

You can find more functions that OG defines at: http://www.drupalcontrib.org/api/drupal/contributions!og!og.module/7

Here's an example of og_ungroup:

og_ungroup('node', $gid, 'user', $uid);


How to create a module in HTML directly? For instance, I would like to create a module like

    First Name: <input type="text" ng-model="firstName">

    Last Name: <input type="text" ng-model="lastName">

    Full Name: {{firstName + " " + lastName}}

But what I found is that I have to create the module in PHP (For example, mymodule.module), import JavaScript file using drupal_add_js, create functions to establish a form in phpm etc.

So is there any way or an example to create a module directly with HTML?

No there is no way to create a Drupal module without creating the associated .module (a PHP file) and .info files. If you want your JS file to be inserted on all pages, you can have an empty .module file and add a scripts[] = myscript.js enty in the .info file. Keep in mind that Drupal is a CMS, designed to let site administrator manage content. what you are trying to do looks like embedding a JavaScript application on pages of a site whose content is managed with Drupal. While Drupal is extensible, it is very opinionated on how to build custom page.

Since you module actually mixes JavaScript and HTML, the clean way would be to have the required PHP boilerplate code to produce the HTML markup (ie. register a theme template hook and provides its default implementation) while ensuring the JavaScript file is included on the page whenever you template is rendered. Then have the required PHP code to produce a page containing your markup.

MODULE.module

/*
 * Implements hook_menu().
 */
function MODULE_menu() {
  return array(
    'my-app' => array(
      'page_callback' => 'MODULE_page',
    )
  );
}

/*
 * Page callback for MODULE app page.
 */
function MODULE_page() {
   // A simple page containing a single element rendered from out own template.
  return array(
    '#theme' => 'MODULE_app',
    '#ngApp' => 'myApp',
    '#ngController' => 'myCtrl'
  );
}

/**
 * Implements hook_theme().
 */
function MODULE_theme() {
  return array(
    'MODULE_app' => array(
      'template' => 'MODULE_app',
      'variables' => array(
        'ngApp' => 'myApp',
        'ngController' => 'myCtrl',
      )
    ),
  );
}

/*
 * Implements  hook_preprocess_HOOK().
 */
function MODULE_preprocess_MODULE_app(&$varialbles) {
  // Add required libraries, with
  drupal_add_js(...);
  // Add the custom JavaScript to the page.
  drupal_add_js(drupal_get_path('module', 'mymodule') . '/MODULE-app.js');
  // Add settings for the rendered element to the page.
  drupal_add_js(array('MODULE' => array($variables['id'] => array(
    'ng-app' => $variables['ngApp'],
    'ng-controller' => $variables['ngController'],
  ))), 'setting');
}

MODULE-app.tpl.php

<?php
/**
 * Add documentation here explaining what this template is and what
 * is expected from any overriding implementation (like having a root element
 * with the ng-app and ng-controller attributes, and what's available in the scope).
 */
?>
<div ng-app="<?php print $ngApp; ?>" ng-controller="<?php print $ngController; ?>">
    First Name: <input type="text" ng-model="firstName">

    Last Name: <input type="text" ng-model="lastName">

    Full Name: {{firstName + " " + lastName}}

MODULE-app.js

Drupal.behaviors.MODULEApp = {
  attach: function(context, settings) {
    // Bootstrap the Angular app for any instance or our element.
    settings.MODULE.forEach(function(variables) {
      var app = angular.module(variables['ng-app'], []);
          app.controller(variables['ng-controller'], function($scope) {
            $scope.firstName = "John";
            $scope.lastName = "Doe";
          });
    });
  }
}


Drupal - Run update.php after updating several modules? In Drupal, if several modules need updating, is it OK to copy all the files across and run update.php once, or do I need to copy each module individually and run the update each time?
Thanks

You can copy all the files at once and run update.php just once.


Language switcher block is different on remote site I'm working on a multilingual site and on my local version of the site I added the default language switcher. It show like this:

                    English

                    Français

And when I click the link to go to the french version of the site I am send to the /fr/a-propos page. Just like I'd expect.
Now I pushed my site update to my remote server. Looking at the code there. I see the switcher is different:

                English

                Français

The language switcher has a different class not language-switcher-language-url but language-switcher-language-content-entity so my styling is off. I changed to using the ID instead so the styling problem is fixed. but still strange things are happening. Sometimes when I click a link in the switch the url has the language_content_entity as parameter. And currently the active state of the language switch is not working on the remote site?
Using git both sites are exactly the same. The config is the same on both sites and I cleaned cache on my remote site.
Why is this code different on my remote site?

Possible reason:

Maybe you are not in the same page.
You dont have the same configuration

Solution:
We suggest you add your own custom class or container div. And from these, add the correct CSS.


Displaying individual fields in a template I have a template for a specific content type. I want to output individual fields from that content type in a specific order, which requires me to change the content type template. It's too complicated to explain why I need to do this.

In the template I see {{ page.content }} for outputting all the fields together, which displays everything, but I want to take the field variables out of this, and separately display each of them.

So for example I tried the following, but it displays nothing to the page.

{{ page.content.field_field_name1 }}
{{ page.content.field_field_name2 }}

I also tried {{ content.field_field_name1 }}, {{ field_field_name1 }}, and {{ content.field_field_name1.entity }}, but none of them work.

Suggestions?

You can not print out content fields directly in the page template. content is available in the node template, not in the page template.

The correct way to print out parts of the node elswhere in the page template is to define a block that does that, for example with the ctools module and a specific view mode that just contains the fields you want.

Alternatively, you can load the node yourself in theme_preprocess_page() and then view/prepare them manually and put it in $variables. But using blocks and regions is the standard and recommended way to put something in the page template.


Having trouble using responsive feature of Superfish I am using the Superfish module for Drupal 7.x, and the menu itself works as advertised. However, no matter what configuration options I try, I cannot get the main menu to change into a select menu when at smaller screen sizes. It just attempts to render the original menu (which, of course, becomes a mess at smartphone size).  I'm not even sure where to start looking for a problem.  Any clues would be appreciated!

I ran into the same problem a while ago, and wound up writing some javascript/css to convert a multi-level superfish menu into a windowshade-style menu. It wasn't very elegant, though, and I later found the Responsive Menus module - it was very easy to set up, from what I remember, and worked with Superfish right out of the box. It also provides several styles of mobile navigation -- though not a select menu, if that's specifically what you want.


How to programmatically populate a country field We are using the Countries module to provide country fields where editors can choose a country and it gets displayed in the frontend. Which works absolutely fine.

But we want to fill that field programmatically through a custom module. No matter what value we provide to fill the field (country name, ISO 2 code etc.) the field doesn't get populated.

We are certainly sure that there is no any error somewhere else as we are filling multiple fields in our module and all are working as expected.

We want to know in which format does the country field expect the value to be?

Clarification:

We have a field field_country in profile2 with the Country type coming through Countries module.  We are getting input in our module through following code in our form:

include_once DRUPAL_ROOT . '/includes/iso.inc';
include_once DRUPAL_ROOT . '/includes/locale.inc';

$form['country'] = array(
  '#title' => t('Country'),
  '#type' => 'select',
  '#description' => t('Please Select Your Country Where Do You Belong To.'),
  '#required' => 'true',
  '#options' => array('' => t('-Select a Country-')) + country_get_list(),
  '#default_value' => isset($values['country']) ? $values['country'] : '',
);

We have also tried '#type' => 'country' and a few other things but same result.

For submitting this value we are using the code:

$profile->field_country['LANGUAGE_NONE'][0]['value'] = $data;

I played around with this now for a little while. Seems all you need is the iso2 key to be set.

global $user;

$node = new stdClass();
$node->title = 'Lorem Ipsum';
$node->type = 'article';
node_object_prepare($node);

$node->language = LANGUAGE_NONE;
$node->uid = $user->uid;
$node->status = 1;

// In the end this was it.
$node->field_country[LANGUAGE_NONE][] = [
  'iso2' => 'FR',
];

$node = node_submit($node);
node_save($node);

Apart from that you can use the Devel module to either dump variables like that

dpm($variables);

for example in a MYMODULE_preprocess_node() hook. After you filled out a node with a country field from the UI you can use that to check which values are set. Or you can checkout node values directly by appending /devel to a node path (http://example.com/node/42/devel). Although I must admit that what I got there as output was quite misleading. All that really was needed was the iso2 key.


Using Webform with tokens in drupal 7 I have a custom content type "Project" which has two fields "Completed Projects" and "WIP Projects". I have added some of my project as completed and rest of them are wip.

Using webform, I wanted to create a form, which can show ONLY my WIP projects (Not completed projects) in check box option. So that check box entries can be generated dynamically and user can select WIP projects.

You dont have to use tokens there. You can use hook_form_alter to add the correct node titles to the form at that stage. You write a custom query, and populate the empty list.


Post image via webservices I tried to create a node through external application using web services. This having only two fields node title and cck field image. i will grateful if anyone share the JSON format to post the images. I tried using format that mentioned below link but its failed means image not uploaded.

https://www.drupal.org/node/2195165

Any one guide me do this.

Thanks..

URL: http://example.com/service_enpoint/file

Method: POST

file: (file to be uploaded in base 64 encoded format)

filename :plus-box.jpg

uid: 55

The jpg file should be uploaded in base 64 encoded format.

As response you will get a fid , which you will have to pass in the image field while creating the node.


Views Row Classes Not Appearing I'm using a view to display articles, I want to see views row classes in the code, like this:

div class="views-row views-row-1 views-row-odd views-row-first

But for some reason the rendered code is missing these row-specific div wrappers and just shows the nodes like this:

div id="node-4" class="node node-article"

Even more frustrating, the code in the views PREVIEW shows the desired views row classes div class="views-row views-row-1" but those div wrappers don't appear in the rendered site code.

On the last site I made, the views-row classes appeared automatically. Now for some reason they're not appearing. I've been frantically googling and pulling my hair out for two days on this so any help you could provide would be greatly appreciated :-)

Did you check:

Template (*.tpl.php file) override. I am not sure if preview shows template overrides.
Template.php for altering hooks
Contrib modules for altering hooks


What are the differences between EntityFieldQuery and field_get_items() What are the differences between EntityFieldQuery and field_get_items() ?

When should one be used over the other?

I have a relatively complex query that I need to build, using values from custom fields.

They are intended for different purposes.

EntityFieldQuery is an object to query entities using conditions that includes the value of their fields (for example: retrieve all entities of type node that have 'foo' as value in the field_somestring field).

  Retrieves entities matching a given set of conditions.

  This class allows finding entities based on entity properties (for
  example, node->changed), field values, and generic entity meta data
  (bundle, entity type, entity id, and revision ID). It is not possible
  to query across multiple entity types. For example, there is no
  facility to find published nodes written by users created in the last
  hour, as this would require querying both node->status and
  user->created.

field_get_items(), on the other side, is a function to retrieve field data of a single entity:

  Returns the field items in the language they currently would be
  displayed.

So, I guess you should use EntityFieldQuery. Keep in mind the advice I copiyed above: you can only query properties (status, creation date, etc),metadata and field values, but you can't join with other data (any other specific table or query two entity types). If you need that use db_select.


why is hook_access_node running three times? I'm working on a custom node access module. For this I'm working with hook_node_access hook (for the first time).
I want visitors to be able to view a node only when they are looking at them from the right domain. For this I have a content type page, in this content type I created a field field_domain.
Now I create a two nodes, Node A with field_domain value d9-a.lcl and Node B with field_domain value d9-b.lcl.
Now I wanted to create the module based on the this tutorial. But before this I created a simple check to see if I can get the value from the field and current domain. So I wrote this:
function hook_access_node_access(NodeInterface $node, $op, $account)
{
    $type = $node->bundle();
    if ($type == 'page') {
        $currentDomain = $_SERVER['SERVER_NAME'];
        $readerDomain = $node->field_domain->value;
        dpm($node->id());
        dpm('Current domain: ' . $currentDomain);
        dpm('Pages domain: ' . $readerDomain);
    }
}

Now going to Node B from domain d9-b.lcl made me expect to see three values. And the values I wanted to see are there but they get returned three times.

So for some reason the hook is called three times and I can't figure out why. Is it normal that this hook is called three times? And if it is is there a better way to do what I want?

Yes it’s perfectly usual for a node access hook to be hit multiple times in one request, check the $op parameter to see what you’re dealing with each time.
Checks may be done for different $op values like view,update and delete.
(Answer from @Clive in comments, posted here as answer after his advice. Please see question's comments.)


prepare() function doesn't work well in migrate module This is my code to move a few records from a table to a Drupal content type (called CT1)

<?php
class CT1Migration extends Migration {
    public function __construct() {
        parent::__construct(MigrateGroup::getInstance());
        $this->description = 'Imports CT1';
        $fields = array(
                'id',
                'subject',
                'content',
        );

        $query = db_select('tbl', 'qf')
        ->fields('qf', $fields);

        $this->source = new MigrateSourceSQL($query);

        $this->destination = new MigrateDestinationNode('porseman');

        $pkmap = array('id' => array('type'  => 'int',
                'unsigned'  => TRUE,
                'not null'  => TRUE,
                'alias'     => 'qf'));

        $this->map = new MigrateSQLMap($this->machineName, $pkmap, MigrateDestinationNode::getKeySchema());
        $this->addFieldMapping('title','subject');
        $this->addFieldMapping('field_CT_body', 'content')->arguments(array('format' => 'full_html'));
    }

    public function prepare($row) {
        $row->title = "This is title 1";
        $row->field_CT_body = t("This is body");
    }
}
?>

CT1 has two fields, title and body. I need to perform some settings before the migration so I use prepare() function. From function prepare($row) function I expect the values of title and field_CT_body of all of the imported records to be This is title 1 and This is body while after the migration the title correctly gets this string (This is title 1) as its value but field_CT_body has no value at all.

if I remove the prepare function it migrates the records successfully.

Unfortunately you can't set the value directly like that, you need to reference the language and delta in the classic, hated method:

public function prepare($entity, stdClass $row) {
  $row->title = "This is title 1";
  $row->field_CT_body[LANGUAGE_NONE][0]['value'] = t("This is body");
}

Note: This function takes 2 params, the entity object being built and the source row. So, since we're altering the entity object, we gotta manipulate it as such.  (I'm not sure, but you might be able to wrap that object in a metadata wrapper in order to use the cleaner API)

Also, please note that the "value" key will depend on the field type in use.

Note: untested code but it should be fine! :)


Is there a filter/search option available for navigating the 'Find Content > Files' page? I have a site with thousands of files uploaded, and Drupal's admin view doesn't seem to offer a comprehensive filter for the Files view like it does with the Content view.

There also apparently isn't the option to search the files either.

Files view:

Is any such filter or search option available? This would make updating files 10 x faster!

The best thing to do here is create a custom VBO view to suit your needs!
It can have all the filters and sortable columns you want, and ... checkboxes so you can perform actions on the selected items.

See a guide here for using Views Bulk Operations.

Don't forget to set the views access permssions as you want to create an admin only vbo view !


Load AJAX form on every page via drupal_get_form I'm trying to load this contact form on every page via drupal_get_form()

<?php
function MYMODULE_menu() {
    $items = array();
    $items['contact'] = array(
        'title' => t('Contact'),
        'description' => t('Contact'),
        'page callback' => 'contact_page',
        'access callback' => TRUE,
        'type' => MENU_CALLBACK
    );
    return $items;
}

function contact_page () {
     $output = '
'.drupal_render(drupal_get_form('ajax_contact_form')).'
';
}

function ajax_contact_form($form, &$form_state) {
    $form = array();
    $form['name'] = array(
        '#type' => 'textfield',
        '#title' => t('Name'),
        '#required' => TRUE,
    );

    $form['submit'] = array(
        '#type' => 'submit',
        '#ajax' => array(
            'callback' => 'ajax_contact_callback',
            'wrapper' => 'ajax_contact_form',
            'name' => 'submit1',
            'method' => 'html',
            'progress' => array(
                    'type' => 'throbber',
                    'message' => t('Message is sending...'),
                ),
        ),
    '#value' => t('Send'),
    );
    $form['box'] = array(
    '#type' => 'markup',
    '#prefix' => '
',
    '#suffix' => '
',
    );
  return $form;
}

function ajax_contact_callback($form, &$form_state){
    drupal_validate_form('ajax_contact_form', $form, $form_state);
    $name =  $form_state['values']['name'];
    if (form_get_errors()) {

        $form['box']['#markup']='
'.t('Please check your fields!').'
';
        $form_state['rebuild'] = TRUE;
        return $form;
    }
    return $form;
}
?>

Basically everything is works on /contact page but when I try to load this form from page.tpl.php. It doesn't want to validate. What should I do?

<?php  print render(drupal_get_form('ajax_contact_form'));  ?>

Here

I solved this issue, problem was in 'wrapper' so this is how it works

<?php  print '
'.drupal_render(drupal_get_form('ajax_contact_form')).'
';  ?>


How to provide a contextual filter with an OR conjunction to a view? I have users that can be associated with a single node of type foo. The node has a list of users that are associated with it. I populate the entity reference fields in the content type with a view, which filters users that aren't associated with foo (user has no foo).

What I need to happen is that I need this view to also grab users that are associated with the specific node that I'm looking at, so when I try to add new users to the foo content type, the users that were associated with it beforehand remain associated with it (user has no foo OR user's foo id equals current foo id). The problem is that the first filter is a normal filter, the second is a contextual filter. How can I, programmatically or otherwise, get the views to grab the users I need with those conditions?

Edit: Unfortunately, the views-related hooks aren't called when populating an Entity Reference, which makes things like hook_views_query_alter not a solution. So a more accurate question would be: how can I get the entity reference to grab the users I need with the given conditions?

I guess you need to use hook_views_query_alter and then you could add your OR condition.

function hook_views_query_alter(ViewExecutable $view, QueryPluginBase $query) {
  if ($view->id() == 'machine_name_of_your_view' ) {
   //$query->where contains the filter conditions
   //i.e. 'Where' part of the query where you could add yours.
   var_dump($query->where);die;
  }
}

more from drupal.org


Stop autosubmit on textfield I have tree element exposed on a View, two Select Box and a custom filter (textfield). I set up the View for Autosubmit (Automatically submit the form once an element is changed). For the two Select Box is OK but for the textfield is a problem because the page is submitting after every key up.

There is any options to do the textfiel stop the autosubmit behaviour on Drupal 7?

Views depends of ctools and this is the cause of autosubmit.

On do: https://www.drupal.org/node/1735254

This is the feature what I need.

  If you want to exclude a field from the ctool-auto-submit-full-form
  auto submission, add the class ctools-auto-submit-exclude to the form
  element. With FAPI, add:

'#attributes' => array('class' => array('ctools-auto-submit-exclude')),


Field template not being rendered On our company website we have a people page which amongst others has an image field called 'field_photo'

This is being rendered using the following:

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

However I need to be able to add some attributes to the img tag outputted, to do this I figured I would have to use a custom template and add in the required bits like so:

$item['#item']['attributes']['class'] = 'photo';

Problem I am having is no matter what I do, I don't seem to be able to get this to work no matter what I name the template (eg field--field_photo--image.tpl.php). I'm not used to working with Drupal at all, so any help would be great!

Ta

Can you try:

$item['#attributes'] = array('class' => 'photo');


Send old Simplenews to newly registered users? I have sent a Simplenews newsletter.

Added some new users since this mailing, and would like to resend it to some newly subscribed users. How can I do that?

I also found a brute way.

Set newsletter sending status to 0 which will allow a resend to the entire userbase.

Install https://www.drupal.org/project/simplenews_filter

Select only the users that were missed the last time via Views, and send.

(One could also select to send all and delete the subscriber ids from the spool table where you dont want to send)