How to register a new PHP function in Twig? I am trying to create a theme for Drupal 7 with Twig. If I wanted to register a new PHP function, I should implement "hook_twig_function()" as the module explains.

My simple question is: where should I implement my functions? If I write code - as usual -  inside my "template.php", I have this alert: "Unknown "my_module_coolfunction" function in "sites/all/themes/abc/templates/page.tpl.twig"

If I edited the "Extension.php" file, after every update, I would lost all my custom functions.

In the docs it says:

  Functions

  To register a new filter you should implement hook_twig_function() and
  return an indexed array with unique keys and new Twig_SimpleFunction
  as value.

function my_module_twig_function(){

To answer your question:

  My simple question is: where should I implement my functions?

Notice how it uses "my_module", so clearly in your custom module .module file is where these function(s) should be added. If you don't have a custom module yet, then you will need to create one.

So if your custom module is named Hello Kitty, then in hello_kitty.module

function hello_kitty_twig_function(){
    $functions = [];
    $functions['coolfunction'] = new Twig_SimpleFunction('coolfunction','hello_kitty_coolfunction');
    return $filters;
}

function hello_kitty_coolfunction($param_1,$param_2...){
    // do what you need to do, and return something.
}


Ajax reloading a view with ajax mini pager I have this view, a 'block' display that has ajax enabled and have a mini pager that loads next page content through ajax.

As a requirement I have to reload the current view content through ajax along with some custom sort/filter.

After going through some forums, I did something like below.

in .module page callback :

$view = views_get_view('vdlibrary');
$view->set_display('block');
$view->set_use_ajax(TRUE);

$settings = array(
    'views' => array(
        'ajax_path' => url('views/ajax'),
        'ajaxViews' => array(
            array(
                'view_name' => $view->name,
                'view_display_id' => $view->current_display,
                'view_args' => check_plain(implode('/', $view->args)),
                'view_path' => check_plain($_GET['q']),
                'view_base_path' => $view->get_path(),
                'view_dom_id' => 1,
                //'pager_element' => $view->pager['element'],
            ),
        ),
    ),
);
drupal_add_js($settings, 'setting');
views_add_js('ajax_view');

in JS I am calling below ajax function on a click event to load the new views content based on the condition.

for (var key in Drupal.settings.views.ajaxViews[0]) {
  data[key] = Drupal.settings.views.ajaxViews[0][key];
}
// I add additional filters/sort params to var data.
$.ajax({
  url: Drupal.settings.views.ajax_path,
  type: 'GET',
  data: data,
  dataType: 'json',
  success: function(response) {

    $(".vdr_container").html(response[1].data);

  },
  error: function() {
    // handle error response.
  },
});

Not surprisingly, after it loads the content, the ajax pagination feature not working instead it reloads the page along with params. How do I keep the old context or make the new loaded views to rebind pager click event to work with ajax pager.

NOTE: my descriptions might not be good enough, let me know where I could explain in better way.

Thanks

After going through ajax_views.js and understanding view-dom-id element structure, finally I could able to get this done.

In ajax response object, there are 3 callbacks, In the last 'insert' callback, I got data with command to 'replacewith' and a DOM selector (unique dom for views wrapper with '.view-dom-id-xxxxx'). So I did replace the new content like :

$(".view-dom-id-" + vDomId).replaceWith(response[2].data);

Then I got the content with existing context, all I had to do then is re-attach the 'ViewsAjaxView' behavior as found in ajax_view.js

Drupal.attachBehaviors('ViewsAjaxView');

This attachBehaviors function will take care of binding ajax pagination to my newly altered views data.

I still feel, as if this can be more simpler like running all callbacks I get in response variable in success. I will post more if I get into. Hopefully someone gets some help from this.

Anybody have idea to run those commands?


how to request multiple public image sizes from a field's filename? this node endpoint - http://cms.tripchi.com/drupalgap/node/35921 - in my Service includes...

field_photo: {
und: [
{
fid: "810",
uid: "1",
filename: "dxb-airport_1.jpg",
uri: "public://dxb-airport_1.jpg",
filemime: "image/jpeg",
filesize: "64389",
status: "1",
timestamp: "1408433735",
uuid: "697b5fd7-a968-4f6d-b5a0-558ff0f76680",
rdf_mapping: [ ],
alt: "DXB",
title: "DXB Airport",
width: "390",
height: "270"
}
]
},...

using javascript - similiar to this http://cms.tripchi.com/mobile-app/js/index.js - I want to be able to request the large/medium/small dimensions of this public image dynamically - without changing the field_photo's settings in Drupal's.

I have the content-type's image style configured per the image below:

When the field's "Preview image style" is set to "Thumbnail (100x100)", I can do

var size = 'thumbnail';
sDomain + '/sites/default/files/styles/'+size+'/public/' + utils.getLang('field_photo', obj, 'uri');

However, when I change the size variable to 'large', I get an Access Denied error.

Changing the field_photo settings to the "Large (480x480)" size does fix that, but I only want this size returned for the API via JavaScript and this changings the Drupal's front-end view/template as well.

When I change the API's Display-Suite I get no difference to what the API returns and manually reconstructing the URL with 'large' still returns Access Denied.

Is there a way to expose requesting multiple image sizes without changing Drupal's field configurations? I would accept a solution that includes a Drupal hook to create the other image sizes on the presence of a parameter.

But avoid … Asking for clarification,

Really? What a joke! I hate this forum so much

There are a few things happening here. When you make a change to the field in the content type UI the imagecache is being manipulated/cleared. Changing the javascript manually does not do this so the path is not pushed through the system.

The easiest way to do this is to have separate fields for each size in the content type to make them available to your js. Hide the display of the fields not needed on the page (use  hook_alter or the admin UI).

Then in your js call them programmatically. To ease the JS call I would name the fields so they can be iterated, ie. field_photo_1(lrg),field_photo_2(med),field_photo_3(sml)


Getting the number of Flood events within threshold? The FloodInterface has 4 methods:

register - which adds an event
clear - which clears an event
isAllowed - which checks to see if the number of logged events is greater than the threshold
garbageCollection - removes expired events

I'm creating an EntityForm and need to use the number of flood events to conditionally set certain form elements, does anyone know if there is a way to do this?

The only way to do that with the default FloodInterface would be to use the isAllowed method and adjust the threshold to the number of allowed attempts.

From a hook_form_alter() you could do something similar to this, where 'my_trigger' is the name of the event that is registered, such as 'contact' for the contact form or 'user.failed_login_ip' and 'user.failed_login_user' for user login. 5 would be the maximum number of times the event could have been registered in 3600 seconds.

<?php

function hook_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  // Hide element if over the number of allowed attempts
  if (!\Drupal::flood()->isAllowed('my_trigger', 5, 3600)) {
    $form['my_element']['#access'] = FALSE;
  }
}


Drupal form elements in html table, label (title) rendering How to place title/label in other cell of the html  table

I have:

function hook_theme() {
  return array(
    'hook_form_table' => array(
      // The renderable element is the form.
      'render element' => 'form',
    ),
  );
}

function hook_form_table_form($form = array(), &$form_state) {

    $form['#theme']= 'hook_form_table';
    $selected_two="";
    $options_second=array("a");
    $form['carmodel'] = array('#type' => 'select',
        '#options' => $options_second,
        '#default_value' => $selected_two,
        '#required' => TRUE, '#title' => t('Car model:'),
        '#validated' => true,
        '#prefix' => '
',
        '#suffix' => '
',
    );

    $options_euro=array("Euro 3,4","Euro 5" );

    $form['euro'] = array('#type' => 'select',
        '#options' => $options_euro,
        '#default_value' => $selected_two,
        '#required' => TRUE,
         '#title' => t('Euro type:'),
        '#validated' => true,
     );

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

  return $form;
}

function theme_hook_form_table(&$variables) {
    $form = $variables['form'];
    $content = '
' . t('Please enter your information below') . '
';
    $content.="
";
    $content.="
";
    $content.="";
    $content.=$form['carmodel']['#title'];
    $form['carmodel']["#type"]="";

    $content.="	";
    $content.="";
    $form['carmodel']['#title']="";
    $form['carmodel']['#required']="";
    $content .= drupal_render($form['carmodel']);
    $content.="	";
    $content.="";
     $content.="hire want euro type  with * and label and all";
    $content.="	";
    $content.="";

    $content .= drupal_render($form['euro']);
    $content.="	";
    $content.="
";
    $content.="
";
  return $content;
}

This give me a table but labels is on top:

How to render label to put it like this:

My not nice solution is

function drupal_render_label($field){
    $result= "
";
    $result.= "".$field['#title'];
    if ($field['#required']==true){
       $result.= "*";
    }
    $result.="";
    $result.="
";
    return $result;
}

and then:

  $content.="";
  $content.=drupal_render_label($form['carmodel']);
  $content.="	";

Anyone have sth better?


Copy a user directly in database from another database (from production to dev-site) related to this post for Drupal 6 (Adding a new user directly in database), I wanted to ask for help for my problem:

I have a drupal 7 site which is already online ("in use/production"). Users can register there.

To get an up to date dev-enviroment, I download the files (uploaded files, modules and so on) via ftp from my production server to my dev server.
The DB is migrated by "backup and create"-module (export on production server, import on dev-server and vice versa).

As I develop the features in my dev instances, new users register on my production site. If I now import my new backup of the dev-server to production site, the new users registered are lost because the db has been overwritten by the backup.

How can I copy these new user accounts directly to the dev database? what database tables are involved in Drupal 7?

THX in advance
phil

Databases shouldn't be copied upstream, they should only be copied downstream, for the exact reason you are seeing.

This is a bit of a problem in Drupal 7.

If you need to move content up from dev -> production, like new nodes or you want to move configuration, then the best way to do it is either manually, or to set up something like the migrate module to migrate your content.


Teaser view doesn't show image field I've added an image field in a content type, and set the 'Field Settings' -> 'number of values' to unlimited, which means users can upload unlimited images for this field.

