file unmanaged save upload I'm moving some existing functionality into a new Drupal site.

Files are uploaded via posted form
Their file names are prefixes with UID
They are then moved to temp holding directory
A cron job on another server SCPs the files in batches
The files are verified copied, then deleted via batch ssh command

I'm looking for a clean way to handle (save) an uploaded file coming from a submitted form with an element of type 'file' without "managing" it. I've browsed over file_save_upload() and like the validation/error handling it offers.

However, I'd rather not have the files exist in the managed file tables. I would need to modify my pulling server's cron job to trigger a managed deletes via web request.

Just as there is a file_save_data() and analogous file_unmanaged_save_data() I'm looking for file_unmanaged_save_upload(). I basically want the first half of file_save_upload() before it touch the database. It seems like something similar or a workaround should already exist but I haven't found one. I trying to avoid reinventing the wheel.

I suggest using file_save_upload() anyway, beacause (as the API docs say):

  The file will be added to the {file_managed} table as a temporary file. Temporary files are periodically cleaned. To make the file a permanent file, assign the status and use file_save() to save the changes.

So you don't need to worry about having the file "managed" by Drupal as long as you don't change the status of the file to FILE_STATUS_PERMANENT.

Otherwise, if you really don't want this default behaviour (and also no hooks to get invoked), just copy the file in your form_submit() using file_unmanaged_copy() (give it uploaded tmp file as source).


Content List vs Administer nodes New Drupal and playing with permissions. I can't figure out how to get a content list or something similar if the Administer Nodes permission has been disabled.

I'm trying to restrict a user role, strip down the admin menu, e.g. remove 'Post Settings' under content management.

I have a feeling I'm doing this wrong, so my question is: Can I create a user menu, same as the admin menu without certain links and how?

You could use views to create a list of all the nodes on the site and make sure the role has access to see it. This is by far the simplest and quickest way of implementing such a feature.

A more complex way would be to alter the menu link and change it's access control but I wouldn't recommend doing this.


How do I alter a form using an AJAX callback? I have this callback function triggered by an onChange() event in another select box.
This code, however, doesn't make the field enabled

public static function changeForm(array &$form, FormStateInterface $form_state) : array {
  $form['field_my_custom_field']['#disabled'] = FALSE;
  return $form;
}

What am I doing wrong?

Ajax Forms in Drupal 7 states:

  Changes to the form must only be made in the form builder function. The callback function must not alter the form or any other state.

In form build/alter, check $form_state->getTriggeringElement() for the triggering element and then enable the field.


Using D7 OG I want to force (auto) join - any ideas? I'm using D7 Organic Groups to create custom member profiles such that when a new user registers, a rule creates a group with their name (/member/firstname-lastname) and redirects them to their group's home page where there is a "build-profile" panel using quicktabs to guide them through the 7 steps of building a complete profile.  The build panel is visible until such time as they complete the final step at which point they are autoassigned a new role which uses a different page layout sans the build panel.

This all works well.  When users browse for other users they are actually directed to the associated /member/firstname-lastname page for the user whose profile they are viewing.

Here is the issue I'm now having.  I need to make it so that when a user "follows" another user (joins or subscribes-to their group) I want the owner of the group being followed to automatically "follow" (join or subscribe-to) their group.

This is really only doable because each member only "owns" or is admin to a single group, so it should be relatively easy to say - if user-a (owner of group-a) joins group-b (owned by user-b) then user-b joins group-a.

I'm just not sure programatically how to do this.  Can anyone help me with a code snippet to do this?

I'm going to assume that you are using the 7.x-1.x branch of Organic groups. I believe there are some major changes in the 2.x branch - so this solution may/may not work with that.

// Assuming your group is of the entity type "node"
// and the name of your bundle is "group". A node bundle
// is the unique name of the content type which is a group
// type as well.
// Say $follower is the follower user entity and
//     $followee is the followee user entity
$opts = array(
  ':uid' => $follower->uid
  ':type' => 'group'
);
$gnid = db_query('SELECT nid FROM {node} WHERE type=:type AND uid=:uid', $opts)->fetchField();
if ($gnid) {
  $group = og_get_group('node', $gnid);
  og_group($group->gid, array(
    'entity type' => 'user',
    'entity' => $followee,
    'state' => OG_STATE_ACTIVE
  ));
}
else {
  watchdog('my_mod', 'Follower (uid=!uid) does not have a member group', array(':uid' => $follower->uid), WATCHDOG_ERROR);
}

Still, own (group manager) and is admin of are two different things, at least in OG parlance. Because a user may have the "administrator user" role in many groups. If you mean is admin of, the lookup of the node table above may have to be changed by doing a join with {og} and {og_users_roles}.


How do I add a "Add more" button? I want to  show a Add more button that adds an extra text field and the corresponding Remove button.

I followed ajax_example_add_more() to achieve this in Drupal 7. For Drupal 8, I tried with the following code.

class XmlfeedsSettingsForm extends FormBase {
  public function getFormId() {
    return 'formid';
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
   // Because we have many fields with the same values, we have to set
  // #tree to be able to access them.
  $form['#tree'] = TRUE;
  $form['names_fieldset'] = array(
    '#type' => 'fieldset',
    '#title' => t('People coming to the picnic'),
    // Set up the wrapper so that AJAX will be able to replace the fieldset.
    '#prefix' => '
',
    '#suffix' => '
',
  );

  // Build the fieldset with the proper number of names. We'll use
  // $form_state['num_names'] to determine the number of textfields to build.
  $form_state->getValue['num_names_parent'] = '';
  if (empty($form_state->getValue['num_names_parent'])) {
    $form_state->getValue['num_names_parent'] = 1;
  }
  for ($i = 0; $i < $form_state->getValue['num_names_parent']; $i++) {
    $form['names_fieldset']['name'][$i] = array(
      '#type' => 'textfield',
      '#title' => t('Name'),
    );
  }
  $form['names_fieldset']['add_name'] = array(
    '#type' => 'submit',
    '#value' => t('Add one more'),
    '#submit' => array('::ajax_example_add_more_add_one'),
    // See the examples in ajax_example.module for more details on the
    // properties of #ajax.
    '#ajax' => array(
      'callback' => '::ajax_example_add_more_callback',
      'wrapper' => 'names-fieldset-wrapper',
    ),
  );
  if ($form_state->getValue['num_names_parent'] > 1) {
    $form['names_fieldset']['remove_name'] = array(
      '#type' => 'submit',
      '#value' => t('Remove one'),
      '#submit' => array('::ajax_example_add_more_remove_one'),
      '#ajax' => array(
        'callback' => '::ajax_example_add_more_callback',
        'wrapper' => 'names-fieldset-wrapper',
      ),
    );
  }
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit'),
  );

  // This simply allows us to demonstrate no-javascript use without
  // actually turning off javascript in the browser. Removing the #ajax
  // element turns off AJAX behaviors on that element and as a result
  // ajax.js doesn't get loaded.
  // For demonstration only! You don't need this.
 // if ($no_js_use) {
    // Remove the #ajax from the above, so ajax.js won't be loaded.
//    if (!empty($form['names_fieldset']['remove_name']['#ajax'])) {
//      unset($form['names_fieldset']['remove_name']['#ajax']);
//    }
//    unset($form['names_fieldset']['add_name']['#ajax']);
 // }

  return $form;
  }
  public function ajax_example_add_more_add_one(array &$form, FormStateInterface $form_state) {
      print_R($form_state);die;
  //$form_state->getValue['num_names_parent']++;
  //$form_state->setRebuild(TRUE);

}
public function ajax_example_add_more_callback(array &$form, FormStateInterface $form_state) {
  return $form['names_fieldset'];

}
public function ajax_example_add_more_remove_one(array &$form, FormStateInterface $form_state) {
  if ($form_state->getValue['num_names_parent'] > 1) {
    $form_state->getValue['num_names_parent']--;
  }
  $form_state['rebuild'] = TRUE;
}

print_r($form_state) in buildForm() outputs the following.

[getValue] => Array
        (
            [num_names_parent] => 1
        )

In ajax_example_add_more_add_one(), the num_names_parent index is missing.

How can I correctly add the Add more button?

It works !! Try this
<?php

namespace Drupal\fapi_example\Form;

use Drupal\Core\Form\FormStateInterface;

class AjaxAddMore extends FormBase {
  public function buildForm(array $form, FormStateInterface $form_state) {
    $form['description'] = array(
      '#markup' => '
'. $this->t('This example shows an add-more and a remove-last button.').'
',
    );

    $i = 0;
    $name_field = $form_state->get('num_names');
    $form['#tree'] = TRUE;
    $form['names_fieldset'] = [
      '#type' => 'fieldset',
      '#title' => $this->t('People coming to picnic'),
      '#prefix' => '
',
      '#suffix' => '
',
    ];
    if (empty($name_field)) {
      $name_field = $form_state->set('num_names', 1);
    }
    for ($i = 0; $i < $name_field; $i++) {
      $form['names_fieldset']['name'][$i] = [
      '#type' => 'textfield',
      '#title' => $this->t('Name'),
      ];
    }
    $form['actions'] = [
      '#type' => 'actions',
    ];
    $form['names_fieldset']['actions']['add_name'] = [
      '#type' => 'submit',
      '#value' => $this->t('Add one more'),
      '#submit' => array('::addOne'),
      '#ajax' => [
      'callback' => '::addmoreCallback',
      'wrapper' => 'names-fieldset-wrapper',
      ],
    ];
    if ($name_field > 1) {
      $form['names_fieldset']['actions']['remove_name'] = [
      '#type' => 'submit',
      '#value' => $this->t('Remove one'),
      '#submit' => array('::removeCallback'),
       '#ajax' => [
        'callback' => '::addmoreCallback',
        'wrapper' => 'names-fieldset-wrapper',
      ]
      ];
    }
    $form_state->setCached(FALSE);
    $form['actions']['submit'] = [
      '#type' => 'submit',
      '#value' => $this->t('Submit'),
    ];

    return $form;
  }

  public function getFormId() {
    return 'fapi_example_ajax_addmore';
  }

  public function addOne(array &$form, FormStateInterface $form_state) {
    $name_field = $form_state->get('num_names');
    $add_button = $name_field + 1;
    $form_state->set('num_names', $add_button);
    $form_state->setRebuild();
  }

  public function addmoreCallback(array &$form, FormStateInterface $form_state) {
    $name_field = $form_state->get('num_names');
    return $form['names_fieldset'];
  }

  public function removeCallback(array &$form, FormStateInterface $form_state) {
    $name_field = $form_state->get('num_names');
    if ($name_field > 1) {
      $remove_button = $name_field - 1;
      $form_state->set('num_names', $remove_button);
    }
    $form_state->setRebuild();
  }

  public function submitForm(array &$form, FormStateInterface $form_state) {
    $values = $form_state->getValue(array('names_fieldset', 'name'));

    $output = t('These people are coming to the picnic: @names', array(
      '@names' => implode(', ', $values),
      )
    );
    drupal_set_message($output);
  }
}


How to programmatically stop a migration? Say I want to stop a migration that I'd like to stop on preImport under similar circumstances as a dependency not being fulfilled, is there a way to do this?

I would like to stop the migration and prevent postImport from running, preferably from preImport().

public function preImport() {
  parent::preImport();
  if($this->externalDependency == 0){
  // Stop the migration, and maybe even throw an error.
  }
}

According to my comment on Luke solution, here is the complete code to interrupt you Migration in Migrate these days.

public function preImport() {
  parent::preImport();
  if($this->externalDependency == 0){
  throw new MigrateException('Dependencies were unfulfilled.');
  }
}

public function postImport() {
  parent::postImport();
  if($this->externalDependency == 0){
  return false;
  }
  // My code here
}

public function processImport(array $options = array()) {
  try {
    $result = parent::processImport($options);
    return $result;
  }
  catch (MigrateException $e) {
    $this->endProcess();
    drupal_set_message($e->getMessage(), 'error');
    return MigrationBase::RESULT_STOPPED;
  }
}


How to display an individual list of user created nodes? I'm having a block on the front page with a list of users displaying their profile fields like: picture, full name, e-mail etc. I achieved this by simply creating a User View in Views displaying it as a block.

Now I want to add an extra option to it that gives a list of the user's created node articles. So that their articles (per user) will be visible as a list and displayed like the profile fields.

I've tried several ways but all to no avail. The following approaches got me close:

Made a relationship "User: Representative node" and added a Node Title field to the View with this relationship. The way this relationship works is what I actually want, I think. The thing is: it obtains a SINGLE representative node for each user but I want to obtain ALL the nodes for each user.
Made a seperate user View (block) with relationship "User: Content authored" and contextual filter "Content: Author uid". Having the Node Title as a field again. I tinkered a bit with the contextual filter and setting it with "User ID from logged in user" gets me a nice list of nodes of the logged in user. But that's not what I want, I want to show all content of each user separately. Providing a default value "User ID from URL" gives me nothing. Probably because the block is on the frontpage.

Can anybody tell me what's the solution, or just give some ideas? I'm on it for days now and I'm out of ideas.

The simple "non-coding" version would be:

install Views Field View module
create a separate node view with a contextual filter that filters by node author
in your first/initial view, add the "uid" as a hidden field
in the same first/initial view, add a "views field" that is displaying the view created at point 2
in this "views filed" settings add the uid field as an argument


Running code only once when building a form I have built a form using the field API. The function hook_field_widget_form gets called for every field. I have a bit of code that populates a select box but it is being called for every field in the form - see the first 10 lines of the code below.

function mango_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {

  $library = libraries_detect('d3_custom_scripts');
  if($library) {
    $libs = libraries_get_libraries();
    $custom_scripts_path = $libs['d3_custom_scripts'];
    $files = file_scan_directory($custom_scripts_path, '/.*\.js$/');
    $custom_script_list[''] = t('Please select');
    foreach ($files as $file => $info) {
      $custom_script_list[$info->filename] = $info->filename;
    }
  }
  dpm($items[$delta]);
  $item =& $items[$delta];
  $element += array(
    '#type' => 'fieldset',
  );

  $element['enabled'] = array(
    '#title' => t('Enabled'),
    '#type' => 'checkbox',
    '#default_value' => isset($item['enabled']) ? $item['enabled'] : '',
  );

  $element['custom_script'] = array(
    '#title' => t('Attach script'),
    '#type' => 'select',
    '#options' => $custom_script_list,
    '#default_value' => isset($item['custom_script']) ? $item['custom_script'] : '',
  );
  return $element;
}

Is there a ay to only run the code once and pass in the variables into the hook_field_widget_form function so I can avoid calling the same code over and over when I only really need to call it once?
Many thanks.

Use built-in caching!

At the beginning of your function, test if results are already prepared in cache:

function mango_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {
  // Construct cache id. Let's start with function name, as it should eb unique
  $cid = __FUNCTION__;
  // Now let's add a fast hash of everything important. Seems only $items matter
  $cid .= '-' . hash('adler32', serialize($items));
  // Oh, and language, too!
  $cid .= '-' . $langcode;

  // Do we have results for this set of parameters?
  if( $result = cache_get($cid)  ) {
    // We do, return it.
    return $result->data;
  }

At the end of your function, just before you return value, save it to cache:

  cache_set($cid, $element);

That's all. It will not prevent your function from being called, but it will prevent actual computation in it. Just be sure to choose cache id carefully. It must be fast to compute, but avoid collisions well.


list on node page where node selected on different content types I have a content type 'projects' and a content type 'staff'. So on the projects node I have two fields that list the 'staff' nodes, 'project manager' (one staff node) and 'other people' (multiple staff nodes). So what I want to do is on the 'staff' node when this is viewed on it's own to list the projects they are involved in. Is there a way in the template to grab any project link that this person might be involved in, be it leading it or just listed?

I assume you are lining the nodes via Entity Reference.

In that case use Views to grab the staff node nid and show the related projects via a relationship. Add it to your staff page via a block, EVA, Display Suite, Panels or some other contrib module (there are a quite a few that can embed a View).

The exact module you choose depends on your requirements, such as what modules you already have installed, and what other features you would like from the module.

You can do it yourself in the template if you wish, but you will have to create an SQL query for that or use views_embed_view to embed the same view referred to above directly into the template as a variable via template_preprocess_node. The problem is that the list of staff is available on the project node but not the other way round. You can solve that by having a two-way reference, by using a module such as Corresponding Entity References, but to me that sounds too convoluted.


Where to include javascript instances in drupal I've added my.js using js injector module and updated .info file.
Where do I have to create those instances?
Sorry, I'm new with technology.

To Add any js file to your Drupal site , a good way is to create a custom module and add your js file there.Following points may help you.

Create one custom module of yours. Useful Link. https://www.drupal.org/developing/modules/7
In your module , create one folder name js.
Add your js file here.You can copy paste your js file also here.
Now in yourmodule file the following code to tell drupal about your js file.

function YOURMODULENAME_init(){

 drupal_add_js(drupal_get_path('module', 'YOURMODULENAME') . '/js/yourjs.js');

}

At the end enable your custom module.You are ready to go.


How can I remove the site logo? I want to remove the logo from my site.

I found some instructions on Disabling the Drupal logo in your Drupal 8 theme. My problem is that the instructions say to unselect Logo in the toggle section of the theme settings page. I only get four options: User pictures in posts, User pictures in comments, User verification status in comments, and Shortcut icon.

I've checked in two sites. One has the vanilla Bartik theme, and the other has a subtheme of Bartik with no changes other than CSS.

How can I remove the logo?

Uncheck the Use the default logo supplied by the theme option you find under the Logo image settings section. Don't forget to clear the cache.


Sorting non-english characters in multilingual website I'm having an issue with finding good approach to make sorting works
  in a Drupal Views.

  I've multilingual website (1 database for all languages). Few
  languages are sorted wrong.

  I've read that the real issue is on database layer, however I can't set
  any specific encoding there, since database contains many different
  languages.

  What would be the most correct approach to make sorting works?
  The minimum I need atm is a sorting in a Drupal Views.

Any good approach of solving such issues?

It may help to somebody.

I end up with doing a simple module (which I'm gonna improve later) that inject COLLATE while doing query to Database so it sort everything properly.

Please feel free to comment this solution :)

<?php

/**
 * @file
 * Implements hook_views_query_alter().
 *
 * it adds 'COLLATE utf8_language_ci' to languages that are not supported by default
 * so far there are only few languages we have issues with.
 */
function views_collate_sorting_views_query_alter(&$view, &$query) {
  // views where we want to enable collation
  $views = array(
    'dictionary_overview'
  );

  // exit if the current view is not specified
  if (!in_array ($view->name, $views)) {
    return FALSE;
  }

  // define list of languages we support
  $map = array(
    'da' => 'utf8_danish_ci',
    'sv' => 'utf8_swedish_ci',
    'nb' => 'utf8_danish_ci',
    'es' => 'utf8_spanish_ci',
    'pl' => 'utf8_polish_ci',
  );

  // get current utf8
  $l = $GLOBALS['language']->language;

  if (!array_key_exists ($l, $map)) {
    return FALSE;
  }

  // get current utf8 language which we are going to add to all sort fields
  $utf8 = $map[$l];

  // add COLLATE utf8_xx_ci to all sort criteria
  $orderby = &$query->orderby;
  foreach ($orderby as &$order) {
    $order['field'] .= ' COLLATE ' . $utf8;
  }
}


How to use the Rate module to rate things inside the content? I'm quite new to Drupal so I haven't figured out how to use the Rate module for rating things inside the content of, for example, a basic page. I'm using Drupal 7.

Here is what I want to do, but I don't know how:

I have a basic page with links inside the content. I want visitors to be able to vote with thumbs up or down if the link is good. Also I want stars for voting for the contents of the other page. My problem is how to display the thumbs up and stars on my page. Do I create a widget? A view? How do I make them show on my page? A step-by-step explanation would be great!

I've spent so many hours on figuring this out, but I'm sure you can do it in just a few minutes.

I was also looking how to use the Rate module until I found how. Just:

Go to Structure > Rate Widgets.
Select the type of rate you want to create and click on Next
Enter the information. It allows you to select what type of content will have the new type of rate.

Hope it helps anybody else.


Display particular Image Style for image based on Role of User? Using ImageCache Actions there are 2 different Image Styles - e.g. S1 and S2.

What needs to happen:

User A has Role Y and when s/he views a node/user profile should always be presented with S1 images.
User B has Role Z and when s/he views a node/user profile should always be presented with S2 images.

What are the different ways this can be achieved? All suggestions very welcome.

You can use a hook_preprocess_image_style to alter the style name to use:

/**
 * Implements hook_preprocess_HOOK for theme image_style.
 */
 function mymodule_preprocess_image_style(&$variables) {
   $style = mymodule_determine_style_to_use($variables);
   $variables['style_name'] = $style;
 }

Take care that you do not alter all image styles, but only those you want/need to change, so mymodule_determine_style_to_use() should e.g have a check on $variables['style_name'] being S1 or S2.


How to modify the header  in superfish menu? I am trying to convert a html theme into drupal theme using superfish module. I can't figure out what to edit so that my menu has a different ID. So, instead of

I'd like to have
.
 Which files do I have to edit? Here is the code

Home

Who we are

Project

I'm not sure that this is a good idea because changing that ID may break the scripted functionality of a Superfish menu but that said, here goes...

I'm assuming you're on Drupal 7.

It's not a template that you'll be doing anything with. It is a theme function. When the Superfish menu is generated by drupal it is in response to a call to the theme_superfish() function. You can find detailed info info on it here: http://api.drupalhelp.net/api/superfish/superfish.module/function/theme_superfish/7

So with that in mind, you would want to override that funtion in your template.php file in your theme folder by copying the function to your template.php file, renaming it to YOUR_THEME_theme_superfish($variables) and changing the part at the end where it builds the menu.

If you have several Superfish menus and only want to affect one of them (ie: superfish-1), you can add a conditional to the function so that it only changes the ID of the menu when the conditions match.

Hope that works for you.


How to add placeholder to all Drupal 7 text forms in node page? I'm trying to add the placeholders from field description to all Drupal 7 text forms only in node page using Drupal API

I've created a module that overrides hook_form_alter

  <?php
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
    if (isset($form['#node_edit_form']) && $form['#node_edit_form'] == TRUE) {
        foreach ($form as $key => $value) {
            if ($value == "textfield") {
            $form['type'][$value]['#attributes']['placeholder'] = $form['#description'];
            unset($form['#description']);
            }
        }
    }
}