Then I build a view for this content type and expose the image filed to the view. What I'd like is to expose only image in teaser view, and all images in the full view.

I use a template preprocess function

function MYTHEME_process_field(&$vars) {
  $element = $vars['element'];
  // Field type image
  if ($element['#field_type'] == 'image') {
    // Reduce number of images in teaser view mode to single image
    if ($element['#view_mode'] == 'teaser') {
      // something might be wrong here
      $item = reset($vars['items']);      // not working
      $vars['items'] = array($item);      // not working
    }
  }
}

In debugging this function, this 2 lines

  $item = reset($vars['items']);
  $vars['items'] = array($item);

It doesn't seem to work because the image field in the content type can have multiple images.

I just tested that exact code in Drupal 7 and it's working perfectly!  The full view displays two or more images and a view of teasers just shows one image per node.

HOWEVER, I did notice the following: if you're just in the process of building a view the Preview below the view does not display the final output correctly.  The Preview in the view of teasers shows multiple images per teaser, but if you just go ahead and hit 'save' and then test your view (by going to its link if it's a page), you'll see that it actually displays correctly.

Does that end up working for you?


Is it possible to pass variables as arguments to *.libraries.yml? Say I have a foo.libraries.yml defined as so:

external.bc.js:
  version: 1.x
  js:
    //players.brightcove.net/{{variable here}}/{{variable here}}/index.min.js: { type: external, minified: true}

Where {{ variable here }} is where I want to insert values when I attach the library

Then, in a hook_ENTITY_TYPE_view() I am running:

$build['#attached']['library'][] = 'brightcove/external.bc.js';

Which is where I'd also like the pass those variables. Is that possible?

Instead of defining the library in the .libraries.yml file, you should add it using hook_library_info_build(), which is the hook to add dynamic library definitions, as in your case.
function mymodule_library_info_build() {
  $libraries = [];

  $js_path = 'the dynamic path to the external JavaScript file';
  $libraries['external.bc.js'] = [
    'version' => '1.x',
    'js' => [
      $js_path => ['type' => 'external', 'minified' => TRUE]
    ],
  ];

  return $libraries;
}


Override global JPEG quality value based on cookie I am working on a site that has an international audience and that needs to allow users to toggle a "low bandwidth" version. In order to achieve this, I would like to check if a cookie has been set and if so, override the global JPEG quality value from 75% down to, for example, 40%.

How can I override this variable and is this even possible with image caching?

This would need a bunch of image styles, a custom field formatter, a custom module that reads that cookie value, and a speed test of some sort.

You'd need to create image styles for each of the quality tiers that you want. That part can be done with the built-in image styles module.
Then you'd want to create a custom module that:

Detects the speed of the client's connection and sets that cookie. It can simply be JS downloading a 1KB file download whose start and end times are recorded and set on a cookie.
Supplies a custom field formatter to image fields that, instead of making you select a fixed quality, will select the image style and render the image with that image style on-the-fly. As an added bonus, you could allow the formatter to be configurable by exposing a form that allows the selection of which image style to use at certain speeds.
Lastly, detects the cookie that was set earlier and informs the field formatter which image style to use based on the cookie value.

This assumes that all imagery are coming from fields (because of the field formatter). For theme imagery, you'll need to render your images by hand in the same way as above, sans the field formatter.


Pass variables from html preprocess function to page preprocess function? In my custom theme's hook_preprocess_page() and hook_preprocess_html() functions, I often need to identify the same information. Rather than essentially running the same if statement checks in both the identify the same info, it would make much more sense to just do it once in both of them and then pass that info to the other preprocess function. How can I do this? I tried the following but it didn't work:

function myTheme_preprocess_page(&$vars){
    $vars['myValue'] = 7;
}

function myTheme_preprocess_html(&$vars){
    //$vars['myValue'] should equal 7...
}

I also tried it the other way around (setting the value in the preprocess html function and then retrieving it in the page preprocess function) but that didn't work either. Which brings up a related question: in what order are these preprocess functions, er, processed? It seems to me that the page preprocess function comes before the html one, is that correct?

You're going to need either a global or static variable to accomplish this...personally I'd recommend going with static and implementing a generic helper function using Drupal's static pattern like so:

function _myTheme_var($var_name, $new_val = NULL) {
  $vars = &drupal_static(__FUNCTION__, array());

  // If a new value has been passed
  if ($new_val) {
    $vars[$var_name] = $new_val;
  }

  return isset($vars[$var_name]) ? $vars[$var_name] : NULL;
}

function myTheme_preprocess_page(&$vars){
  $vars['some_var'] = _myTheme_var('my_var', 7); // Set the value and retrieve it
}

function myTheme_preprocess_html(&$vars){
  $vars['some_var'] = _myTheme_var('my_var'); // Get the value
}

The $vars arrays for each preprocess function are completely different objects in memory so you won't be able to use that array to pass things around. I've seen this sort of pattern used a lot in Drupal core so I think it would be the best way to go.

EDIT

Oh and yes, hook_preprocess_page() is called before hook_preprocess_html()...as far as I'm aware Drupal works in a sort of "inside-out" manner so hook_preprocess_html() would probably be the last one that's run in a page build.


How to toggle views filter when user click on tab? i got 2 tabs and i want to achive this goal: once user click on tab 1 for example, its shows him a filters for tab1, if he clicks on other tab, its toggles the form to other "sory by" forms elements related to tab2, im using drupal 6 and jquery
attached image for demo: http://www.media396.com/tmp/tabsexampleugly.png

You can define two displays in the View which both pull from the "Default" view and use the Tab option for the menu type. Then, override the exposed filters in each of the two displays. So on the display for Tab 1 have the Tab 1 related exposed filters, then on the Tab 2 display you can use your Tab 2 related exposed filters.


Cancel if condition not met, show status I have the Mimemail module set up to send HTML mails out, after a form is filled in an email is sent to the user based on a custom template.
But the email should only be sent out if the user has previously filled in another form, if they haven't a message needs to be displayed and the email cancelled.
I'm simply using the following code to check that they have filled in the other form previously:
$query_result = db_query("SELECT MAX(sid) as max_id FROM webform_submitted_data WHERE data = '" . $email . "' AND nid = ###" )->fetchCol();

So if this returns an empty array then a message needs to be displayed and the email cancelled, but I can't seem to stop the email being sent, how do I do this?

You can use hook_mail_alter() for that, e.g.

function MYMODULE_mail_alter(&$message) {
  if ($message['id'] == 'MYMODULE_foo' && any_other_condition()) {
    $message['send'] = FALSE;
  }
}


Google Map will not show on new ajax page load I have added a styled google map V3 to a block using full html this all works fine and displays on page refresh. I'm have trouble with the map loading after linking to another page in conjunction with the ajax pages module.

All of my main menu links are ajax calls and pages load via ajax. On a page refresh the map will show, but if I click back and forth through the ajax pages the map will fail to load. I'm guessing this has something to do with this line?

google.maps.event.addDomListener(window, 'load', initialise);

Is there something I can do to make the map load even after a ajax page change? I have tried to change the load to on.load but that doesn't make a difference.

Here is the code in my block:

Thanks,

Terry

You can do it this way:

var success = Drupal.ajax.prototype.success;

Drupal.ajax.prototype.success = function(xmlhttprequest, options) {
    success.apply(this, arguments);
    initialize();
}