?>

How to do it using Drupal Api without using JavaScript?

I take it by wanting a Placeholder that the text is going to be removed by javaScript when the use enters text ?

If so, there are a couple of modules for that, for example :
https://www.drupal.org/project/field_placeholder

This will give you an extra setting in the field setting form so you wont have to use your description, allowing it to be used for the description.


8 - SQL error "String data, right truncated..." when creating/updating a node programmatically, but OK when inserting via the CLI. Why? When I attempt to programmatically update an event node, I get the error:

SQLSTATE[22001]: String data, right truncated: 1406 Data too long for column 'field_event_end_date_and_time_value'...

For most date fields. If I insert the record(s) with the same information into MySQL directly via the CLI, it updates/inserts correctly. Anyone have any idea what's going wrong here?

Full error from logs:

  Drupal\Core\Entity\EntityStorageException: SQLSTATE[22001]: String
  data, right truncated: 1406 Data too long for column
  'field_event_end_date_and_time_value' at row 1: INSERT INTO
  {node__field_event_end_date_and_time} (entity_id, revision_id, bundle,
  delta, langcode, field_event_end_date_and_time_value) VALUES
  (:db_insert_placeholder_0, :db_insert_placeholder_1,
  :db_insert_placeholder_2, :db_insert_placeholder_3,
  :db_insert_placeholder_4, :db_insert_placeholder_5); Array (
  [:db_insert_placeholder_0] => 7159 [:db_insert_placeholder_1] => 7750
  [:db_insert_placeholder_2] => events [:db_insert_placeholder_3] => 0
  [:db_insert_placeholder_4] => en [:db_insert_placeholder_5] =>
  2014-06-18CDT21:30:00 ) in
  Drupal\Core\Entity\Sql\SqlContentEntityStorage->save() (line 770 of
  /var/www/acg/html/core/lib/Drupal/Core/Entity/Sql/SqlContentEntityStorage.php).

My queries:

UPDATE node__field_event_end_date_and_time SET field_event_end_date_and_time_value = '2014-06-18CDT21:30:00' WHERE delta = 0 AND langcode = 'en' AND entity_i
d = 7159 AND deleted = 0;

and

INSERT INTO node__field_event_end_date_and_time (entity_id, revision_id, bundle, delta, langcode, field_event_end_date_and_time_value) VALUES(7159, 7750, '
events', 0, 'en', '2014-06-18CDT21:30:00');

work correctly through the CLI.

Output of show columns FROM node__field_event_end_date_and_time

+-------------------------------------+------------------+------+-----+---------+-------+
| Field                               | Type             | Null | Key | Default | Extra |
+-------------------------------------+------------------+------+-----+---------+-------+
| bundle                              | varchar(128)     | NO   | MUL |         |       |
| deleted                             | tinyint(4)       | NO   | PRI | 0       |       |
| entity_id                           | int(10) unsigned | NO   | PRI | NULL    |       |
| revision_id                         | int(10) unsigned | NO   | MUL | NULL    |       |
| langcode                            | varchar(32)      | NO   | PRI |         |       |
| delta                               | int(10) unsigned | NO   | PRI | NULL    |       |
| field_event_end_date_and_time_value | varchar(20)      | NO   | MUL | NULL    |       |
+-------------------------------------+------------------+------+-----+---------+-------+

Does anyone see it?

The CLI works because then you're not in strict mode and it just cuts the string off.

Your date format is wrong. It must be in the format defined by DATETIME_DATETIME_STORAGE_FORMAT
 and converted to the correct timezone DATETIME_STORAGE_TIMEZONE.


editor interface with views I had a site where the developer set up an screen that you went to directly upon logging in. it was a custom view, within a template that displayed all the content. The view was a block and displayed only to editors.  I set this all up but the blocks are not displaying. Am I missing a step here

this is all i have in my page.tpl.php file

  <div id="content" class="clearfix">
    <?php print $content; ?>
  </div>

In your page.tpl.php there's nothing regarding regions ? You're certainly missing some code like:

<?php if ($page['sidebar_first']): ?>
  <div id="sidebar-first" class="sidebar">
    <?php print render($page['sidebar_first']); ?>
  </div>
<?php endif; ?>

See page.tpl.php documentation.


Delete all nodes where the taxonomy term matches a given value I have a content type (example_content_type) with 3 3 fields: title, body, and pks_type. pks_type is a taxonomy term select list field. and 'pks_type'has 2 terms:

Type1, tid = 1
Type2, tid = 2

I have 150 nodes using those taxonomy terms. Now I need to delete all nodes from 'example_content_type' except last 5 nodes, where the taxonomy term ID is 1.

How can I achieve this with db_delete()?

The major problem here is the "except last 5" constraint. I suggest the following solution:

db_select the nodes' nids that you don't want to delete in the first step, like

$savenids = select nid from node where -whatever- limit 5.

Then db_delete the rest of the nodes like

delete from node where -whatever- and nid not in $savenids.

The -whatever- terms strongly depend on your field setup, take a look at your tables for that.


Is it possible that these modules conflict with each other? I have a view set up with the format Views Accordion. I have installed the module draggable views so that I can order each node as I like whenever I add a new node to the view. I'm finding that the sort version of this view display isn't rendering the drag and drop anchors at all. Is it possible that there is a conflict between Views Accordion and Draggable Views?

I'd like to clarify.
As far as I can tell, there's no way to use Draggable Views to reorder a View that uses the Views Accordion display format. However, as Jens mentioned, you can follow the instructions on the Draggable Views documentation page to clone the Views display and change its display format to Table or HTML List. This cloned display can then be used to order the items, and the order will be respected on the Views Accordion display (as long as it's part of the same View or uses Field API weights).


Take 2 fields in a content type with php I have a content type with the following fields:
Name, Language, Date, Photo, Text
associated with the following names for internal use:
title, language, field_date, field_photo, body

I created instances. One of these is called "Mondovi." I would like to see only the fields field_data and body of this instance. I want to use php to put them within the content or within a block. What to do?

Let assume that you are using Drupal 7

You need to know nid of node "Mondovi".

Then you can use following code:

$node = node_view(node_load(NID_OF_NODE));

// print value of body field without field label
print render($node['body'][0]);

// or print body value with field label and all div wrappers
print render($node['body']);

// print value of field_data without field label
// if field can have multiple values - use cycle to dipslay all of them
print render($node['field_data'][0]);


Drupal advanced forum - different styles for different forums With Advanced Forum on Drupal 7, how can I apply different styles to different forum posts, depending upon which forum they are in? Although I can see how to style different forums, there doesn't seem to be any way of using a different style per post depending upon the forum it is in, as there is no CSS class added denoting the posts forum.

On further investigation I believe this can be done with a combination of assigning a path to a post via pathauto, and the Context module, which can add CSS depending on the path.


flysystem error message. Driver is missing In my Drupal 8 project, I want to use the Flysystem module in order to manage files directly on a remote FTP server.
I installed the module and all external libraries via composer.
I also edited settings.php and added the FTP schema based on the README file.
Everything seems to be right, but in the status report, I always see a "Driver is missing" error message.
I don't know what wrong. I searched the Drupal website and module issue page, but I found no solution or guidelines for FTP.
Does any body know how can we use the module with FTP?

Requirements
If you look at the flysystem.install file (it's currently the same whether you installed 2.0.x or 8.x-1.x), you can see the code used for flysystem_requirements().
The general structure of the checking is as follows:

Validate the schemes in settings.php
Make sure the dependencies are installed:
a) League\Flysystem\Filesystem
b) League\Flysystem\Replicate\ReplicateAdapter
c) Twistor\FlysystemStreamWrapper
Then, it calls ensure() on the plugin for each scheme, and makes sure the plugin can be instantiated.

This 3rd step calls this code (src/FlysystemFactory.php):
  public function getPlugin($scheme) {
    if (!isset($this->plugins[$scheme])) {
      $settings = $this->getSettings($scheme);

      $this->plugins[$scheme] = $this->pluginManager->createInstance($settings['driver'], $settings['config']);
    }

    return $this->plugins[$scheme];
  }

It also provides the defaults:
  protected $defaults = [
    'driver' => '',
    'config' => [],
    'replicate' => FALSE,
    'cache' => FALSE,
    'name' => '',
    'description' => '',
  ];

Given the above information, your plugin and schema should have declared your driver with 'driver' => 'ftp'.
Solution?
Also, on the main module page under "supported adapters", it says:

Ftp (Requires the ftp extension)

Though I'm not sure, since it doesn't link to another module like the other adapters, I think it means the PHP extension. Try installing the ftp PHP extension. Here's the page for setup instructions.


Correct way to call a service in a controller I'm new to services (and drupal 8!) and trying to figure out services. I think perhaps I'm just doing the create in an outdated way. What I want do is make my 'hello generator' a service and call it in another controller with the following:

DBController.php

namespace Drupal\db\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\db\DbServices\HelloGenerator;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\Response;

class DBController extends ControllerBase
{
private $helloGenerator;

public function __construct(HelloGenerator $x) {
    $this->helloGenerator = $x;
}
public function say($count) {
    $hello = $this->helloGenerator->getHello($count);

    return new Response($hello);
}

public static function create(ContainerInterface $container) {
    $x = $container->get('db.hello_generator');
    return new static ($x);
}
}

HellGenerator.php

namespace Drupal\db\DbServices;

class HelloGenerator {

public function getHello($count) {
    $foo = 4 + 4 + 4;
    return $foo . ' ' . $count;
}

}

db.services.yml

services:
  db.hello_generator:
     class: Drupal\db\DbServices\HelloGenerator

db.db_says:
  path: /db/says/{count}
  defaults:
    _controller: '\Drupal\db\Controller\DBController::say'
  requirements:
    _permission: 'access content'

There are 3 questions here:

How to create a controller?
How to create a service?
How to use services in a controller?

1. Create a controller

1.1 Add a controller class - you did it. For others see Drupal documentation

1.2 Add a routing file - it looks like this is missing in your code:

my_module.routing.yml

my_module.my_route_name:
  path: '/my/path'
  defaults:
    _controller: '\Drupal\my_module\Controller\MyController::myAction'
  requirements:
    _permission: 'access content'

see Drupal documentation

2. Create a service

2.1 Add a service class - you did it.

2.2 Add a routing file - you did it although it contains extra code that belongs to the routing file. This is all you need:

my_module.services.yml

services:
  my_module.my_service:
    class: Drupal\my_module\Service\MyService

see Drupal documentation

3. Use services in a controller

You did it. Here's a reference for others:

3.1 Override the create() method

The controller class inherits this method from class ControllerBase. Its role is to create the controller object. Watch the method argument: it is passed the services container. Extract the services you need and pass them to the constructor:

public static function create(ContainerInterface $container) {
    $my_service = $container->get('my_module.my_service');
    $other_service = $container->get('other_service');

    return new static($my_service, $other_service);
}

3.2 Initialise services in __construct()

public function __construct($my_service, $other_service)
{
    $this->my_service = $my_service;
    $this->other_service = $other_service;
}

3.3 Start using the services


Autocomplete textfield widget? Does anybody know of a Drupal 7 autocomplete widget for textfields? I've tried Autocomplete Widgets, but the "Autocomplete for allowed values list" widget from that doesn't seem to exist in Drupal 7 -- only the other two widgets show up. My goal is to store plain text but autocomplete from a user profile field. Thanks!

Try http://timonweb.com/how-create-ajax-autocomplete-textfield-drupal-7

ALSO:
http://qandeelaslam.com/blogs/cck/converting-texfield-autocomplete-using-drupals-form-api
http://www.elevatedthird.com/blog/enable-ajax-autocomplete-drupal-7-webform-textfield

(Looking for a module,  now.)


how to make a row in a view a different style depending on the content type I have a view with two content types.  I can use views conditional to add a field depending on the content type, but how do I add a style to the entire row of content depending on the content type, for example I want content of type Article to have a class so that I can color it blue, while content of type "statistical data" will be white .

In the left top, behind format you can click the settings button. This shows you the style options dialog, where you can define a row class.

This class fields accepts views tokens (though does not provide the overview of them). So you should add a field for the content type, hide it from display if you please. Discover the token name of this field by checking the rewrite section and finally place this token in the row class field.

In my example I use the value of a php field to add row classes:


Can I change pager.inc theme? can I theme output of includes/pager.inc using drupal template system?

I want invert page links, I don't want any edit on pager.inc or CSS.

maybe invert items passed to theme_pager function

Not sure what you are asking here, you can override theme_pager() like any other theme function in Drupal. It is however quite a bit of code.

It's also relying on global functions, so you probably can't simply call the original fuction with reverted arguments.


Drupal 8 - Bootstrap paragraphs not rendering color and width classes I have installed bootstrap paragraphs module and when setting the color and width to the "Simple" bundle or any default bundles that comes with "Bootstrap Paragraphs" the classes are not being rendered on the div.

Please see image below: The classes should have been added to the wrapping div.

This is how the source looks like for this paragraph.

Am I missing anything?

Thanks in advance.

From your screenshots, it looks like it is adding template suggestions back in for the width and color fields. That makes it ignore what we are specifying in the Paragraphs bundle level templates, to print the content without those two fields.

My guess is that comes from the Field Layout module.


Database error when upgrading from Drupal 6.37 to Drupal 7.41 I have updated my site from Drupal 6.21 to 6.37 and it worked fine. Now I am trying to upgrade it to Drupal 7.41. I have changed the core as per the instructions that we follow for upgrading, but there is a database error I am seeing and don't know how can we fix it. I have googled and there were few threads asking to manually increasing the field size https://www.drupal.org/node/1133024 but it doesn't helped much and shows the same error again.

How can I fix this error?

Heading ##I see this post is a few days old, hope you are still watching.

What is happening is that the update is trying to 're-shape' the type field in the system table, to look like this in D7:

type           | character varying(12)  | not null default ''::character varying
However in D6 the field looked like this:

type           | character varying(255) | not null default ''::character varyin
g

Now you have old content in that field that is longer than 12 and would be truncated and therefore the ALTER TABLE command fails. Now, this is what I would call a messed up update system.

I think there are several options to fix this.

First make a backup of your system table.

Then open a database connection to your drupal database and check what the longest entry will be. I am assuming you are using Postgres:

select (length(type)), type from system group by type;
 length |  type
--------+--------
      5 | theme
      6 | module

That is my output, now you can check which entry is longer than 12 characters, and see if it contained any useful data.

Now, the easiest way is probably to simply do the field truncations yourself:

ALTER TABLE system ALTER COLUMN type TYPE VARCHAR(12) USING SUBSTR(type, 1, 12)

Then attempt the migration again, you still have your backup should this go wrong.

Second option depends on if you need these defined types, possibly they can simply be deleted:

select type from system where length(type) > 12;
Turn this into a delete statement if you will.

Third option is possible if no code will rely on the field size being 12.

The code for the db update is in modules/system/system.install line 2112:

function system_update_7018() {
  db_drop_index('system', 'modules');
  db_drop_index('system', 'type_name');
  db_change_field('system', 'type', 'type', array('type' => 'varchar', 'length' => 12, 'not null' => TRUE, 'default' => ''));
  db_add_index('system', 'type_name', array('type', 'name'));
}

change length => 12 to the maximum desired length, and run the dbupdate again.

I can't say which consequences each of the approaches will have and each can possibly cause follow-up errors and break other stuff, so you should try them all.

Hint: use drush for the updates, there will be a lot of repetitive tasks, roll-back-update-roll-back-update.


How can I change the year range displayed by a FAPI date field? I have created a FAPI form with an element of #type => date and it works as expected.

$form['date'] = array(
  '#type' => 'date',
  '#title' => t('Event date:'),
);

However, the options displayed in the year field range from 1900 - 2050. I would like to be able to limit this to a much smaller range starting with the current year. What would be the best way to accomplish this?

If you don't want to change every date field—which might have side effects else where on the site—you can easily do it on specific form elements.

function example_form(&$form, &$form_state)  {
  $form['birthday'] = array(
    '#type' => 'date',
    '#title' => t('Birthday'),
    '#required' => TRUE,
    // Add a second process function so we can change the years:
    '#process' => array('form_process_date', 'example_fix_year_range'),
  );

  return $form;
}

/**
 * Follow form_process_date() and re-do the years.
 */
function example_fix_year_range($element) {
  $year = format_date(REQUEST_TIME, 'custom', 'Y');
  $element['year']['#options'] = drupal_map_assoc(range($year - 120, $year));
  return $element;
}


How to set defaults for a custom Views display? I'm maintaining a module that provides a new type of Views display (extending the built-in views_plugin_display_page).

When the user chooses to add my type of display, I'd like to set up some sensible defaults, like creating a default url path, a default display_title, and some defaults for the additional options my module defines in the display's options_form.

How do I set these defaults?

The class views_plugin_display_page defines its options (and defaults) through the
views_plugin_display_page::option_definition() method. This method is just a series overridden methods that extends from the view base class. In a similar manner, your custom plugin can override this method:

// defined in your views_plugin_display_page descendant class
function option_definition() {
  $options = parent::option_definition();

  // @TODO: set your own options plus override any other options
  // defined in parent classes. For example:
  // $options['path'] = array('default' => 'my-default-view-path');

  return $options;
}


What part of the Feeds api knows if there is a difference between old and new data? i want to flag an item if the feed has made any changes in a record.  What hook can I use to do a check of the new data and the old data to see if there is a difference?
I need to mark data that is changed with a flag and also get a log of all changed nodes.  Right now feeds seems to mark everything as updated even if there is no change.

I tried looking in hook_feeds_presave, but both the $item and the $entity are already changed there.  What hook can see a comparison between the old and the new ?

I am modifying the code in hook_feeds_before_update and writing the code like this :