This will call initialize (make a note about your init function - it' called initialiSe) just after successful Drupal.ajax call.

Using this code

success.apply(this, arguments)

we ensuring ourselves that nothing interrupt normal behaviour of the original handler.


Filter a view by a value being absent from a multiple value field Given a field "field-participants" on a node type "discussion" that references an unlimited number of users:

How can I produce a view that shows all discussions that do NOT have the current user listed in their field_participants?

The problem comes from the fact that views creates a separate row of results for each reference in field_participants in any given discussion.

I can use 'Distinct' or Aggregation to get rid of duplicate rows, but while this would work to include results (showing discussions that listed the current user as a participant) it doesn't work to exclude results.

This is because a contextual filter on the current user with "excludes" checked only excludes the one of these rows that matches the current user. It doesn't exclude all the rows from that discussion. Therefore I get false positives: the view shows all discussions that have someone other than the current user listed as a participant.

Right now I'm thinking that I either need to figure out some arcane HAVING clause and add it to the query programmatically, or try to use the pre-alpha Flag module (setting a per-user flag and filtering by that instead of field_participants).

You could use hook_views_query_alter() to modify SQL query.

/**
 * Implements hook_views_query_alter().
 */
function example_views_query_alter(ViewExecutable $view, QueryPluginBase $query) {
  if ($view->id() == 'discussions') {
    // Exclude discussions the current logged user has participated in.
    $uid = Drupal::currentUser()->id();
    $nids = Drupal::entityQuery('node')
      ->condition('type', 'discussion')
      ->condition('field_participants', $uid)
      ->execute();
    $query->addWhere(0, 'nid', $nids, 'NOT IN');
  }
}

In the example above we are getting ID's of excluded nodes using entity field query and then them to NOT IN condtion.

The resulting SQL query will be as follows:

SELECT node_field_data.created AS node_field_data_created, node_field_data.nid AS nid
FROM
{node_field_data} node_field_data
WHERE (nid NOT IN ('1', '2', '3')) AND (node_field_data.type IN ('discussion'))
ORDER BY node_field_data_created DESC

Alternative way would be using JOIN with extra conditions:

/**
 * Implements hook_views_query_alter().
 */
function example_views_query_alter(ViewExecutable $view, QueryPluginBase $query) {
  if ($view->id() == 'discussions') {
    // Exclude discussions the current logged user has participated in.
    $uid = Drupal::currentUser()->id();
    $definition = [
      'table' => 'node__field_participants',
      'field' => 'entity_id',
      'left_table' => 'node_field_data',
      'left_field' => 'nid',
      'extra' => [
        0 => [
          'field' => 'field_participants_target_id',
          'value' => $uid,
        ],
      ],
    ];
    $join = Drupal::service('plugin.manager.views.join')->createInstance('standard', $definition);
    $query->addRelationship('participants', $join, 'node');
    $query->addWhere(0, 'field_participants_target_id', NULL, 'IS NULL');
  }
}

The generated SQL query:

SELECT node_field_data.created AS node_field_data_created, node_field_data.nid AS nid
FROM
{node_field_data} node_field_data
LEFT JOIN {node__field_participants} participants ON node_field_data.nid = participants.entity_id AND participants.field_participants_target_id = '1'
WHERE (field_participants_target_id IS NULL) AND (node_field_data.type IN ('discussion'))
ORDER BY node_field_data_created DESC

The view itself becomes quite simple. No need of contextual argument and aggregation.


Clean and easy way to add meta tags to my D7 website I'm looking for a easy way to add meta tags to my D7 website. Not that I'm afraid of code or anything like it, but the content managers (Marketing => biggest IT noobs you've ever seen) want to add meta-tags by using the Drupal UI.

I've checked the MetaTags Quick-module, but it seems like this module is only capable of adding path-meta tags. Are there any alternatives? Or what is the most clean way to add meta tags do my Drupal 7 website?

For Drupal 7 the Meta tags module is the way to go:

  The Meta tags module allows you to automatically provide structured metadata about your website.

MetaTags Quick is also good, but Meta tags has more features.


Line item custom field value not be saved after update line item I added a custom field into line item type, but it cannot be edit on order edit page. My environment: commerce_kickstart-7.x-2.22(With IEF 1.5 and the widget: Inline entity form - Multiple values)

Steps to produce this issue:

Add a "field_additional_information" text field on    admin/commerce/config/line-items/product/fields, Do not include it on    "add to Cart from".
Switch widget line item manager into inline entity form - multiple values.
Edit order on admin/commerce/orders/%commerce_order/edit, click "Edit" link to edit a line item, "field_additional_information" field is shown, fill something in it.
Reopen admin/commerce/orders/%commerce_order/edit page, click "Edit" link again, the value of "field_additional_information" field is not be shown(leave blank). Check database, the value is not be saved.

Many problems on Drupal Commerce make me distracted recently. Any comment or help would be appreciated, Thanks!

I have to "save" the whole form at bottom of the page, not only update that line.


sort the content based on click count I'm using Link Click Count module.I want to sort the view content based count.how to list sort the content based on link click count.now It displayed the node 4 times if the count is 4.

Configure the link click count module
Add new field in content type and set 'count the click happened on the link' in manage display
Use the default link click count stats view
In sort criteria, add the link node id and chooose the you wanted order.

whenever you click the field in the node, It will be get counted
The sorted result based on the click of the link will be shown in the view's result


How to render node content according to site theme after hook_node_insert/update? How can I get the actual HTML of the node when i am in hook_node_insert/update?
I would like to get the rendered HTML as it should appear in the site and save it somewhere else ...
I am working in drupal 7.

So first as the hook_node_update doc says:

  Note that when this hook is invoked, the changes have not yet been
  written to the database, because a database transaction is still in
  progress. The transaction is not finalized until the save operation is
  entirely completed and node_save() goes out of scope. You should not
  rely on data in the database at this time as it is not updated yet.
  You should also note that any write/update database queries executed
  from this hook are also not committed immediately. Check node_save()
  and db_transaction() for more info.

Solutions:

There's a module for that: hook_post_action

There's also a short article about drupal_register_shutdown_function


how to fetch parts of url in javascript I have a url like this: http://localhost/something/de/

The last one is the language code de for German. I want to fetch it using javascript. The link may also become like this: http://localhost/something/de/node/artist/117/author/98, in that case how do I fetch the language part.

Actually I want to set up placeholder using javascript, I got the help for placeholder but I dont get how to fetch the language part from url.

You can do this in jQuery, just get the url and then split as required.

$(document).ready(function() {
    var $url = window.location.pathname;
});


Drupal 7: Looking for suggestions on AJAX-base update to view I have a requirement that I'm not sure how to go about implementing. The flow goes something like this:

User clicks button: share your update
Popup window opens
User fills in form and clicks Save
View is updated immediately to reflect update

I'm thinking I'll need a new content type for updates since the view being updated is for node content, not comments.

Anyway, I think I'll need to AJAX-load the node/add form, then somehow trigger the view to update upon saving the node. Perhaps it will work by using the Overlay module? (Note: I would only want the Overlay to be used in this one specific case.)

Anyone done this that can provide some pointers and/or some links?

Thanks,

Dan

Wow this was not all that difficult after all.

The following forces the overlay to only be used for my desired node type and admin pages:

<?php
  function yourmodule_admin_paths_alter(&$paths) {
  $paths['node/add/user-update'] = TRUE;
  $paths['user'] = FALSE;
  $paths['user/*'] = FALSE;
  $paths['users/*'] = FALSE;
  $paths['node/*/edit'] = FALSE;
  // Add this for each content type you don't want the overlay to be used for.
  $paths['node/add/other-types'] = FALSE;
?>

Then I needed a rule to redirect to my view (home page in this case) after the content was added:

{ "rules_redirect" : {
"LABEL" : "Redirect to home page",
"PLUGIN" : "reaction rule",
"REQUIRES" : [ "rules" ],
"ON" : [ "node_insert" ],
"IF" : [
  { "node_is_of_type" : {
      "node" : [ "node" ],
      "type" : { "value" : { "user_update" : "user_update" } }
    }
  }
],
"DO" : [ { "redirect" : { "url" : "\/" } } ]
  }
}

The combination of the two makes it appear as if the user is adding a "quick update".


How to add a report an error button in a Drupal 7 website and collect user's browser details? We just did a website upgrade. On some sites I have seen a 'Report an error' icon (in the right hind corner). After clicking on it, a user can report an error which will send along other information about their system like OS, the user's browser and what link they were on when the error occurred.

Question: Any suggestions on which module to use for it and/or how to add such 'Report an error' to the website?

Update: I am looking for something like whatismybrowser.com, which can be added like a button or tool.

You could check out the Feedback module to see if it meets your needs - it's pretty simple and lightweight. If you don't want to use a contrib module, you could do something similar to the Feedback module - create a block (either using existing blocks in your theme or create a new block region programmatically), position it absolutely, and then link the 'Report an Error' block text to some kind of web form where you can collect the desired information. You could also use the Webform module to help you quickly create a form.


Term reference redirect after node save i am new to Drupal. I have few nodes with term reference. After creating nodes with term reference, i want to redirect user not on created node, but on term page. Is this possible?

You can set redirect state for your node form. For example

function my_module_form_alter( &$form, &$form_state, $form_id ){
  if($form_id == 'your_node_form_id') {
    $form['actions']['submit']['#submit'][] = '_mymodule_node_redirect';
  }
}

/**
 * Custom Submit Handler to set conditional redirection rule.
 */
function _mymodule_node_redirect($form, &$form_state) {
  // If terms are already in the system.
  if($form_state['values]['your_taxonomy_field']['und'][0]['tid'] ==  'tid_to_compare_with') {
    $form_state['redirect'] = 'whereever you want';
 }
}


Allow users to choose from multiple avatars while registration in drupal 7 Currently I am working on a website registration page and I want a new user to select a default avatar from a given list if they have not uploaded a profile image while they are registering. I am using drupal 7 so avatar selection module is not compatible with this version so can you kindly suggest me some other way out

Have you tried Avatar Selection for custom images ?
Also you can try the Gravatar module to use with this service.


Trigger ajax callback from input field webform I have a form build with the webform module. When text is entered in the input box in this case webform component 2 I want it to execute a ajax function and put data in a div. However this is not working at the moment. When i connect the ajax to $form['actions']['submit'] it does work.But i want it to be stuck to the input box not the submit function. The function is placed in the hook_form_alter.

$form['#node']->webform['components'][2]['#ajax'] = array(
  'callback' => 'callback function',
  'wrapper' => '#foo',
  'method' => 'replace',
  'effect' => 'fade',
);

I figured out you cannot attach ajax to webform components you need to add them to $form['submitted']

$form['submitted']['TEXTFIELDNAME']['#ajax'] = array(
  'callback' => 'callback function',
  'wrapper' => '#foo',
  'method' => 'replace',
  'effect' => 'fade',
);


Can users switch to different Profile2 profiles? I'm trying to implement a membership site and am considering using a Profile2 profile form as an application for membership.

So I'd make a profile type for Membership A. The user would apply for Membership A, get admin approval, then be given an account with Membership A.

Later, they might want to upgrade their membership to B. Can they just switch their Profile type to a different one? Or submit a request for this and an admin changes their profile type?

Note that Membership A has fields 1,2,3,4 and Membership B has 1,2,3,4,5,6,7,8,9. So maybe just add a second profile type (B, with fields 5,6,7,8,9) rather than switch?

It's up to you whether it is better to duplicate fields 1 - 4 or not. That depends on your specific requirements, what the fields are, etc.

In my experience I generally go with A (1, 2, 3, 4), B (5, 6, 7, 8, 9) and the fields are usually logically grouped into each profile.
For example there might be 2 profiles like "Personal information" and "Employment information" or something like that, which obviously will have their own different grouping of fields, but I can see there may be cases where you might want to go the other way.

One annoyance that you might have to deal with if replicating fields is that when a user switches types they have to enter information into fields they already filled out in the other profile. That would annoy me as a user. You could work around that though and auto fill the fields.

Either way, you can control access to different profile types based on user role.

So the easiest solution would be to configure a role for each of the profiles and then have an administrator add/remove the roles from users as required.

If your use case allows for it there are also modules that allow users to change their own roles (you can limit it to specific roles so they can't make themselves an admin), for example role delegation. This might be appropriate for some websites. Just make sure they can't give themselves any dangerous permissions.


Maintaing Images when switching servers I just changed the server one of my sites is hosted on. In doing so, I lost all the images. The CCK file upload fields show "ghost" data but contain no actual image data as they did before the site transfer.
All my data is fine, however.

Is there a way to prevent this so all my images are maintained?
Thanks

What module are you using to upload/show images? CCK + ImageField?

Anyways, to troubleshot your problem you need to figure the reason why no images are shown. This can be due to several reasons:

Wrong file Permission. When uploading via FTP or CPanel sometimes sometimes file permission gets messed. Try setting permission to 777 recursively to your image folder and see if images appear.
different absolute path. Some modules use an absolute path to figure in which folder they should upload images to. one easy way to find out is to create/upload a new image via CKK and using firebug (for instance) compare the URI of old images to the URI of the new image.

Keep us posted


How to redirect a user to a visited sub-domain on his next visit to main domain I have a website say example.com with 5 sub-domains: site1.example.com, site2.example.com, site3.example.com, site4.example.com, and site5.example.com.

When users visit example.com, they are presented with the other 5 sub-domains to choose from. I want to implement something that redirect the users to the sub-domain they choose the first time they visit the main domain. I know I can use cookies for this, but how can I implement this in Drupal?

This implementation of hook_init() should be present on your subdomains but not on your main domain:

function YOUR_MODULE_NAME_init() {
  if(!isset($_COOKIE['your_cookie_name'])) {
    /*Your need to set cookie for your main domain, as well as for all your subdomains otherwise once a user visits another subdomain by typing the url directly in the address bar the cookie would be overwritten*/
    setcookie('your_cookie_name', base64_encode($_SERVER['HTTP_HOST']), YOUR_EXPIRATION_TIME, '/', 'example.com');
    setcookie('your_cookie_name', base64_encode($_SERVER['HTTP_HOST']), YOUR_EXPIRATION_TIME, '/', 'site1.example.com');
    setcookie('your_cookie_name', base64_encode($_SERVER['HTTP_HOST']), YOUR_EXPIRATION_TIME, '/', 'site2.example.com');
    ...
    setcookie('your_cookie_name', base64_encode($_SERVER['HTTP_HOST']), YOUR_EXPIRATION_TIME, '/', 'site5.example.com');
  }
  else {
    header('Location: ' . base64_decode($_COOKIE['your_cookie_name']));
  }
}

Your main domain should have a module with the following code:

function YOUR_MODULE_NAME_init() {
  if(isset($_COOKIE['your_cookie_name'])) {
    header('Location: ' . base64_decode($_COOKIE['your_cookie_name']));
  }
}

I didn't test this code, but I am positive it should work, or at the very least it illustrates the approach.


How to interlace ouput of nodes two content types in views I have nodes of two different content types and want to output them interlacing in a view. So nodes of type A are on odd places and nodes of type B on even ones.

Is there a straight-forward way to do this?

You could create a view that outputs the two node types and then use hook_views_pre_render() to sort, shuffle, or arrange the $view->result array any way you wanted.  Then when it is rendered in the next steps, it would be printed however you wanted.  You would hook into this like:

function YOURMODULE_views_pre_render(&$view) {

  if ($view->name=='thisistheviewyouarelookingfor') {

    // do whatever you want with $view->result[]

  }

}

MORE INFO:  $view->result[] is an array of "rows" basically, eg $view->result[0] contains all the raw data that makes up the first row, $view->result[1] is the second, etc.


How to restrict Drupal commerce Shipping only for two provinces we have a drupal commerece site http://floristerianoe.com, that need only to deliver (commerce shipping) in Madrid and Guadalajara (only two privinces in Spain) and we can´t find the option to do this, we only find the option to restrict contry, but we need this for province or city.
Thanks in advence.

If you are using the Address Field module, you definitely have Madrid and Guadalajara as options. Thereafter, you need to use rules and add conditions. I'm not sure how your shipping works but I would use the Flat Rate module to create components, such as 0-5km, which costs a set amount. Create a flat rate, give it a name: perhaps 0-5 km, and a price then add conditions. Select "Order address component comparison". Province will be available. Your operator is "equals" and then you add your values, Madrid and Guadalajara.

Here is a screenshot of a rule that restricts shipping costs being applied to a certain country, within weight parameters and restricts it to a particular product but it is possible to select a province instead of a country

Here is a screenshot of the components, I selected province here to show that it is available


Can I add to an existing Entity schema from my own custom module I'm extending a the Quiz module; by having taking extra data regarding the test .   For this I have a custom module that redirects using a custom form .

It all works fine but as its only a single value I'd like to just add it to the existing 'Quiz result' entity.  I know how to do this by hacking the 'contrib' module
OPEN 'quiz.install' and adding it to the $schema['quiz_node_results'] array.

Once its added here I can then see it in Views as needed.  But obviously this solution isn't good enough.  Is there a way to add to an existing Entity schema from my own custom module; rather making a separate table in SQL for this info.

I've tried hook_schema_alter as well, but can't seem to get that to work either.

Here's what I had in my my_module.install file

 function my_module_schema_alter() {
  $schema = array();
  // Create the quiz node results table
  $schema['quiz_node_results']['fields']['time_taken'] = array(
    'type' => 'int',
    'size' => '10',
    'not null' => TRUE,
    'default' => 0,
    'description' => 'Stores the user inputted estimated time.',
  );
}

function my_module_install() {
  $ret = array();
  $schema['quiz_node_results'] = array();
  rcni_saq_extended_schema_alter($schema);
   foreach ($schema['quiz_node_results']['fields'] as $name => $spec) {
    db_add_field($ret, 'quiz_node_results', $name, $spec);
  }
}

Many thanks for any help.

your my_module_schema_alter is missing a schema parameter.

fixed:

function my_module_schema_alter(&$schema) {
  $schema = array();
  // Create the quiz node results table
  $schema['quiz_node_results']['fields']['time_taken'] = array(
    'type' => 'int',
    'size' => '10',
    'not null' => TRUE,
    'default' => 0,
    'description' => 'Stores the user inputted estimated time.',
  );
}


why feed importer cron fails? In my drupal 6 website, we have used feed importers to import feed, but from few days We are not getting new feeds and then I have gone to 'status report' in admin panel and checked status report & I found that cron is not running.As I have seen that there is problem in cron I imported feed manually and it worked for me.

When I tried to run feed import cron manually from status report page I got error "cron run failed"

As I am new to Drupal, I dont know that from where I should start cron failed troubleshooting.

Can anyone suggest me the way.

I got the answer to this problem.

I used debug code if ($hook == 'cron') watchdog('cron', "hit $module cron"); in function module_invoke_all()

where to put debug code ?

In module.inc file of core drupal, add

 $function = $module .'_'. $hook;
 $result = call_user_func_array($function, $args);

between this two line of module_invoke_all() function, add above debug line.

It will look like :

$function = $module .'_'. $hook;

if ($hook == 'cron') watchdog('cron', "hit $module cron");

$result = call_user_func_array($function, $args);

After putting above line in module.inc,run cron manually and check log in recent log entries.

Because of this debug statement, I found the module which was not allowing to run cron.

I corrected the custom module code in that and cron started working fine.


Adding the video field to a content type We've been using an SWF player for a while. I added the Video module without adding a new content type, just to see if the HTML5 tag worked. It does. However, that obviously doesn't give us an SWF fallback.

I then tried to add a Video content type as per this video tutorial, but when I did it, I didn't see the Video field type or an option for 'video-widget'. Is that a feature present only in Drupal 7, or did I miss something in configuring the Video module?

How do I enable the Video widget so I can have HTML5 and the SWF fallback? Is there an alternative set of HTML to get this done?

I was facing the same issue, then I realized that we were doing it the wrong way.

You have to select "file" drop down "Select a Field Type", then "Video" becomes available in the next drop down labelled "Form element to edit the data".


How to instantiate a service inside ServiceProvider? I need to instantiate a service inside ServiceProvider.
At that point the container is not built.

Any ideas or useful links?

<?php

namespace Drupal\my_module;

use Drupal\Core\DependencyInjection\ContainerBuilder;
use Drupal\Core\DependencyInjection\ServiceProviderBase;

class MyModuleServiceProvider extends ServiceProviderBase {

  public function register(ContainerBuilder $container) {
    parent::register($container);

    // How to get a service here?
    // Currently container is not built :)

  }

}

You can't get services at this point.
This interface ServiceProviderInterface is only for registering services, not for retrieving
For retrieving service with future altering try to use ServiceModifierInterface


What is the purpose of the Version Control API module? We are relatively new to Drupal development and are investigating various tools that can assist us with some upcoming projects.

The Version Control API module seems interesting, especially since it's semi-official.  I think we have some confusion regarding it's actual purpose, however.

See the link here: http://drupal.org/project/versioncontrol

Assuming we get this configured properly with a git backend, how does this change our workflow while developing with Drupal?  Will resources that we add to the website (such as graphics and html) be added to git source control automatically?  Does this git source control replace the existing Drupal "revision" feature?

Any additional information or real-world examples of how to use this module would be appreciated.

Documentation, as Clive pointed out, provides good technical explanation. For those who need more "human-readable ones": Every time you download module from Drupal.org or any Drupal page, use issue queue or in any other way interacts with module or theme version, you are using Version Control API or other module with the same purpose.


How can I build a subscription product selling system with drupal commerce I'm creating an Drupal commerce website, I want to sell subscription to internet via satellite service.
Sincerely I'm confused and I don't know what modules I should to use for this kind of product.

Check Commerce subscription products module.

  Features

  Sell subscriptions via products.
  Administers can view and customize the subscription validity per user    if they have necessary field permissions.
  There are two "rule sets" (Subscription starts, Subscription ends)    that make customizing the subscription easy, e.g. one could    easily    add rules for granting/removing a user role.
  Subscriptions expire automatically once the validity time is reached    thanks to the Rules Scheduler (requires cron to function).
  Views integration, as the subscription validity date is implemented    as account field.
  Custom notifications like "Warning: Subscription expires in 2 weeks"    can be easily configured using Rules and the Rules    Scheduler.


How do you include a field.tpl.php, to a custom views field handler. outside of the theme? so i've created my custom field handler in views. and i want to include a field template in the module. i can achieve what i need by copying the views-view-field.tpl.php into my theme. but i want views-view-field--MYMODULE.tpl.php to be scanned and used from the module folder..

do i need to "declare a theme function" in my

class views_handler_MYMODULE extends views_handler_field

THANKS

If you want to have a template file being loaded from your module's templates folder, you should do the following:

Implement hook_views_api to tell Views where you keep views templates, e.g. your_module/templates
Following the naming conventions for Views and add views-view-field.tpl.php into your module's template folder, e.g. your_module/templates

After you clear your cache and rescan the template folders using Views UI, your tpl file should be selected.

Hope this helps, the main source for this answer was https://stevenyeung.com/article/template-override-drupal-views-3-from-module/


Add query condition for referenced user by user ID I have created a content type with machine name user_points and let's say have the following fields for this content type:

nid,
title,
reference_id (text),
user (reference of user entity),
points (integer)

the following code give me the sum of all points.

$storage = $this->entityTypeManager()->getStorage('node');
    $total_points = $storage->getAggregateQuery()
      ->condition('status', 1)
      ->aggregate('points', 'SUM')
      ->condition('type', 'user_points')
      ->execute();

I would like to add a condition to get total points for specific referenced user by user ID. How can I do it?

if the machine name of user entity referenced in user_points content type is for example field_my_user, the following condition can be added to the query above to select only nodes with referenced user equal to $user_id

->condition('field_my_user.entity:user.uid', $user_id)


Get total row count in views-view-fields.html.twig How can I get the total rows number in views-view-fields.html.twig template file in Drupal 8? In Drupal 7, I can get it by the following code.

$view = views_get_current_view();
$view->total_rows;

Is there any variable to render the total number of rows in Drupal 8?

You can use simple code {{ view.total_rows }} in every file template views. Variable view is global.


give permission of create new revision to specific roles I need to give the permission of "create new revision" to a specific role. but nothing related to this issue appeares in permissions page! I've installed Revisioning module too.
how can I set it?

permissions (minimum):

  node:

  View published content

  View own unpublished content

  View content revisions (optional)

  [content type]: create new content

  revisioning:

  [content type]: view revisions of own content

For content types, in its edit UI:

  Publishing options: Create new revision, New revision in draft,
  pending moderation (requires "Create new revision")

if you want to do it with Drupal core only, then this will suffice:

  node:

  View published content

  View content revisions (otional)

  [content type]: create new content

For content types, in its edit UI:

  Publishing options: Create new revision


How do I find if a taxonomy term is used? I'm using drupal6 taxonomy.The content type 'B' is using a tag field which can use the title of the some of nodes of the content type 'A'.If any node of 'B' tagged a name or title of a node of content type 'A', I want to display one message in the respective node of 'A'.

Alternatively, is there any way to find if www.mysite/category/tag/term doesn't gives the "Page not found" error? This is to find if the term is used, or not.

If you have the term name, you can use the following code.

$nodes = array();

if ($term = taxonomy_get_term_by_name($term_name)) {
  $result = taxonomy_select_nodes(array($term->tid), 'or', 0, FALSE, 'n.sticky DESC, n.created DESC');
  while ($row = db_fetch_object($result)) {
    $nodes[] = $row->nid;
  }
}

if (!empty($nodes)) {
  // The taxonomy term is used from at least a node.
}


Multiple image sizes from one uploaded image? In my content type, I've got an image uploader. That image then gets processed by an Image Style that scales the image. I want to produce multiple scaled sizes of that image though. So essentially, I need to assign multiple Image Styles to that one image upload. In the UI, I can only assign one. This is Drupal 7, by the way.

So, for example: I start by uploading an 800x600 image and I've applied an Image Style to output it at 400x300. Now I want to apply another Image Style to get a 200x150 version. And so on...

Surely, I'm missing something here! Seems like a straightforward request. Thanks in advance!

This is the function that I was looking for:

image_style_url($style_name, $path)

More info here.

(Should have done a little more digging via Google before I asked!)


Paragraph migration for link field not working I have below migration script for paragraph migration, where I have 2 fields,
(1) icon_type --> List(text) field type
(2) icon_url --> Link field type
UPDATED WORKING CODE BELOW
If I run the migration script only icon_type is created but not the icon_url
id: icon_type_link
label: Icon Type Link
migration_group: devel
source:
 plugin: csv
 path: 'modules/custom/my_custom_module/data/icon_type_link.csv'
 keys:
   - id
 header_row_count: 1
destination:
 plugin: entity:paragraph
process:
 type:
      plugin: default_value
      default_value: icon_type_link
 uuid: uuid
 entity_id: entity_id
 icon_type: icon_type
 icon_url/uri: url
 icon_url/title: title
migration_dependencies: {}

I guess both icon_url and icon_type are fields of your paragraph entity.
Remove the leading blanks in front of the line

icon_url:

until it has the same indentation level as icon_type.

(Whitespaces are very important in YAML: Indenting something blanks makes it a child of a previous line with less blanks. In your example icon_url has 2 blanks and therefor it is a sub value of field icon_type. With only one blank [same as icon_type and all the other fields] it means that icon_url is a direct child of the global process [the one without blanks].)


How to register Post Submit handler for form? I have a form which I want to modify some of it's data after submission.

I'm using drupal 8.3 and I tried to used hook_form_alter and registered my functions to $form['#submit'][] and $form['actions']['submit']['#submit'][]  but none of them working after form submission.

Any help? Thanks.

I added the following snippet in hook_form_alter:

array_unshift($form['#submit'], 'callback');
foreach ($form['actions'] as $action => $values) {
    if (isset($form['actions'][$action]['#submit']) && is_array($form['actions'][$action]['#submit'])) {
        if (!in_array('callback',$form['actions'][$action]['#submit'])) {
            array_unshift($form['actions'][$action]['#submit'], 'callback');
        }
    }
}

This registers to all actions.


Non-directional/symmetric relation between nodes of the same content type In a Drupal 7 website I would like to create an "is similar to" relation between nodes of the same content type. The nodes are vessels (ships) and a vessel can be similar to several others.

Think of the similarity as a Volkswagen Golf I is similar to the VW Golf II, Golf III and so on. The relation is symmatric, because the VW Golf IV is similar to the Golf VII and vice versa.

In the current custom made website, which will be migrated to Drupal 7, there are over 6500 relations between vessels.

I've tried several modules, but I can not create what I intend:

the Relation module can not create relations between endpoints of the same entity type (e.g. nodes of the same content type);
the module Entity reference only creates directional relations. This would mean creating two references per relation, ending up with over 13000 references;
the References module also only creates directional relations, again ending up with over 13000 references.

So the question is: how do I create non-directional/symmetric relations between nodes of the same content type?

Corresponding entity references fixes this for you:

  CER keeps reference fields in sync. If you have two entities that refer to each other using Entity Reference (or some other kind of reference field), it saves you the trouble of double-editing your entities in order to have them point at each other. If entity Alice references entity Bob, CER will make Bob reference Alice, and keep the references up-to-date when either entity is updated or deleted.


Can composer-dependent PHP libraries be used with the Libraries API? I'm trying to include a PHP library called Geocod.io in my custom module. I am also trying to use the Libraries API. So far I have:

Downloaded geocod.io to sites/all/libraries
composer install'ed in sites/all/libraries/geocodio
Started creating a hook_libraries_info() function with the following contents:

return array(
  'geocodio' => array(
    'name' => 'Geocod.io',
    'vendor url' => 'http://geocod.io',
    'download url' => 'https://github.com/davidstanley01/geocodio-php',
    'version arguments' => array(),
    'files' => array(
      'php' => array('geocodio/vendor/autoload.php'),
    ),
  ),
);

I have no idea what to put for 'files', is the path the the autoloader the right thing to do? Are these two ways of including things even compatible? I'm a bit stumped as to what to do next, I want to use the geocod.io library and I want to do it the most correct way. Other questions that mention these issues don't seem to include anything about how to list the files/versions.

This is not really a direct answer to your question, but as an alternative to using the Libraries API (which I too have struggled with in this context), check out the Composer Manager module. It works nicely for PHP libraries installed via Composer, and takes care of the autoload seamlessly.


Use a 3rd part library when uninstalling a module my module uses several third part PHP libraries, loaded by using the library module supported by the x_autoload (several third part libraries are based on composer, so this support directly pointing to the composer file).

Just to provide you with an example:

function mymodule_libraries_info() {
  $libraries = array();
  ...
  $libraries['mongo-php-library'] = array(
      'name' => 'mongo-php-library',
      'vendor url' => 'https://github.com/mongodb/mongo-php-library',
      'download url' => 'https://github.com/mongodb/mongo-php-library/releases',
      'path' => 'src',
      'version arguments' => array(
          'file' => 'RELEASE-1.0',
          'pattern' => '/RELEASE (\d+\.\d+\.\d+).*/',
          'lines' => 1,
      ),
      'versions' => array("1.0.4"=>array()),
      'xautoload' => function($adapter) {
        $adapter->composerJson('composer.json');
      },
  );
  ...
  return $libraries;
}

Everithing works fine (I can use this library in my working code) except for the "uninstall" part.

In fact, I need that the hook_uninstall() can access to this library in order to perform several operations, but I receive a WD php: Error: Class 'MongoDB\Client' not found error.

I guess this is related to a specific problem: when I try to uninstall the module, it has already been disabled, so its libraries are no loger available when I call the "uninstall".

How can I deal with this problem?

Not knowing what "operations" you are performing with this composer lib, I suggest you might want to just think of when you actually want to perform these operations. Doing it on Uninstall seems like a bad idea. Why not utilize hook_disable, instead of hook_uninstall, which should allow you to do things just before the module gets disabled.

If you really want to do it in a hook_uninstall, then you can load your .module file using drupal_load() and call the functions in your .module file from hook_uninstall.


Backup & Migrate: Restored changes lost after clearing cache I have a live and a development version of a Drupal 7 site. I want to keep them as close in content as possible so I am using the Backup and Migrate module to take a backup of the live site and restore it onto the development site. This works fine until I clear the cache on the development site after the restore and things like views, menu items and entity forms disappear for some reason. They work fine after the restore up until I clear the cache.

Anybody have any idea what's going on?

I'm using the features module if that makes any difference.

Sorry, but your approach is wrong.

If things gets to disappear after cache clear, you have some serious bug in your implementation.

You should exclude all cache tables from migration.
After migration, you should clear cache of recipient site.

If your procedure is different, it's buggy. Details may vary but these two points are pretty much needed for consistent workflow.

If one of your sites generates different menu than the other after cache clear, then you failed to migrate some files that provide hook_menu or hook_menu_alter, or you have a problem with migrating menu data in database. Either way, disable cache for migration, don't ever try to rely on migrated cache.


Add custom CSS code for a textbox in form The following are the code in my module function for textfield in my form:

 $form['price'] = array(
   '#type' => 'textfield',
   '#title' => 'What is Your Price?',
   '#size' => 100,
   '#maxlength' => 10,
   '#required' => TRUE,
  );

Now I want to add css for the textbox like I want to add inline code display:none; only for the textbox. How can  I do that? Please help.

I do it like this:

function the_form($form, &$form_state){
     $form['price'] = array(
       '#type' => 'textfield',
       '#title' => 'What is Your Price?',
       '#size' => 100,
       '#maxlength' => 10,
       '#required' => TRUE,
       '#prefix' => '
',
       '#suffix' => '
',
     );


How to create a filter in Views for filtering dates by day, month, or year? I have a few thousand nodes with different dates as one of the fields. I am trying to create an exposed filter in views that allows the user to filter by day, month, or year.

For example, I would like someone to be able to enter "July" and get all the nodes associated with July, regardless of their day or year. I would also like users to be able to filter for "July 6" of any year or only "July 1973." Likewise, I would also like the user to have the ability of drilling right down to "July 6 1973" with the filter.

I have created a view with day granularity and an "equal to" operator. While this allows the user to select by day, month, and year ("July 6 1973"), any time only day, month, or year is put in, the form indicates that the other parts of the date need to be entered as well.

Does anyone have any suggestions?

I ended up creating a module that made three new fields - month, day, and year - and then processed the date field to populate these new fields. Then it was simply a matter of adding a view with exposed filters for month, day, and year.


How to wrap / manipulate element outputs on a form's checkboxes html? I have the following form that contains a big list of checkboxes. The first checkbox is the parent of the children below it. In my case it is called "Africa" and the ones below it are "Africa-child" checkboxes. I was able to manipulate the classes, but I can't seem to find a way to add a wrapper div around the "Africa-child" elements. I mean I can do it via javascript, but I was wondering if there was a Drupal hook to add in extra html to the select options html before it gets outputted.

The code below is it form data used to build the form. The prefix and suffix is wrapping ALL of the checkboxes, but I only want to wrap certain ones.

function hotsite_filters() {

  $form['offices'] = array(
    '#type'       =>  'checkboxes',
    '#title'      =>  '',
    '#options'      =>  get_office_options(true, '', 'local_alias ASC', false, true, true, false, true),
    '#default_value'  =>  filter_get_keys('browse-offices'),
    '#prefix'     =>  '

' . variable_get_value('hotsite_filter_offices_header') . '
',
    '#suffix'     =>  '
',
    '#size'       =>  11,
    '#multiple'     =>  true,
    '#required'     =>  false,
  );

You could use your get_office_options function and add some html

For example:

$alphas = range('A', 'Z');
    foreach($w_question->get('field_option_radio') as $key => $option){
        $options[$option_id] = '<i></i>'.$option_text;
    }

    return $options;


Autologin feature killing my website I have a drupal 7 site.

Running a auto login feature when people click on my newsletter.

A hook is fired when they visit the site to check for the cookie.
my setup :
Background info : I am already using Memcache, APC, Varnish,

2 Varnish Servers (8 GB)
1 Db percona server (32 GB)
1 HaProxy 4
Webservers, 16 GB

my question is, Performance wise. I can see that my server cannot handle 8000 users logging in.

Is there any way to make this impact on the server more "soft" in terms of performance. So my DB doesnt go down. when 8000 request auto login at the same time.

Example 1.

Ex: 1 request to auto login, causing 3-4 query to DB via  the core Drupal API if so if I get 1000 users at the same time I got 3000 queries to DB -> DB cannot handle the load. What to do ?!

Best regards

Victor

You could cache the content and displaying it cached would ideally take stress off your database. Check out module "Boost" it can help.

Ideally optimization of the site is what is needed along with better hardware and maybe Varnish.

If you are using views consider using views built in cache with time based expiration to take stress off database.

Update

If you already have Varnish, APC and memcache then the only other think you can really do is get some better hardware.

We have servers that get about double what you have and they run on a quad core processor with 32GB of RAM.

We also split Web and DB server so we can utilize APC for Web Server and memcache for DB server.

Have you checked your APC stats? Varnish probably won't do much unless you configure it to cache Authenticated traffic which by default bypasses Varnish.

What are your server stats?


Search inside the view, if not found, how to set up no results behaviour? All view need a No results behaviour, this applies to Courses list(view), information list(view) and activities list(view);please tell to how to do this

Please set this at the field level or at the right corner at the views edit.

No Result Behaviour. If you want to set this with all the views than select All display at field level.


Do not let Drupal handle 404's on development environment Drupal handles 404 error pages, but on localhost that can be very annoying, especially if you have missing assets (such as uploaded images). For each image, CSS and such that is not found, a drupal is bootstrapped and ran.

How can one best disable this?

Removing the line ErrorDocument 404 /index.php from .htaccess gives no change. Should that work?

Changing it to ErrorDocument 404 "development not found" does not work either.

Newer versions of Drupal have an addition to settings.php so that it doesn't handle the 404 for certain assets:

$conf['404_fast_paths_exclude'] = '/\/(?:styles)\//';
$conf['404_fast_paths'] = '/\.(?:txt|png|gif|jpeg|css|js|ico|swf|flv|cgi|bat|pl|dll|exe|asp)$/i';
$conf['404_fast_html'] = '<title>404 Not Found</title>
Not Found

The requested URL "@path" was not found on this server.
';

There are comments in the file that explain these new options some more.

You can also edit the .htaccess to disable the ErrorDocument and then put some ErrorCond directives in to prevent missing files from being punted to index.php:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !=/favicon.ico
RewriteCond %{REQUEST_URI} !files/foo/(.*)\.bar$
RewriteRule ^ index.php [L]


Meaning of "Query results" and "Rendered output" in Views cache? Previously I've set the "Query results" and "Rendered output" cache to 1 hour.

What I need is:

Cache for 1 hour
Update the cache immediately when related node updated

But when updating node, it takes exactly 1 hour for the views page to be updated.

I'm quite confuse about what is "Query results" and "Rendered output"?

Is "Query results" the GET request?

“Query results” are raw data from DB. After fetching data you often do some additional work (modifications, templates) with data and then render it to HTML in some way — so you get a “Rendered output”. For more flexibility you have two levels for caching here.

As I think (I can be wrong!) here is no sense to set “Query results cache” time less than “Rendered output cache”.

Your use case, as I can see, to flush View cache immediately after new content added. You can solve it with additional staff Cache Actions, which requires Rules.
For example, you can create a rule with event "After saving new content" or "After updating existing content", condition "Content is published" and one of the Cache actions.

Cache will be flushed regardless of cache settings in your view.


How to programmatically list member entities of an Organic Group? How can I programmatically get a list of member entities of an Organic Group?

(I know how to get a list of group members using Views — I'd prefer to do this using the Organic Groups API, but haven't been able to find the right method.)

Using directly the Organic Groups API:

og_get_group_members_properties($yourGroupNode, array(), 'members', 'node');

gives you an array of user ids.

To obtain only active, pending or blocked users, you can put 'members__1', 'members__2' or 'members__3' in place of 'members', like in this example:

og_get_group_members_properties($yourGroupNode, array(), 'members__1', 'node');

of, if you prefer, like this one:

og_get_group_members_properties($yourGroupNode, array(), 'members__' . OG_STATE_ACTIVE, 'node');

Example of the returned value:

Array
(
    [0] => 48
    [1] => 49
    [2] => 51
)


Assign a submitted Node to a Single User of Role Editor I am building a content publishing website. There are users with different roles editors, authors, content managers. There are many users with each role. Now what needs to be done is to assign a node to a specific user with a role as an editor or you can say to a specific editor.

I am using workflow module which puts the article to a review state once it is submitted. Now what it does is it allows all of the user with a role as an editors to edit and review the node. But I want that it should only be assigned to one editor and that should be done by the content manager.

I can not get my head around how should this be done. Are there any modules available or I would need to write something myself?

I haven't test it, but the module's description seems to match your needs:

https://drupal.org/project/nodeaccess

Otherwise it can be done with a custom module: add a field "authorized editor" of type user reference to your content type, and then use the node_access function to grant access to the update operation to the user who is currently trying to edit it.


Relation between field of two webform I have created two webform as Vendor and Sponsors.There is two sponsorship type as gold and platinum in sponsors and each vendor is sponsors. Now i want to show in Vendor view the type of sponsorship this vendor have. Both are separate modules. I am not able to understand how to do this.

As far as I know you can not reference a webform submission from another webform. The functionality you describe is needed here is something I recommend using standard Drupal content types for.

Create a content type called Vendor and another one called Sponsor. Use the module Entity reference to create a field that describes the reference between the content types.

Webforms are great for simple forms, surveys etc but not in this use case.


How do I get a block to use a URL to configure a contextual filter? Blocks do not have paths so how can I pass a context to the block to get the correct results for a page?

I am new and do not have enough reputation to answer my own question for eight hours (Go figure!)  The answer for this question will  come after the time limit has expired.

A views page can read the url and use a path for the page to read a taxonomy term input for a contextual filter.  A URL such as example.com/a/term/b would be read by the view page with a path of a/%/b.  The value for the % in the URL is passed in to the contextual filter to determine what content to include in the view.

Since a block doesn’t possess a path it is necessary to do a bit more configuration to achieve the result. To do so:

Click on the contextual filter on the block view form in views.
Under When the filter value is NOT available select Provide default value.

If the page in the path is a taxonomy term try this step 3 and 4:

Choose Taxonomy term ID from URL from the Type drop-down box.
Check Load default filter from term page.

Or otherwise try this:

Choose Raw value from URL
Identify which part of the URL is the term. eg. for A/term/B the term is in the second position.

Then:

Under When the filter value IS in the URL or a default is provided check "Specify Validation criteria"
Select Taxonomy term and the specific vocabulary being used.
Under Filter Value type pick term name converted to term ID"
Checking Transform dashes in URL to spaces in term name filter values will ensure that any auto generated path alias' that have converted spaces to dashes are properly handled. Try your view with this checked and unchecked.

If your view is not appearing on the page troubleshooting steps should include verifying that the view works by testing input in the view preview. Make certain that any spaces are handled to match up with the setting in step 8. Also make certain that your view block is exposed in admin/structure/block.


slideshow images for one specific view, with alot of fields I have a product content type which has like 10 fields, so I want to show it in my main page with view, the problem is, I want to show it's multiple images as a slideshow, It's not only images that I can use views_slideshow or nivo_slider or any other slideshow modules, I only want the images to be shown as slideshow, along other text-fields of my node.

I would really appreciate any help, thanks

you can use Field Slideshow. If it's not a good solution, another one would be to create 2 views (one slideshow with only the images, one normal with all the other fields) and, with CSS, position one over the other.

Have fun !


How can I make a mobile app that is basically a mobile browser to access my live Drupal site? There is a question about exporting Drupal pages for use in a mobile app, but I would like to know if there is an easy way to make a mobile app (iOS, Android, etc.) that simply loads the existing site in a browser for online-only access.

I looked into Phonegap, but (as far as I can tell) you have to export the pages as HTML for that.  However, the primary purpose of my site is to send messages back and forth using the Private Message module, so making the site accessible offline makes no sense.

I already have a responsive theme, so the site also looks decent in mobile browsers.  I just want a mobile app because I want the site to appear in App Store and Google Play searches.

Is there a straightforward way to address this use case?

There is no module(convenient) to build all apps in Drupal, You have to build your own or if you have a mobile site then you can do it without Drupal help, see my article for android app. There are so  many builders like iBuildApp, Appypie, Como, and so many.


Mouseover overlay for images using Views Photo Grid Trying to add a hover overlay for node title and a couple of other fields for images using  the views photos grid module.

The fields to be used in the overlay need be excluded from the display as the module only uses one image field, however I am not managing to add the excluded fields.

If I the preprocess to template.php

`function THEME_preprocess_views_photo_grid_style(&$vars) { $vars['raw_result'] = $vars['view']->style_plugin->rendered_fields;}`

I can print the titles using

`foreach ($raw_result as $row) {print $row['title']; }`

which prints the titles on the page outside the container as a row, but I can only add the last title to the overlay.
Need to be able combine each title to each image that is shown using

`foreach ($items as $key => $item):

print $item;
endforeach;

As the arrays line up, added an index and combined the arrays

$index = 0; foreach ($items as $key => $item):
print $raw_result[$index]['title']; $index++
print $item;

Works


How do I force-indicate a vocabulary as a source for node breadcrumbs? I have two vocabularies on my site, each node of certain content type has 2 term reference fields - one per vocabulary, single value only. For browsing through both vocabularies I am using Taxonomy Menu and Taxonomy Breadcrumb modules.

As long as I'm browsing through terms, the breadcrumb is ok, the problem starts when I step down to a node instance - the breadcrumb path is then always taken from vocabulary A, while what I want is the path from vocabulary B.

In the content type definition I checked vocabulary A as the source of active trail for menu (this is Taxonomy Menu setting most probably). Apparently that does not influence the breadcrumb. However, none of the options in the Taxonomy Breadcrumb config screen seems to have any impact on the source of the breadcrumbs.

What else should I check?

You can try Crumbs instead of taxonomy breadcrumb.
You can be bold and try the 7.x-2.x branch (*)

Documentation for Crumbs + Taxonomy: http://drupal.org/node/1984484

I have not personally tried it in combination with taxonomy menu, but think it should work ok.

To solve the problem on node pages:

Install Crumbs
Visit Admin > Structure > Crumbs to adjust the plugin priorities (*).
The taxonomy.termReference.field_vocab_B.node.certain_node_type (**) needs to be moved up, into the "Enabled" section.

You can do more stuff with Crumbs (you could even replace taxonomy menu with menupoly), but one question at a time.

(*) The crumbs-7.x-2.x, among other things, has a revamped admin UI to set the plugin priorities. It is still not perfect, which is the main reason there is no 7.x-2.0 stable yet.

(**) Thanks to the wildcard system, you could also move taxonomy.termReference.field_vocab_B.node.* or even taxonomy.termReference.field_vocab_B.* into "Enabled", instead of taxonomy.termReference.field_vocab_B.node.certain_node_type. Doing that would activate this behavior for other node types and/or other entity types that have field_vocab_B.


Translated node does not use translated entity reference, how to fix this? So I have 2 translatable content types: event and artist.
I've also created an English artist and his French translation.

I now create an English event and link my English artist to it through Entity References. If I now translate my English event to French, my French event will have a reference field with my English artist instead of my French artist...

How can I solve this problem?

I want it to try to fetch the translated reference and if it does not exist, I want to entity referenced field to stay empty.

Some people told me this happends on default, but I've just set up a test site with i18n and entityreferences enabled, and it gives the same result.

But I found a sandbox project that worked for me after changing one line of code in the entityreference_translation.module:

This didn't work:

if ($item['target_type'] == "node") {

This works:

if ($field['settings']['target_type'] == "node") {


Import translation file only for specific core module I am creating a multilingual D7 website. I am using core module locale and i18n contrib module. I am trying to import the localization files for a language.

I know that I can download the unified .po file for a language from https://localize.drupal.org and import it in the multilingual website from http://EXAMPLE.COM/admin/config/regional/translate/import.

Is there a way I can export from https://localize.drupal.org a .po file only for a specific core module (eg contact)? I can do this for a contrib module but not for a core module.

Thanks a lot.

Nope, you cannot.

Translations are stored per project, not per module, and core is one project. Of course there is experimental Contact project on Drupal.org, but it's translation stays pretty empty as it's not needed.

Worse, in exported files (at least in my language) there is no metadata, no comments about modules these strings originated. So manually cutting this file to your needs would be pretty hard, too.


How to get the base URL of a site My site is on http://drupal8.local/. How do I get the drupal8.local part of that URL?

Url::fromRoute('<'current'>') or base_path() returns the path parth of the URL; For example, for http://drupal8.local/a/b/c/d/e/f, they return '/a/b/c/d/e/f' when I just need to get 'drupal8.local'.

How can I get that part of the URL?

You can get the hostname, "drupal8.local", directly from the getHost() request:

$host = \Drupal::request()->getHost();

In some cases you might want to get the schema as well, fx https://drupal8.local:

$host = \Drupal::request()->getSchemeAndHttpHost();


Assign custom id for user on registering I need to assign custom ids for all users. The Id will come from API and its depend on other filled by user custom field. Witch hook should I use and witch variable holds id value?

I presume you're referring to a login ID - you should be able to use hook_form_alter to access the registration form, and create a default value.

get Devel module and use dpm($form) in that function to look through the array to find the exact element you want to change.

after that you can probably use a number of options to hide the element, including css so that the user can't change it before being submitted.


How can a description be added to the body field summary widget in node edit form? On a particular content type I have made summary input required by checking both
"Summary Input" and "Summary required" on the body field settings.
We would like to add a help text to the summary field on the resulting form. I have tried using hook_form_BASE_FORM_ID_alter as seen below which is working for the title field.
$title_description = 'Why we need a title.';
$title_widget =& $form['title']['widget'];
if (empty($title_widget[0]['value']['#description'])) {
  $title_widget[0]['value']['#description'] = $title_description;
}

I am having a hard time finding the summary in the $form array however.
To recap how can I alter this widget to add a description?

I assume you're using Drupal 8.
Try the below in your hook alter. This also assumes the usage of the default body field in use:
use Drupal\Core\StringTranslation\TranslatableMarkup;

// Ensure summary field existence.
if (isset($form['body']['widget'][0]['summary'])) {
  $form['body']['widget'][0]['summary']['#description'] = new TranslatableMarkup('Your summary description goes here.');
}


How to debug a server reset or WSOD? We have recently observed that we can put Drupal in an inconsistent state where it responds with a server reset or WSOD, where no data is sent. This by simply having some faulty configuration (See CCK field migration reproducibly results in server error )

We have started to doubt the robustness of the our Drupal instance (and even Drupal in general if it is so easy to push off the tracks), so we want to look into this event further and understand exactly why, because in any case even a cryptic error message would be preferred over just dying.

How to debug such a situation, properly? There is no output whatsoever, neither in the logs nor to the browser. We have enabled the devel module debug outptu an krumo output, but it dies before this. We have also tried to catch sql queries using pg_top, nothing.

What do?

To debug more on WSOD, you can always go to Server (Apache2/httpd) error logs or if accessible Recent logs Messages (Admin => Reports => Recent Log Messages) in Drupal.

You can find more details about WSOD and debugging it on below link:
Blank pages or "white screen of death" (WSOD)

Hope this helps.


Implement javascript inside body, error: jQuery is not defined In Drupal 7, I had js-output template.

I define the template output as javascript. This is used for our front end person that can easily input javascript without touching backend.

<script>
<?php if(isset($content['field_custom_javascript'])) print $content['field_custom_javascript']['#items'][0]['value']; ?>
</script>

In Drupal 8, I am trying to do the same thing by define twig file:

{% if content.field_custom_javascript is not empty %}
<script>
    {{ content.field_custom_javascript }}
</script>
{% endif %}

But when I put js in the customize_js_output field, as the following:

(function ($, Drupal) {
 $( document ).ready(function() {
    console.log( "ready!" );
 });
})(jQuery, Drupal);

Or

 $( document ).ready(function() {
        console.log( "ready!" );
  });

Have jQuery is not defined or $ is not defined error.
Got all of jQuery libraries load correct in the footer.

My question:
Is this a good way to do it? If not, do you have any suggestions?

If i only want to write js inside my body field in the source or even php filter as content editor, can I do it?

In Drupal 8 it is not a good idea at all. You must define a library and put your js in a seperate file.

Here is a link to how to do it

Libraries in Drupal 8

Then if you want to write jquery you just need to add a dependency on core/jquery, also explained on the link.

If you want to attach a library to a twig function, you can do like this:

{# In a Twig template we attach the library. #}
{{ attach_library('modulename/libraryname') }}


Devel issue - "Rebuild the theme registry on every page load" won't work I use D7. My site is being hosted on a "Shared" Server at Siteground.com. My site doesn't have any CSS/JS aggregation what so ever (see attachment), and I'm sick and tired of clearing the cache after the smallest of the CSS changes.

Many people told me that installing Devel and enabling "Rebuild the theme registry on every page load" should solve the problem, and will let me see the CSS changes after a refresh (F5/ctrl+r/ctrl+f5), but the fact is that even after I did that and enabled the Theme registry rebuilding option, I still have to clear caches to see the CSS changes, so I'm still stuck with this, and it's indeed frustrating!.

So, why would "Rebuild the theme registry on every page load" won't work? Why do I still need to flush all caches to see the CSS changes?

Not a straight solution and not really the best one but it seems that the co-problem; clearing the cache after every css change, was mainly server-sided, rather than Drupal sided --- I store at siteground.com and it was a Cpanel tool named "Supercacher" that caused all this mess and apparent lifetime wasting (and yet it raises the chance for good SEO when you site is finished).

Anyway, When you develop, better turn it off in Cpanel.

Btw, this was enough by it's own for me... Neither Devel nor any other external module is needed for this solution to work... Just disable the tool at Cpanel.


Real-time workflow scheduled transitions? I have a simple workflow and am trying to figure out a way to get workflow scheduler to make node state changes in real time, at their scheduled time.

I set the state change on a node to occur at 09:00 from draft to live.
If cron runs before 09:00, the state does not change until the next time cron runs.
If the next time cron runs is not until 11:00AM, the state change doesn't occur until 11:00.

This is a problem since editors expect their content to go live when they tell it to go live. This does not seem like difficult functionality, but maybe I missing something basic. I understand that I can run cron more frequently, but it seems crazy that my cron schedule has to match the editor's publishing workflow, as in, "you should always have articles go live at 9am because that's when cron runs". What happens when editors want a node to go live outside of the normal cron schedule? It seems I missing a way for Drupal to "wake up" at this time and run cron to make the node live. Does anyone have a way to do this that I am overlooking? I find it hard to believe that news sites running in Drupal like economist.com or examiner.com don't have this type of real-time scheduling functionality. Thanks in advance.

You can use Elysia Cron to let the workflow cron hook run every minute, without sacrifing performance by having other cron hooks run that often.

See Multiple (and differents) crons?


Using drupal_add_css to dynamically add inline CSS based on term reference I'm trying to create a CSS class called .bg-unit-color which will change depending on the taxonomy reference chosen

I've set up a course category taxonomy and then set up a color field within it using jQuery Colorpicker module.  I've got to the point where I can render the color in my node--example.tpl.php file with the following:

<?php
$term=taxonomy_term_load($node->field_example_category['und'][0]['tid']);
$category_color=field_view_field('taxonomy_term',$term,'field_example_category_color');
echo render($category_color);
?>

I've also used the drupal_add_css function in my template.php file, so this works:

$new_color='black';
drupal_add_css(".bg-unit-color {background-color: $new_color;}", 'inline');

However I can't marry the two together to create what I'd like to do which is this:

drupal_add_css(".bg-unit-color {background-color: $category_color;}", 'inline');

Any help would be massively appreciated. Thanks in advance

If using render you should attach the css to that render array.

$term = taxonomy_term_load($node->field_example_category['und'][0]['tid']);
$category_color = field_view_field('taxonomy_term',$term,'field_example_category_color');
$name = $term->name;
$category_color['#attached']['css'][] = array(
  'data' => ".bg-unit-color {background-color: $name;}",
  'type' => 'inline',
);


How to programmatically assign (attach) a file to file field while creating/saving the node? I'm trying to assign (not upload) files to nodes programmatically.
This is the scenario:
I will create 2000 nodes and there are 2000 PDF files (one PDF per node). I don't want to upload these files via Drupal interface. I will upload all these PDF files via FTP.
These PDF files are well-named, I mean all of them have a standardized name such as {field_magazine_name}-{field_issue_number}.pdf (under sites/default/files/pdf for example).
What I want to do is to assign these PDF files to related nodes while creating/saving the nodes.

Possible Method 1
One method to do this would be to use the File Field Sources module.

I think remote file transfer can be used with some JavaScript code. The remote file transfer input can be automatically filled with the fields I want and it will work (for example http://example.com/sites/default/files/pdf/{field_magazine_name}-{field_issue_number}.pdf)... but I don't create nodes manually, I'm creating the nodes via Feeds. So, using JavaScript isn't the method I can use.
Is there any way to programmatically assign (attach) a file to file field while creating/saving the node?

I had a similar situation. My situation is attach a file to a node in the creation of a different content type node. Done this in hook_node_insert

Initially i uploaded all files into a temp directory in /default/files/.
Then for each node, i created a new file object with my file attributes.
Then moved that particular file into the destination where i want the files to be placed. This results a clean complete file object with fid.
Then simply assign this file object attributes to file field and save the node.

The code used is follows..

$source_node = node_load($nid);
$filename = $bio_file_name; //your specific filename
$dir = 'public://temp-path/'.$filename; //path to specific file with name
$file_size = filesize($dir);

//New file object
$file = new stdClass;
$file->uid = $source_node->uid;
$file->filename = $filename;
$file->uri = $dir;
$file->filemime = file_get_mimetype($dir);
// Make it permanent, otherwise it will get deleted later.
$file->status = FILE_STATUS_PERMANENT;
// Save file object to make it a 'managed file'.
$file_obj = file_move($file, 'public://newpath', FILE_EXISTS_REPLACE);

$source_node->your-file-field-name['und'][0] = array(
 'fid'  => $file_obj->fid,
 'uid'  => $file_obj->uid,
 'filename'  => $file_obj->filename,
 'uri'  => $file_obj->uri,
 'filemime'  => $file_obj->filemime,
 'filesize'  => $file_obj->filesize,
 'status'  => 1,
 'display'  => 1,
 'description'  => '',
 );

 node_save($source_node);

Hope this will help you..


Installing Acquia BLT on an existing site We have a working Drupal 9 installation (running within Docksal), which has pretty much the whole install living in docroot/ except for the config/ directory, which is a sibling of docroot/.  This application is fairly plain-vanilla--no custom modules, just some well-known contrib modules and normal config.  I will refer to it herein as the "working app."
In order to get this application onto Acquia Cloud and set up our CI/CD we hope to use their BLT utility.
We have tried several approaches to get BLT working with this application:

Create a Docksal Drupal 9 BLT boilerplate application and attempt to use
composer install to get the same set of modules as the working app, and
then import the working app's configuration with fin drush cim.
Create a Drupal 9 BLT
boilerplate application and hand-edit composer.lock with selections
from the working app's composer.lock file, run composer install, and
then import the working app's configuration using fin drush cim.
Install BLT within the
working app as described here:
https://docs.acquia.com/blt/install/adding-to-project/.

Approaches 1 & 2 did not work because of incompatibilities between the BLT boilerplate app's composer configuration requirements (minimum-stability dev and prefer-stable true) and those configurations in the composer.json file of the working app.  There were also version incompatibilities between the contrib modules in the working app and those which the BLT boilerplate app wanted to install.   Hand editing the composer.json file also proved equally fruitless.
Using approach 3 we got as far as installing BLT in that the blt/ directory and associated files are now present, but blt doctor complains of a missing docroot/docroot directory.  Looking at the differences in the filesystem layout between the BLT boilerplate app and the working app made it seem like it might be worth trying to move vendor/, sites/, composer.json and composer.lock up one level from within docroot/ such that those two directories and two files are now siblings of docroot/ and seeing if that satisfies blt doctor.  Doing this of course breaks the application and makes composer unhappy.  I have tried the following:

Deleting everything in vendor/ and running composer install
Running composer dump-autoload
Hand-editing docroot/autoload.php looking for and
attempting to edit incorrect filesystem locations within the
relocated vendor/ directory

As you can imagine, none of the above have worked and we are just about at the end of our patience with this endeavor.
I have a few general questions:

Are any of the three approaches above likely to result in a successful BLT install?
With regard to approach 3, is there a generally accepted method of moving either vendor/, composer.* and/or the sites/ directory as described above?

Thank you in advance for any general or specific help you can offer.

You have two distinct problems here:

"Composerizing" your codebase
Installing BLT

The latter should be pretty painless once you've got the former (theoretically more painful) out of the way.
Fortunately, the Composerize Drupal plugin should get you most if not all of the way there. From the description of your project, you'll want to run this in the root folder (the one containing config/ and docroot/). You don't need to move anything out of the docroot/ folder yourself, anything that needs to be updated will be.
Once that process is complete, run database updates (contrib modules may have been updated to more recent versions), clear cache, verify the site is working, and commit the changes.
At this point you have the structure BLT is expecting, so following the installation instructions again (link in your third approach) should work out a bit better.