if ($item){
    $node = node_load($item);
    $changed=false;

      if ($entity['ITEM'] != $node->field_item[LANGUAGE_NONE][0]['value']){
         if (trim($entity['ITEM'])=="UNKNOWN"){
             $entity['ITEM'] = $node->field_item[LANGUAGE_NONE][0]['value'];

         }

      }

AND then I flag it with a rule :

{ "rules_flag_when_updated_by_feed" : {
"LABEL" : "Flag when updated by feed",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"REQUIRES" : [ "flag", "feeds" ],
"ON" : { "feeds_import_csv_importer" : [] },
"DO" : [
  { "flag_flagnode" : {
      "flag" : "flag_asset_for_review",
      "node" : [ "node" ],
      "flagging_user" : [ "site:current-user" ],
      "permission_check" : "1"
    }
  }
]

}
}


force block module to load admin panel theme I use diffident themes for admin panel and content pages. when I want to use block module, it loads my content page theme (made by me) and doesn't work correctly.

how can I force block module to display admin panel theme?

or maybe force it to display a specific theme?

If what you are asking is if, when you go to admin/build/block, is there a way to make drupal use your admin theme instead of your custom theme, then the answer to that question is no, because it needs your theme to figure out what regions are available and what blocks are in them.  But it will allow you to pick different active themes so you can put different blocks in different regions in different themes if desired once your custom theme has the needed regions and other logic required to work with the block admin pages.


Restore database from backup I accidentally deleted the Drupal 8 files, but the database is not damaged. Is there anyway I can bring my site back to live?

I have an old backup of only files. I restored the file of that backup in the root folder, and replaced the database credentials in the settings.php file. It didn't work.

Is there any other way to bring back the site to live from the database?

Note: this is shared hosting.

Replace the settings.php with the default.settings.php and re-run the installer.

Use the same database credentials and it should detect that there is an existing installation and say the installer cannot continue. However, you should be able to view the site normally once the installer cannot continue.


How to redirect user to new page after submitting user register form? I've being trying to write custom module that redirects user from user register page after submit. I read several issues on Drupal Offsite and here on Stackexchange, but could not still resolve the issue.

This is my custom module code:

function myregistration_form_user_register_form_alter(&$form,&$form_state){
  unset($_GET['destination']);
  drupal_static_reset('drupal_get_destination');
  $_GET['destination'] = array('query'=>array('q'=>'order_translaton'));
}

The URL of the page I want to redirect to is: http://www.sociofobic.ru/drupal/?q=order_translaton.

After registering user no redirect occurs. Instead I get the NOTICE:

  Notice: Array to string conversion in url_is_external() (line 2312 of
  /home/bnqpdcme/public_html/drupal/includes/common.inc). Notice: Array
  to string conversion in drupal_parse_url() (line 589 of
  /home/bnqpdcme/public_html/drupal/includes/common.inc). and  Page not
  found: The requested page "/drupal/?q=Array" could not be found.

Please tell me what I do wrong, because the syntax for URL redirection I use is the same as explained in drupal_redirect_form().

The syntax that you use is not the same as in the API docs. The qis to much.

Also, you shouldn't manipulate $_GET, that's not at all reliable. The correct way to achieve what you want, is to add a custom form submit handler and when that is called to set $form_state['redirect'].

Have a look at the accepted answer to this question: https://stackoverflow.com/questions/14542975/drupal-7-redirect-to-a-specific-page-a-tab-after-form-submit


Ajax not working in text field I made custom module that implements hook_form_alter that marks the field_text_field_1 textfield as Ajax-enabled. When a key is pressed inside the field_text_field_1, it should change the value in a second textfield: field_text_field_2.

$form['#prefix'] = '
';
$form['#suffix'] = '
';

// $form['field_village']['#attributes']['id'] = 'edit-field-cities-wrapper';

$form['field_text_field_1']['widget']['#ajax'] =array(
    "callback" => "ajax_change1",
    'wrapper' => 'my_form_submit_wrapper',
    "event" => "change",
    "effect" => "fade",
);

The callback function:

function ajax_change1(array &$form, FormStateInterface $form_state){
      $form['field_text_field_2']['widget'][0]['value']['#value']='hello';
      return $form;
}

But it's not changing the value of `field_text_field_2 to "hello".

You need to declare on what object (or class if static) to call the callback, like

'callback' => [get_called_class(), 'settingsAjax']

or

'#ajax' => [
            'callback' => [get_class($this), 'addMoreAjax'],
            'wrapper' => $wrapper_id,
            'effect' => 'fade',
          ],

or at least

'callback' => '::settingsAjax'

depending on your code.


Show contact form in a pop-up window with Bootstrap classes Can you please tell us how to create a modal window with a contact form, with the bootstrap classes?

I open the form with

Open form

And why is the modal window not working for anonyms? Thank you!

UPD

Happened!

Connected via theme, at the root of the theme there is a file my-theme.libraries.yml in it, we develop a library

drupal.dialog.ajax:
  version: VERSION
  js:
    /core/misc/dialog/dialog.ajax.js: {}
  dependencies:
    - core/jquery
    - core/drupal
    - core/drupalSettings
    - core/drupal.ajax
    - core/drupal.dialog

Followed by the root theme in the file my-theme.theme Insert function

function my-theme_preprocess_page(&$variables) {
    $variables['#attached']['library'][] = 'my-theme/drupal.dialog.ajax';
}

Bootstrap and Ajax are two different methods for modal dialogs.

If you want to open a popup with Bootstrap this would be client side. This means you deliver the form embedded in the page as a block and hide it by wrapping it in a Bootstrap modal container:

https://v4-alpha.getbootstrap.com/components/modal/

If you want to load a modal with Drupal Ajax, then use the link you've provided in the question, but target the url of the form, not that of the frontpage:

Open form

For this to work you have to attach a js library:

$build['#attached']['library'][] = 'core/drupal.dialog.ajax';

  And why is the modal window not working for anonyms?

It works for logged in users without attaching the library, because core code is doing this already for the admin dialogs.


What is the path for form elements which are ajax-enabled I am working on the quiz module.
I have to modify the form node/add/multichoice by hiding some of the form elements in it.
With the help of krumo function of devel module, I am able to find the correct form elements and set ['#access'] to FALSE in order to hide them.
All this is done in a custom module using the hook_form_alter().

But the problem is that I have to hide advanced fieldset under alternatives.
The path for form element for advanced fieldset is thus like below :
$form['alternatives'][0]['advanced']
$form['alternatives'][1]['advanced']
But there is an option of add more alternatives.
What is the path for form elements which are ajax enabled.

foreach (element_children($form['alternatives']) as $delta) {
  $form['alternatives'][$delta]['advanced']['#access'] = FALSE;
}

Something like this.


Is there a template for the comment links field? I want to use ajax-links-api so that when someone replies to a comment,
the url comment/reply/60/51 is loaded with ajax on the current page.
I need to add rel="a class" on the reply link's anchor, to select witch div to load.

Display suite adds a manage display for comments
Is there a template file I can use to change the html for the comments field "links"?

Update
By Installing Devel and adding the block I see the comment wrapper Devel
The template in modules/comment/comment.tpl does not look to have the html for links in it.Comment Template

Why don't you use the default selectors to get the url? some thing like this:

(function($) {
    $(document).ready(function() {
        $("YOUR-COMMENTS-WRAPPER").find('a').click(function(){
             var url = $(this).attr('href');
        });
    )
    });
})(jQuery);

then use the url to load the DIV


Contextual filter with Node Reference and Pathauto I work for an organization that makes research grants. We periodically write "research briefs" for our grants to summarize what they found. My test Drupal site has a view of research briefs, and what I'd like is to display a block of grant information as a user is looking at a specific research brief.

I've got two custom content types: grants and research-briefs. The research-brief content type has a node reference field to grant ID. I use pathauto, so an example research-brief path is: site.org/research-brief/551023442 where 551023442 is the grant ID.

The way it seems I should set up the block view contextual filter is:
Content: Parent ID (field_parent_id)
When the filter is not available:
   Provide the default value.
   Type: Raw value from URL
   Path component: 2
   Use path alias: checked

This doesn't work and I've tried any number of fields and any number of configuration options and would sure appreciate any helpful pointers. If I display all results I can see all grants in the block.

I'd try this with a contextual filter for the research brief content:nid and then use the default value: node id from the url. This works regardless of pathauto and always provides the correct node is for the research brief.

Then add a Views relationship (join) from the Research brief to the Grant. Select the node reference field for this relationship.

Finally select the fields you want to display, using the Grant relationship.


Display a field of one content type in another content type I am using drupal 7.I have created two custom content types Bank details and Loan offers.
Now in loan offers i want the logo of the bank to be displayed.The logo image is part of bank details content type.can it be done using node reference?I need help to resolve this issue.Thanks.

You have a choice of modules for this:

References
Entity Reference
Relation

Any one of those modules will allow you to create a field on your Loan Offers content type that references a Bank node. Then you can use Views/custom code/etc. to display the bank's image on the loan offer's node pages.


Edit the token values submitted by webforms I am using webform for user registration and confirmation page as profile page.
I have included the token as follows
" [submission:values:name]
[submission:values:email]
[submission:values:country]
[submission:values:date]
 "
Now the submitted values are displayed in profile page but my requirement is the user should be able to edit and save only few fields but view all fields.
How i would include edit option for displayed data using tokens.
Please help me on this issue. Thanks

Have a look at the Field Permissions module. From its project page:

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

Since users are entities also, it should work for any of your fields.


How to add a base field for an entity reference to a specific vocabulary I have an Entity: EntityX.  It installs correctly and works the way that I want it to; with, of course, one exception.

I want to attach an entity reference to a specific vocabulary.  I have tried:

My vocabulary's machine name is: custom_vocabulary

In EntityX's definition I have the following defined in the baseFieldDefinitions function:

$fields['my_custom_vocabulary'] = BaseFieldDefinition::create('entity_reference')
  ->setLabel(t('Vocabulary'))
  ->setDescription(t('What was this tagged with.'))
  ->setSetting('target_type', 'custom_vocabulary')
  ->setSetting('handler', 'default')
  ->setDisplayOptions('view', array(
    'label' => 'above',
    'type' => 'author',
    'weight' => -3,
  ))
  ->setDisplayOptions('form', array(
    'type' => 'entity_reference_autocomplete',
    'settings' => array(
      'match_operator' => 'CONTAINS',
      'size' => 60,
      'placeholder' => '',
    ),
    'weight' => -3,
  ))
  ->setDisplayConfigurable('form', TRUE)
  ->setDisplayConfigurable('view', TRUE);

But when I go to install it, I get the following error:

Drupal\Component\Plugin\Exception\PluginNotFoundException: The "custom_vocabulary" entity type does not exist. in /brew/www/html/core/lib/Drupal/Core/Entity/EntityTypeManager.php:133

While looking at the article defined in the installation profile for Drupal, I see that they use it as a field and not a true entity reference.  Is there no way for me to do it this way?  I can't have this all nicely bundled into one single entity.

What I don't know how to do is add a term from a vocabulary to an entity type.

Vocabularies are bundles of the entity type taxonomy term. If you want to reference a vocabulary then first set taxonomy_term as target type and second restrict the field to a specific vocabulary as target bundle:

$definition = BaseFieldDefinition::create('entity_reference')
  ->setSetting('target_type', 'taxonomy_term')
  ->setSetting('handler_settings', ['target_bundles' => ['custom_vocabulary' => 'custom_vocabulary']]);

See change record https://www.drupal.org/node/2576151


Is "settings" needed in hook_field_widget_info()? hook_field_formatter_info() and hook_field_widget_info return an array containing a "settings" index. I want to know when is it used. What happens if it is empty, or just omitted?

My formatter and widget for my custom field does have settings. It's just that during widget/formatter definition the settings are not known yet.

If the hooks your module implements don't set that array index, the function invoking them will set them to an empty array. See _field_info_collate_types().

  foreach (module_implements('field_widget_info') as $module) {
    $widget_types = (array) module_invoke($module, 'field_widget_info');
    foreach ($widget_types as $name => $widget_info) {
      // Provide defaults.
      $widget_info += array(
        'settings' => array(),
      );
      $info['widget types'][$name] = $widget_info;
      $info['widget types'][$name]['module'] = $module;
    }
  }

  foreach (module_implements('field_formatter_info') as $module) {
    $formatter_types = (array) module_invoke($module, 'field_formatter_info');
    foreach ($formatter_types as $name => $formatter_info) {
      // Provide defaults.
      $formatter_info += array(
        'settings' => array(),
      );
      $info['formatter types'][$name] = $formatter_info;
      $info['formatter types'][$name]['module'] = $module;
    }
  }

It is then up to the module implementing those hooks, and any related one, to correctly handle the values for that array index, even in the case another module changes it to a value the module is not expecting.


Unable to return session value in views Field I am storing a session value via Rules when the user is logged in

session_start()
$_SESSION['userkey'] = "12345";

Also testing it below there

echo $_SESSION['userkey'];

Although when I am trying to retrieve this value in my view in a field as Global: PHP

with Value Code:

return $_SESSION['userkey'];

Output code:

<?php
echo $value;
?>

It does not return anything. Unsure whether the session is not being set properly or I am retrieving the value incorrectly?

Thanks.

You need to remove session_start() from Rules. Drupal calls session_start() when firing drupal_session_start().

Check out session_start manual on php.net

  As of PHP 4.3.3, calling session_start() after the session was
  previously started will result in an error of level E_NOTICE. Also,
  the second session start will simply be ignored.

Screenshot for PHP field settings in Views:


How to use confirm_form OK this one is driving me nuts. I've read the other question posted on DrupalAnswers and several threads on the Internet, but I still can't work this out.

In my menu hook I have this:

$items['import'] = array(
    'title' => '',
    'type' => MENU_CALLBACK,
    'page callback' => 'drupal_get_form',
    'page arguments' => array('_my_module_form'),
    'access arguments' => array('access content'),
);

Then I have these functions:

function _my_module_form($form_state) {
 if(!isset($form_state['storage']['confirm'])) {

  $form ['some_textarea'] = array(
   '#type' => 'textarea',
   '#rows' => 25,
   '#cols' => 10,
  );

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

  return $form;
 } else {
  drupal_set_message('hello');
  return confirm_form($form);
 }
}

function _my_module_form_validate($form, &$form_state) {
 if(!isset($form_state['storage']['confirm'])) {
 }
}

function _my_module_form_submit($form, &$form_state) {
 if(!isset($form_state['storage']['confirm'])) {
  $form_state['storage']['confirm'] = TRUE;
  $form_state['rebuild'] = TRUE;
 } else {
  drupal_set_message('hello2');
 }
}

When I submit the form, nothing happens. I would expect to see the drupal message 'hello', but instead I just get the original form again. However, if I submit the form a second time, then I see a drupal message saying 'hello2'.

Why does the comfirm_form bit not get executed? It seems to me like the form state is not being rebuilt so the 'else' part of the conditional never gets executed.

Note: I am pretty sure form_validate is not needed, but I just put an empty definition in there in case.

Looks like my issue was here:

function _my_module_form($form_state) {

Should have been:

function _my_module_form($form, &$form_state) {


How to enable "find content" for a role in Drupal 7? I created a role called "Writer".   When a writer logs into the system, they have the black toolbar across the top of the page.   They have the "add content" link which is great.  How do I enable the "find content" link for a writer?

Go to admin/people/permissions and enable "Access the content overview page "


How do I add a specific class in a row of a table output depending on a field content? I use the Views module to list the content of a custom entity, using the Table format.
I'd like to add the myClass CSS class to each row where a given field is equal to zero.

How can I achieve this?

Edit I found out that I could use 'Rewrite results' (Overriding the output of a field with custom text) with twig.
For example:

{% if nombreproduits == '0' %}
{{ '99/99/9999' }}
{% else %}
{{ datedistribution }}
{% endif %}

How could I use that to add a class to the corresponding row?

Two options:

You alter your view with a View hook and you add to the row class value your own class based on one of the field value
You use this solution, and you can check with twig the actual row content and add a class based on that(use devel module and {{ kint(row) }} to understand how to reach the values you want)


How do I disable the "Continue to payment" button before the shipping method is selected? How do I disable the Continue to payment button before the shipping method is selected?
I use #states to disable the button, but it doesn't seem to work.

I would've assumed form states would do the trick, but without seeing the code you've tried, it's hard to say what the issue might be. That said, we did just get the patch into Commerce Shipping that automatically calculates shipping upon full address entry and recalculates it on address change. I believe that may resolve the issue that led you to look into this in the first place. You can upgrade to Commerce Shipping 2.x-dev or apply this patch: https://www.drupal.org/project/commerce_shipping/issues/2849756#comment-14030351


Is it possible to use many plugin process for a field? I'm working with migrate and I need to use multiple plugins for a single process.

is it possible? How?

Yes, process plugins can be chained - see the documentation under "The full pipeline".


Form field default value not working I have an inherited project to which I need to add small form api changes. The changes are to two form fields shown below:

$form['start'] = [
    '#type' => 'number',
    '#title' => t('Between:'),
    '#required' => TRUE,
    '#default_value' => 1988,
    '#min' => 1900,
    '#max' => date('Y'),
    '#value' => 1988,
];
$form['test'] = [
    '#type' => 'number',
    '#title' => t('TEST:'),
    '#required' => TRUE,
    '#default_value' => 1988,
    '#max' => date('Y'),
    '#min' => 1900,
    '#value' => 1995,
];
$form['end'] = [
    '#type' => 'number',
    '#title' => t('and'),
    '#required' => TRUE,
    '#min' => 1900,
    '#max' => date('Y'),
    '#default_value' => 1999,
    '#value' => 1999,
];

This is a bizarre problem as my attempts to set the #value and #default_value for both the start and end fields are not working.

However, I created the test field and it successfully adds to the form and sets my configured value and default_value.

So, for the start field, I expect to see 1988 as the displayed value but instead that form field displays 1900.
The test field I create meanwhile displays and behaves properly ... go figure.

As it is an inherited project, I wonder if there are other means of configuring a form which I am unaware of ?

UPDATE:
Thanks to Leymannx for contributing and attempting to help. As per your suggestions, I tried the following but without success:

$form['start'] = [
    '#type' => 'number',
    '#title' => t('Between:'),
    '#required' => TRUE,
    '#min' => 1900,
    '#max' => idate('Y'),
    '#default_value' => 1988,
];

Note: The problem is that both the start and end fields refuse all my efforts to configure the value and default_value. So, for the start field, I expect to see 1988 but instead that form field displays 1900.

I removed all '#value' keys and replaced date('Y') with idate('Y') and for me it's working without any problem. Flush cache!

$form['start'] = [
  '#type' => 'number',
  '#title' => t('Between') . ':',
  '#required' => TRUE,
  '#default_value' => 1988,
  '#min' => 1900,
  '#max' => idate('Y'),
];
$form['test'] = [
  '#type' => 'number',
  '#title' => t('TEST') . ':',
  '#required' => TRUE,
  '#default_value' => 1988,
  '#max' => idate('Y'),
  '#min' => 1900,
];
$form['end'] = [
  '#type' => 'number',
  '#title' => t('and'),
  '#required' => TRUE,
  '#min' => 1900,
  '#max' => idate('Y'),
  '#default_value' => 1999,
];


EntityReference and custom field but not Title By default EntityReference (auto-complete) works with Title, is it possible to use another field (f.x. from selected Content Type)?

I also tried to create a view and use it (it worked well when you selected value) however once you save a Node and reload, it display Title again.

How could I change that and display my own field?

I believe you are looking for the Entity Reference autofill module.

Please excuse me if I misunderstood your need.


Changing the Open Atrium 2 login hyperlink How do I change the open atrium 2 login hyperlink for anonymous users so that they can register instead of being directed to the user login page?

Try this:

Goto admin/config/people/accounts
Select Registration and cancellation
Under Who can register accounts?, chose Visitors instead of Administrators only

Then users can create an account from the user/login page.


Drupal commerce re-indexing causes exception I'm trying to re-index all my products on my Drupal commerce website. When I do so, I get the following error message:

  An AJAX HTTP error occurred. HTTP Result Code: 500 Debugging information follows. Path: /en/batch?id=130&op=do StatusText: Service unavailable (with message) ResponseText:

When I go to watchdog it shows me this error:

  EntityMetadataWrapperException: Unable to get the data property status as the parent data structure is not set. in EntityStructureWrapper->getPropertyValue() (line 438 in /sites/all/modules/entity/includes/entity.wrapper.inc).

I tried finding out if there were any specific products or entities with their status not being set. When I run the following query in my database, it shows me that there are no products without status. (They all show up with 1 as their values.)

SELECT * FROM  `commerce_product` LIMIT 0 , 500

When I put the batch on doing 1 product at a time, it does 18 of the 193 products and then stops and returns the error message.

What I'd like to know is:

How do I check which product is the culprit?
How do I find my indexed items, and how can I find out where it goes wrong? (I'm not using Apache Solr.)

I'm also not quite sure about what is meant by 'the parent data structure is not set'.
If anyone could provide any insights, I'd very much appreciate it.

It sounds like a field got messed up somewhere. Try running Commerce Repair and seeing if that fixes the problem.


How to populate a select list in my custom module with the content types of the site? I am making my first custom module, and I want to have a select list in the module settings that has all the content types in the site, so that the admin can select which content types to have associated with the module.

here is the code I have so far:

$form['MODULE_select_content_types'] = array(
  '#type'          => 'select',
  '#title' => t('Select Content Types'),
  '#description' => t('Select the Content Types that users can subscribe to'),
  '#default_value' => variable_get('MODULE_unlisted_content_types', array()),
  '#options'       => $select,
  '#multiple'      => TRUE,
);

How do I populate the $select variable with a list of all the content types in the site?

I found some code in another module that did the same thing. That module had this code before that form option in the form function

$select = array();
$select[0] = '<' . t('none') . '>';
$nodetypes = node_type_get_types();
foreach ($nodetypes as $ntype => $nname) {
  $select[$ntype] = $nname->name;
}


How do I check if the site is in maintenance mode? How do I call MaintenanceMode::applies(RouteMatchInterface $route_match) from hook_theme_suggestions_page()?

From a procedural hook you'll probably need to use something like:

use Drupal\Core\Routing\RouteMatch;

...

$maintenance_mode = \Drupal::service('maintenance_mode');
$route_match = RouteMatch::createFromRequest(\Drupal::request());

if ($maintenance_mode->applies($route_match)) {
  // ...
}


Getting group posts in og's home page view I'm theming views-view--og.tpl.php, hoping to change the default group listing table into something a bit more attractive.

I'm looping through the $rows I have available, and for each of them I'm loading a $group_node object and creating a div with some specific content, such as the group's mission etc.
I'd also want to present the lastest 2-3 group posts for each of the groups i'm fetching in $rows, along with their autoring and date information.

If it makes it any clearer, here's what i'm doing:

<?php
<?php if ($rows): ?>
    <?php if (drupal_get_path_alias(implode('/',arg())) == 'og') { ?>

        <?php foreach($variables['view']->result as $node) { ?>
            <?php $group_node = node_load($node->nid); ?>

        <?php } ?>

    <?php } else { ?>

            <?php print $rows; ?>

    <?php } ?>
<?php elseif ($empty): ?>

  <?php print $empty; ?>

<?php endif; ?>
?>

How can I load all group posts related to a certain group node, and can this be done from the og home page (path /og), as I understand, it's considered outside of group context?

Help will be much appreciated,

Avner

I recommend creating a whole new view, which would list the three most recent posts for the group passed in the argument.

To make it work together with your existing og view, you'll want to attach the new view to your group content type using one of Viewfield, Views Field View and View reference modules.

For example, using Viewfield; to the group node type add a hidden View field called Recents. Set it to "Always use default value". Set the default value to the recent posts view. The argument is "%nid". Exclude its display from node teaser, full view etc.

In the group view, then, along with group name and mission, also add Attrview as a field. Good luck!


With several user profile pages built in Views as tabs, how do I build a menu linking to those pages? I can't just use the menu UI to create menu links because the links need to be dynamic. The best solution I have found so far is in OpenAtrium. Are there any others?

   $block['content'] .= "<h3>". t('My account') ."</h3>". theme('links',
atrium_account_links());

and

/**
 * Generates an array of account links suitable for use in theme_links().
 */
function atrium_account_links() {
  global $user;
  $links = array();

  // @TODO: If menu.inc had a real API function for this we would use it, but
  // as of now we'd have a copy hand paste hack job of menu_local_tasks()...
  $paths = array(
    "user/{$user->uid}" => t('Profile'),
    "user/{$user->uid}/dashboard" => '',
    "user/{$user->uid}/edit" => '',
    "user/{$user->uid}/notifications" => '',
    'logout' => '',
  );
  foreach ($paths as $path => $title) {
    $item = menu_get_item($path);
    if ($item && $item['access']) {
      $links[] = array(
        'title' => !empty($title) ? $title : $item['title'],
        'href' => $item['href'],
      );
    }
  }
  drupal_alter('atrium_account_links', $links);
  return $links;
}

I went ahead and implemented the OpenAtrium code in Drupal 7 which I'll use unless somebody comes up with a better answer.

/**
* implements hook_block_info()
*/
function helper_block_info () {
  $blocks['helper_user_links'] = array(
    'info' => t('Menu user links'),
    'cache' => DRUPAL_CACHE_PER_ROLE,
  );

  return $blocks;
}

/**
* implements hook_block_view()
*/
function helper_block_view($delta = ''){
  $block = array();

    case 'helper_user_links':
      $block['subject'] = NULL;
      $block['content'] = array(
        '#markup' => theme('links', array(
          'links' => helper_user_links(),
          'attributes' => array('class' => 'menu'),
        )),
      );
    break;
  }

  return $block;
}

/**
 * Generates an array of account links suitable for use in theme_links().
 */
function helper_user_links() {
  global $user;
  $links = array();

  // @TODO: If menu.inc had a real API function for this we would use it, but
  // as of now we'd have a copy hand paste hack job of menu_local_tasks()...
  $paths = array(
    "user/{$user->uid}/businesses/reviews" => '',
    "user/{$user->uid}/content" => '',
    "user/{$user->uid}/workbench" => '',
    'logout' => '',
  );
  foreach ($paths as $path => $title) {
    $item = menu_get_item($path);
    if ($item && $item['access']) {
      $links[] = array(
        'title' => !empty($title) ? $title : $item['title'],
        'href' => $item['href'],
        'class' => $_GET['q'] == $item['path'] ? 'leaf active-trail active' : 'leaf',
      );
    }
  }
  drupal_alter('helper_user_links', $links);
  return $links;
}


How to display a computed field in an automatic node title? I am trying to display something like "Field A - Field B" as a title for each content created on a Drupal 7 website.

The Field A is entered manually through Drupal standard form.

The Field B is computed with the module Computed Field and it depends on Field A value (this part works fine).

Now I would like to create automatically the node title on saving with Automatic Entity Label, using Token. (This is the new Automatic Nodetitles).

Unfortunately, using [node:field_a] - [node:field_b], the computed field B value is invisible. More, if you edit the node and save it a second time, the title is OK...

It seems like the field value calculation is made simultaneously with the title generation and thus this value can not be used to generate the title. Of course, I can not tell my client to save twice, we can not say it is user-friendly...

Is there another way to build this automatic title based on a computed field?

Related questions :

How to Compute fields on the fly

What's wrong in my code for setting up entity title in a Computed Field?

On the same subject on Drupal.org :

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

What about setting up a rules event to set a data value for the node title using the event "after content is saved" ?

This should work...

Set up a rule with the event "after content is saved".
Set up the action "set a data value"
Choose the title field, and use the tokens to set your value.


How to conditionally display field contents in Views I want to edit my View so that it only displays a certain contents if some field in my content type had been set. I installed the Views PHP plugin, but it's currently not producing the desired results.

This is the current example I have - using the custom php field, where field_link_to_page is a checkbox field in my content type that decides what contents are to be displayed:

<?php
// Field is configured to return "1" if it's checked, or "0" if it's unchecked.
if ($row->field_link_to_page =="1") {
    echo $row->body."
[NID]
<?php
echo "\">more...";
}
else
{
    echo $row->body;
}
?>

Removing this code, and doing a var_dump() on the field, returns something like this:

object(stdClass)#250 (7) { ["field_year"]=> string(3) "113" ["field_month"]=>
string(3) "113" ["field_day"]=> string(3) "113" ["title"]=> string(73)
"Forecast opening day for Talking Rock Golf Course (conditions permitting)"
["body"]=> string(3) "113" ["field_link_to_page"]=> string(3) "113" ["php"]=>
NULL } 113

which is confusing because the contents get rendered nicely by Views but here it only looks like it's handles to something (113). How can I render the contents correctly in php?

I have figured out a way to do what I want without the Views PHP module:
I added the link to my fields as well and rewrite the link token in my checkbox field (field_link_to_page) only if it isn't empty. That seems to have worked out well.


Fill table with data on submit I created a submit button in my config form.

$form['actions']['find_users']  = array(
        '#type' => 'submit',
        '#value' => t('Find users'),
        '#submit' => array('::find_users'),
      );

When I press on submit button, I need to create a table and fill it with the all users of my forum.

First, I created this function:

function find_users(array &$form, FormStateInterface $form_state) {
        $header = [
                    'username' => t('username'),
                    'registered' => t('registered'),
                      'email' => t('e-mail'),
                    'ip' => t('ip'),
                      'last_visit' => t('last visit'),
                  ];

                  $form['table'] = array(
                    '#type' => 'tableselect',
                    '#header' => $header,
                    '#empty' => t('No users found'),
                  );
    }

But when I press on my submit button, table doesn't create. What should I do?

For example, I need to fill table with just the first record from users_field_data table (limit 1).

You're missing #options property in your tableselect element, e.g.

$form['table'] = array(
  '#type' => 'tableselect',
  '#header' => $header,
  '#options' => $options,
  '#multiple' => FALSE,
);

See: Adding checkboxes to a table.


How do I bulk delete field collection items that are part of a content type? I have a Drupal 7 site with a content type that is for adding courses and courses have a field collection that has multiple fields for Date, Venue, Location(Province)

Each course can have 1 or many dates, venues and locations and these get updated, usually by the company offering the course(User managed content). I can update the course content and field collections for them using feeds module but the problem I have is that the old dates are not being overwritten. So we end up with old dates which are no longer relevant plus the new dates.

The question, is there a way to delete the old dates in bulk? I can't seem to get VBO and views to do this. Am I missing a module that would allow me to select all the field collection fields for a particular node and delete all without having to delete them 1 at a time?

I created a view that lets us filter by username(so that we can delete for a particular company/user) and course dates(so that we can filter courses with selected dates). It will delete all fields within the field collections for the selected courses. Courses display in rows for each date instance, e.g. if a course has many dates then it displays in a new row with each date field collection item.

I created a content view with a relationships to the field collections-field collection items, author and content field of the field collections attached to my content type for which I selected Delta=All).

I then added fields with the course title, date, venue, location and field collection item ID and displayed in a table with the VBO set to delete the selected field collection items for each instance.

I have filter criteria for the content type, username(author)-exposed, and field collection item for the date-exposed so that I can filter by date to delete old items.

I hope I was able to explain the solution that worked for me so that it can at least offer a clue to someone else with a similar problem.


Delete multiple entites without loading them - running out of memory I'm deleting multiple nodes like this:

$nids = [21,12,45,67]; // Just an example, this data comes from elsewhere
$nodes = \Drupal::entityTypeManager()->getStorage('node')->loadMultiple($nids);
\Drupal::entityTypeManager()->getStorage('node')->delete($nodes);

Drupal is running out of memory when deleting just 6 nodes.

I'm having this problem in general, not just when deleting, but any time I work with multiple nodes. The PHP memory_limit is 256MB and the server admin is reluctant to increase this. Even if it is increased, it's just postponing the problem - it might fail on 12 or 16 instead of 6.

Is there another way, e.g. to delete based on nid without loading the full node object and all of its fields? The deprecated entity_delete_multiple appears to load the entities before deleting anyway. I suspect it has to because various hooks have to be called and it has to delete revisions and field data.

Or is there some special way I can code it to delete one node at a time and free each object afterwards to keep memory usage low?

Loading/deleting one at a time may use less memory:

use Drupal\node\Entity\Node;

$nids = [21,12,45,67];
foreach($nids as $nid)
{
  $node = Node::load($nid);
  $node->delete();
}

Each loop will overwrite the previous instance of $node, releasing the memory.


Get node view count for each day I have site with thousands of user and logins each day. I need to track each page views of each user to generate a report.

If a user 'A' visits a page 'P' today, a new entry daycount is added
to the DB. If the same user 'A' visits the same page 'P' on same day,
the daycount will increment by one. If a user 'A' visits page 'P'
tomorrow, a new entry daycount is added to the DB.

I am using drupal 7. The insert and update works properly if there is no date comparison. Once i added  if($TimeNow > $UpdateTime), the page load never ends. Can anyone help me to fix this.

if(db_query('SELECT daycount FROM {report_page_view} WHERE id = 9999999990 AND uid = :uid )', array(':uid' => $GLOBALS['user']->uid))->rowCount() == 0) {

    $ChQry = "(SELECT timestamp FROM {report_page_view} WHERE id = 9999999990 AND uid = :uid )', array(':uid' => $GLOBALS['user']->uid)"; // Get the previous timestamp
    $ChResult = db_query($ChQry);

    while ( $ChGetResult = $ChResult->fetchAssoc() ) {
       $TimeStm = $ChGetResult['timestamp'];
    }
        $UpdateTime = $TimeStm + 86400; //Get the next day
        $TimeNow = time();
        if($TimeNow > $UpdateTime) { // Compare current time and tomorrows date
        // insert if condition works
        $insert_page = db_insert('report_page_view')->fields(array('title', 'memberorg', 'id', 'type', 'timestamp', 'daycount', 'uid', 'fname', 'lname'));
            $insert_page->values(array(
            'title' => $Title,
            'memberorg' => $MemberOrg,
            'id' => 9999999990,
            'type' => 'views',
            'timestamp' => REQUEST_TIME,
            'daycount' => 1,
            'uid' => $UserId,
            'fname' => $FName,
            'lname' => $LName,

          ));
        $insert_page->execute();
    }
    } // else update
    db_update('report_page_view')
    ->fields(array(
            'title' => $Title,
            'memberorg' => $MemberOrg,
            'id' => 9999999990,
            'type' => 'views',
            'timestamp' => REQUEST_TIME,
            'daycount' => 1,
            'uid' => $UserId,
            'fname' => $FName,
            'lname' => $LName,
    ))
    ->expression('daycount', 'daycount + 1')`

Consider using the Node view count module for this. Here is a quote about it (from its project page, bold markup added here):

... allows to count node views. Unlike statistics module, this module records each view of node with user uid and timestamp. So now you can know how many times a user viewed node by day, week, month and etc.
This module is integrated with Views module. You can use it to create different statistics pages, output new not viewed nodes for user and many more.

By using this module, and to the extend it should be needed, you can then further refine / extend what you get (out-of-the-box) from this module via a custom module(s) and/or view(s).


Load existing form and use hook_form_alter to create a custom submit handler? I have an existing webform in admin and I want to now render that form on other pages. I have a template page node--download_resource_protected.tpl that prints a hidden CSS pop-up box onto pages that show a teaser for content type Download Resource - Protected. When you click on the teaser, this pop-up shows. It currently includes a static form, asking for data-input before access to the download is allowed. See the screenshot here:

Now in place of this static form I want to render an existing webform with the API. The two teasers on the are defined as entity reference fields: Call to Action 1 and Call to Action 2.

After successful completion of the webform I want to post the data to the node URL of the teaser. For example if the page is displaying a teaser of node 34: the user clicks the teaser and the pop-up appears (this already happends), within the popup a webform is rendered (in place of the current static form) and on completion of the form it posts the data and loads URL node/34 (this needs to be dynamic i.e automatically directing to the correct node URL depending on node_id of the teaser).

I want to use hook_form_alter() to set a custom submit handler like this.

 if ($form_id == 'webform_client_form_112') {
    $form['#submit'][] = 'my_custom_submit_handler';
  }

But I need to pass the teaser node id in which the block webform was called, to this custom function (this will then allow me to to redirect to the node URL), any ideas?

Thanks for your time!

You can use the 'Available as block ' for webform settings. This option can find at 'form settings'->Advanced settings of your webform. Once it enabled you can render this webform block, instead of your static form as follows.

You can define custom submit handler for the webform, ex: $
form['#submit'][] = 'my_custom_submit_handler';  in form alter,
in that function you can write the necessary code to save and redirect etc;

hope this may help you.


How do I create a "platform" and "site" from CLI, using the drush extension provision I'm trying to figure out how to use Provision to create new sites from the CLI.

I tried looking at what commands Aegir normally passes to Provision when setting up a new platform and then a new site on that platform, but I haven't succesfully made it work from CLI.

There is a good article on this question in Aegir official documentation here:
http://community.aegirproject.org/content/manage-your-aegir-system-command-line


Add 'attributes' to an html element In my drupal 7 module which is separate from the node portion of drupal (discrete tables) I'm trying to use the array of 'attributes' to one  element of table using theme().

Here's a simple example:

$query = "SELECT projectID, title, housestaff_needed FROM Projects";
$result = db_query($query)->fetchAll();
$header = array('name' => t('Name'), 'title' => t('Title'), 'housestaff_needed' => t('Housestaff Needed'));

    foreach ($result as $item) {
      $rows[] = array(
          $item->title,
          $item->housestaff_needed,
          array('attributes' => array('id' => array('staff-' . $item->projectID))),
          );
    }
    $theme = theme('table', array('header' => $header, 'rows' => $rows));
    return $theme;

As you know, this only adds another  element after the housestaff_needed data. I've used this syntax before to enclose an entire table with an attribute, but I've read and read to see how this can be done on just an element but all I've read is how you can do it in the form api using '#attribute' which doesn't seem to be the same thing and a different setup outside the forms.

I'm trying to get this so I can identify this element for a jQuery scripted and can't get to first base. Please point out what I'm not doing correctly, thx, sam

I believe you need to add the data as an array to an associative array with the 'data' key, and the attributes with the attribute name as the key. For instance, your code would look like:

$rows = array();
foreach ($result as $item) {
  $rows[] = array(
    'data' => array($item->title, $item->housestaff_needed),
    'id' => 'staff-' . $item->projectID,
  );
}
$theme = theme('table', array('header' => $header, 'rows' => $rows));
return $theme;

I think this will add an id to each <tr>. If you want to add attributes to each individual <td>, you would use a similar structure for $item->title and $item->housestaff_needed. That is, it would become:

$rows = array();
foreach ($result as $item) {
  $rows[] = array(
    'data' => array(
      array(
        'data' => $item->title,
        'id' => 'SOME_ID',
      ),
      array(
        'data' => $item->housestaff_needed,
        'id' => 'SOME_OTHER_ID'
      ),
    ),
    'id' => 'staff-' . $item->projectID,
  );
}
$theme = theme('table', array('header' => $header, 'rows' => $rows));
return $theme;

At least, that's how it works in d6, I beleive, so here's hoping it still works in d7.


Unable to add JavaScript on a page I am using this, but I don't understand why it's not working.

if ($_SERVER['REQUEST_URI'] == '/node/1') {
  drupal_add_js(drupal_get_path('theme', 'sanskrit').'/sites/all/themes/sanskrit/scripts/jquery-1.4.3.min.js', 'inline');
  drupal_add_js('/sites/all/themes/sanskrit/scripts/scripts/jquery.nivo.slider.pack.js');
}

What I want to do is adding specific JavaScript files when the user is viewing the front page.

This should do it:

function MYTHEME_preprocess_page(&$vars) {
  if (drupal_is_front_page()) {
    drupal_add_js(drupal_get_path('theme', 'MYTHEME') . '/MYSCRIPTS/myscript.js');
    $vars['scripts'] = drupal_get_js();
  }
}

FYI:  You'd use drupal_get_js in case any modules are also using hook_preprocess_page and setting new scripts themselves.

Also, I wouldn't just add a newer version of jQuery in willy nilly.  Try either jQuery Update or jQuery Multi


Allow module to overwrite multiple templates from module I have a couple paragraphs set up in my content type.  I would like to overwrite the templates from my module (long story - we want to reuse this same set up across multiple sites if I get this to work).

I used the following hook in my module:

/**
 * Implements hook_theme_registry_alter().
 */
function my_module_theme_registry_alter(&$theme_registry) {
  $theme_registry['paragraph']['path'] = drupal_get_path('module', 'my_module') . '/templates/paragraph';
  $theme_registry['paragraph']['template'] = 'paragraph';
}

In my module's templates/paragraph folder I have the following files:

paragraph.html.twig
paragraph--accordion.html.twig
paragraph--carousel.html.twig

Here is theme debug:

<!-- THEME HOOK: 'paragraph' -->
<!-- FILE NAME SUGGESTIONS:
   * paragraph--accordion--default.html.twig
   * paragraph--accordion.html.twig
   x paragraph--default.html.twig
   * paragraph.html.twig
-->
<!-- BEGIN OUTPUT from 'modules/contrib/bootstrap_paragraphs/templates/paragraph/paragraph.html.twig' -->

It seems to work but the problem is that paragraph--accordion and paragraph--carousel always use paragraph.html.twig.  How can I have paragraph--accordion and paragraph--carousel use the templates that are in my module. If I place them in my theme's template folder they do render.

I was able to figure it out. I only used hook_theme_registry_alter().  You have the copy $theme_registry['paragraphs'] to all items you want to use paragraphs.

/**
 * Implements hook_theme_registry_alter().
 */
function my_module_theme_registry_alter(&$theme_registry) {
  $module_path = drupal_get_path('module', 'my_module');

  // Use the templates in my module's template folder.
  $theme_registry['paragraph__accordion'] = $theme_registry['paragraph'];
  $theme_registry['paragraph__accordion']['path'] = $module_path . '/templates/paragraph';
  $theme_registry['paragraph__accordion']['template'] = 'paragraph--accordion';
  $theme_registry['paragraph__carousel'] = $theme_registry['paragraph__accordion'];
  $theme_registry['paragraph__carousel']['template'] = 'paragraph--carousel';
}


Programmatically attach image to a content type from local system folder I am in middle of coding creating nodes programatically. Here i have one problem. I need to programmatically attach image to the content type from local system folder. I mean my image path example 'c://xxxxx/xxxx/images/img.jpg'.

Thanks in advance for your advice.

Hi i used this code and work fine in the localhost. But it's failed when i work on the server.

$filepath = drupal_realpath('misc/druplicon.png');
// Create managed File object and associate with Image field.
$file = (object) array(
 'uid' => 1,
 'uri' => $filepath,
 'filemime' => file_get_mimetype($filepath),
 'status' => 1,
);

// We save the file to the root of the files directory.
$file = file_copy($file, 'public://');

$node->field_image[LANGUAGE_NONE][0] = (array)$file;

Reference link : attaching-files-to-nodes-programmatically-in-drupal-7

  I didn't get the solution yet. Can any one have the experience?

You can just use file_copy or file_move.

Here is an example: https://stackoverflow.com/questions/5129559/attaching-files-to-nodes-programmatically-in-drupal-7