How to make this entity fieldable? I want to make my entity fieldable and manageable from admin area with manage display and manage field admin ui. I have read few tutorials, but I still not understand how to do it? This question is related to my other question. Here is my entity code.

function statuses_entity_info() {
  $backupControl = module_exists('entity') ? 'EntityAPIController' : 'DrupalDefaultEntityController';
  return array(
    'status' => array(
      'label' => t('Status'),
      'plural label' => t('Statuses'),
      'description' => t('A status update.'),
      'entity class' => 'StatusEntity',
      'controller class' => module_exists('statuses') ? 'StatusesEntityController' : $backupControl,
      'base table' => 'statuses',
      'load hook' => 'statuses_load',
      'uri callback' => 'statuses_uri',
      'module' => 'statuses',
      'entity keys' => array(
        'id' => 'sid',
        'label' => 'message',
      ),
       'bundles' => array(
        'status' => array(
          'label' => t('Status'),
        ),
      ),
      'view modes' => array(
        'full' => array(
          'label' => t('Status message'),
          'custom settings' => FALSE,
        ),
      ),
      'entity cache' => FALSE,
    ),
  );
}

function statuses_entity_property_info()  {
  $info = array();

  $info['status']['properties']['sid'] = array(
    'label' => t('Status ID'),
    'description' => t('The ID of the status'),
    'type' => 'integer',
    'schema field' => 'sid',
  );

  $info['status']['properties']['sender'] = array(
    'label' => t('Status sender'),
    'description' => t('Sender uid of the status message'),
    'type' => 'integer',
    'schema field' => 'sender',
  );
  $info['status']['properties']['recipient'] = array(
    'label' => t('Status recipient'),
    'description' => t('Recipient uid of the status message'),
    'type' => 'integer',
    'schema field' => 'recipient',
  );
  $info['status']['properties']['type'] = array(
    'label' => t('Type'),
    'description' => t('Type of status message'),
    'type' => 'text',
    'schema field' => 'type',
  );
  $info['status']['properties']['created'] = array(
    'label' => t('Created'),
    'description' => t('UNIX Timestamp of creation date'),
    'type' => 'integer',
    'schema field' => 'created',
  );
  $info['status']['properties']['message'] = array(
    'label' => t('Message'),
    'description' => t('Status message'),
    'type' => 'text',
    'schema field' => 'message',
  );
  return $info;
}

function statuses_uri($status)  {
  return array(
    'path' => 'statuses/' . $status->sid,
  );
}

class StatusesEntityController extends EntityAPIController  {
//TODO
}

if (class_exists('Entity')) {
  class StatusEntity extends Entity {
    public function __construct(array $values = array(), $entityType = NULL)  {
      parent::__construct($values, 'status');
    }

    public function buildContent($view_mode = 'full', $langcode = NULL) {
      $content['sender'] = array(
      '#markup' => 'Sender Markup TEST',
      );
      $content['recipient'] = array(
        '#markup' => 'Recipient Markup TEST',
      );
      $content['created'] = array(
        '#markup' => 'Created Markup TEST',
      );
      $content['message'] = array(
        '#markup' => 'Message Markup TEST',
      );
      $content['sid'] = array(
        '#markup' => 'sid Markup TEST',
      );
      $content['type'] = array(
        '#markup' => 'type Markup TEST',
      );
      return entity_get_controller($this->entityType)->buildContent($this, $view_mode, $langcode, $content);

    }
  }
}

Just add the fieldable key and set it to true:

return array(
  'status' => array(
    'label' => t('Status'),
    'plural label' => t('Statuses'),
    'fieldable' => TRUE,
    ...


How to sort on different columns in the same view? I'm trying to build a Glossary View in Drupal 8. Let's say I have 3 content types: Person, Article, Event.  I want sort by title ASC for Article and Event, but sort by Last Name for Person.  So that listing would show something like.

Deep Study on Dolphins (article)
John Doe (person)
Jam in the Backyard (event)

And Not

Deep Study
Jam in the Backyard
John Doe

I think I can do this with hook_views_query_alter, but the only examples I've seen are for Drupal 7.

I've got something like this

function mymodule_views_query_alter(ViewExecutable $view, QueryPluginBase $query) {
  if ($view->id() == 'glossary_everything') {
     $query->orderby[0]['field'] = "CASE WHEN node_field_data.last_name IS NULL THEN node_field_data.title ELSE node_field_data.last_name END";
  }
}

But I'm getting a "column not found" sql error.  I think it's treating the whole CASE statement as one big field.  Is that because of the ['field'] designation in my array?

In Drupal 8, if you want to alter an ORDER BY, in particular to use a formula, you have to add an expression and then order by it:

$query->addExpression('SUBSTRING(thread, 1, (LENGTH(thread) - 1))', 'order_field');
$query->orderBy('order_field', 'ASC');

There can be some confusion in Views, because their version of addExpression is Sql::addField. And in fact, Sql::addOrderBy let's you add a field and order by it in one call.

So, your code would look like:

$sql = <<<SQL
CASE
     WHEN node_field_data.last_name IS NULL THEN node_field_data.title
          ELSE node_field_data.last_name
END
SQL;

$query->addField(NULL, $sql, 'last_name_else_title');
$query->orderby[] = array(
  'field' => 'last_name_else_title',
  'direction' => 'ASC',
);

Or just...

$query->addOrderBy(NULL, $sql, 'ASC', 'last_name_else_title');

Thanks agileadam for pointing out the failure point (see also).


Batch API times out when running a single operation I'm trying to print ~100 nodes worth of content (Performance Plans) out to the private file system using the batch API. My process works perfectly up until about 10 of them and then times out. The timeout page happens before it even gets to the batch page with the progress bar. It appears to me like it might be running all 100 as a single batch vs breaking them up. I'm not sure exactly what I'm missing... Any help would be greatly appreciate.

BulkPrintForm.php

<?php
 namespace Drupal\bulk_print_to_files\Form;
 use Drupal\Core\Form\FormBase;
 use Drupal\Core\Form\FormStateInterface;
 use Drupal\node\Entity\Node;
 use Drupal\Core\Url;
/**
 * Class BulkAddForm.
 *
 * @package Drupal\create_perf_plan_for_new_year\Form
 */
class BulkPrintForm extends FormBase {
  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'bulk_print_form';
  }
  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $form['bulk_add'] = array(
      '#type' => 'submit',
      '#value' => $this->t('Print Performance Plans'),
    );
    return $form;
  }
  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $nids = \Drupal::entityQuery('node')
      ->condition('type','perf_plan')
      ->condition('field_performance_plan_year', 18)
      ->range(0, 100)
      ->sort('created' , 'DESC')
      //->condition('nid', 6273)
      ->execute();
    //$year = "1920"; //$year being left here as an example of passing a variable to the bulk process. Not currently in use.

    $operations = [];

    foreach ($nids as $nid) {
      $operations[] = [
        [
          $this->batchFunction($nid),
          [$nid]
        ],
      ];
    }

    $batch = array(
      'title' => t('Bulk Print happening within the Bulk Print Form file...'),
      'operations' => $operations,
      'progress_message' => t('Processed @current out of @total. Estimated time: @estimate.'),
      'init_message'=> t('Performance Plans are being printed to the private directory!'),
      'finished' => '\Drupal\bulk_print_to_files\BulkPrintNode::bulkPrintFinishedCallback',
      'error_message' => t('The migration process has encountered an error. (Make sure the folder you are placing these in exists!)'),
    );
    batch_set($batch);
  }
  function batchFunction($nid) {
    $print_engine = \Drupal::service('plugin.manager.entity_print.print_engine')->createSelectedInstance('pdf');
    $print_builder = \Drupal::service('entity_print.print_builder');
    $path = 'private';
    $filename = "perfplans/{$nid}.pdf";
    $nodes = \Drupal::entityTypeManager()->getStorage('node')->load($nid);
    $uri = $print_builder->savePrintable([$nodes], $print_engine, $path, $filename);
  }
}

BulkPrintNode.php

<?php
namespace Drupal\bulk_print_to_files;
use Drupal\node\Entity\Node;
use Drupal\Core\Url;

function bulkPrintFinishedCallback($success, $operations) {
    if ($success) {
      $message = 'Performance plan printed.';
      $type = 'status';
    }
    else {
      $message = t('Encountered an error during bulk performance plan creation.');
      $type = 'error';
    }
    drupal_set_message($message, $type);
  }
}

Is there a way to limit these to say doing 5 at a time and then moving on to another set? Im under the impression I just have the batching process setup incorrectly.

In BulkPrintForm::submitForm() you invoke batchFunction method by calling it directly via $this->batchFunction($nid) line. This will effectively skip the batch API and run it for all nodes. You should pass the callback instead, check http://cgit.drupalcode.org/examples/tree/batch_example/src/Form/BatchExampleForm.php#n93


Custom field for block's edit form? I would like to add an additional field to block's edit screen and be able to retrieve it's value upon rendering. Is it possible?

The Drupal Examples modules has an example of adding extra configuration to blocks. However, you will responsible for handling the data and how it's saved to the database which means it can get complicated fast. If it is a field with a value that is used on each of the blocks then the example which uses variable_set() and variable_get() will work. You do not want to much data saved to the variable table.

If the data needs to be more dynamic and you are not building a site with 2,000,000 visitors a day, you can make a node type and use Views to render the values in a block.


How to create a separate theme for a custom page? How to create a custom theme for a page? I want to create a template for my example/123 page.

To create a custom template for node/123, copy your theme's default page.tpl.php to a file named page--node--123.tpl.php (D7) in your theme's or subtheme's templates/ directory, and then edit it to do any customization.

To do custom theming, add custom classes where you need them in the custom template, and then add the CSS to style those classes.

Btw.: I usually do this by creating a sub-theme, to avoid any customization from being overwritten when the super-theme is upgraded.

PS: If your page really has the path example/123, the name of the template overide file should be page--example--123.tpl.php

Remember to clear the cache after doing this.    Until you do, your override will not be visible.


Why call javascript behaviour within its own function? Looking at the JavaScript below, what does calling the behaviourName do?

  Drupal.behaviors.behaviourName = {
    attach: function (context) {
      $('.someClass', context).once('some-handler').behaviourName(); // what does this do?
    }
  };

I though that the behaviourName was generally used for name spacing. I can see in the site that im working on that the behaviour name is normally called within itself like in this example. What is this for?

You're reading that wrong - the return from once() isn't Drupal.behaviors (it's a collection of jQuery elements), and Drupal.behaviors.behaviourName isn't a function that will do anything by invoking it, anyway. You would need

Drupal.behaviors.behaviourName.attach();

To get anything meaningful, but that's not synonymous with the code you're referencing.

So that code is not calling a javascript behaviour within its own function. It's calling a jQuery extension function on the elements returned from once(). Most commonly when code needs to do what you're describing in Drupal, you'll see Drupal.attachBehaviors(); instead.

What you have is a convention used by the developer who wrote the script, nothing more; you'll need to ask them for their motivation for doing so, and how/where they're attaching the $.fn functions of the same names as the behaviours.


How to customize permissions for a custom module I created a custom module that hides a field in a content type editing screen from the user and simultaneously auto-selects a value for that field for the user. It works great for the admin role but for some reason my other user's who are able to login and who have permission to edit the content type don't get this functionality applied. They still see the field and can still select a value for it.

Anyone know how to make the permissions for a custom module apply to ALL users?

Here's my module code:

/**
 * @file
 * Auto saving to a term reference field.
 */
 /**
  * Implementation of hook_form_alter().
  */
function seven_form_resource_node_form_alter(&$form, &$form_state, $form_id) {
    hide($form['field_icon']);
}
/**
 * Implementation of hook_node_presave().
 */
function grouphideandselect_node_presave($node){
  //Condition for particular content type
  if($node->type == 'resource'){
    $icon_ary = array();
    //Array to map category with icon given as Category=>Icon
    $field_type_to_icon = array(1 => 1,2 => 1,3 => 1,4 => 2,5 =>
2,6 => 2,7 => 2,8 => 6,9 => 6,97=>6,98 => 6);
    $category = $node->field_type['und'];
    foreach($category as $k=>$c){
      $icon = $field_type_to_icon[$c['value']];
      if(!in_array($icon, $icon_ary)){
        $icon_ary[] = $icon;
        $node->field_icon['und'][$k]['tid'] = $icon;
      }
    }
  }
}

Add the Field Permissions module, this gives you control over every field in the content type. You edit the permissions on a field by field basis in the content type editing area. This gives you control over editing, and viewing the field.

https://www.drupal.org/project/field_permissions


Date with time not viewing on Form If I set a date programatically with this code:

$currentDateString=date("Y-m-d H:i:s", strtotime($current_date));
 $static_media->set('field_posted' , $currentDateString);

the data in field is there , when I do a get-> i can see the date, but it does not show up in the edit view of the entity. (just shows as blank)

If I modify the date in the edit view, when I do a 'get->' the date comes out with the EDT timezone in the time , and then it does show up in the edit form.

I tried inserting it with the EDT Timezone, but I get a message that the data is too long

Drupal\Core\Entity\EntityStorageException: SQLSTATE[22001]: String data, right truncated: 1406 Data too       [error]
long for column 'field_pup_posted_value' at row 1: INSERT INTO {media__field_pup_posted} (entity_id,
revision_id, bundle, delta, langcode, field_posted_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] => 562729
    [:db_insert_placeholder_1] => 1045632
    [:db_insert_placeholder_2] => published_products_static
    [:db_insert_placeholder_3] => 0
    [:db_insert_placeholder_4] => en
    [:db_insert_placeholder_5] => 2017-06-08EDT17:19:31
)

I had to insert it with a T in between the date and time as follows:

$currentDateString=date("Y-m-d", strtotime($current_date))."T".date("H:i:s", strtotime($current_date));


How to Embed Views Exposed Filter for only one field i have a view and many fields are exposed in it. I need to embed (render) a specific exposed filter in my template.

i have came across this article. But it shows all exposed filters of a view.

any idea how this can be done?
thanks

Make a views tpl file with name views-exposed-form--view-name.tpl.php in your theme in this file <?php print_r($widgets); exit; ?> this will give you your widgets then print your widget like this: print $widgets['your widget name']->widget ; in end  print $button;


file_save_upload with multiple form I have a form with the following input field:

<input type="file" name="photo_files[]" />

I would like to save each of this files using file_save_upload and then change their status to permanent via file_save. It seems file_save_upload only takes a name and NOT an array. How can I accomplish this?

Here is how you could do it.

function mymodule_testes($form, $form_state) {
// your form definition goes here
  $form = array();
  $form['upload'] = array( // note the key
    '#type' => 'file',
    '#title' => t('Choose a file'),
    '#weight' => -10,
  );

  $form['upload2'] = array(
    '#type' => 'file',
    '#title' => t('Choose a file'),
    '#weight' => -10,
  );

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

  return $form;
}

function mymodule_testes_validate($form, $form_state) {
  dpm($form_state);
  // pass proper args to file_save_upload .. see documentation
  $file1 = file_save_upload('upload' , array()); // remember the key
  $file2 = file_save_upload('upload2' , array());
  // you dont have to do it verbosly
  // Do all your  validations  if(!$file1 || !$file2) form_set_error ...

  // save it onto form_State
  $form_state['files_storage'][0] = $file1
  $form_state['files_storage'][1] = $file1
  dpm($file1);
  dpm($file2);

}

function mymodule_testes_submit($form, $form_state) {
 // using devel so you could see how it is stored
 dpm($form_state);

  foreach ($form_state['files_storage'] as $key => $file) {
    $file->status = FILE_STATUS_PERMANENT;
    file_save($file);
  }
}

Hope this helps


Adding link to the main help page I have created an help page for my module

function amu_hal_help($route_name, RouteMatchInterface $route_match) {
  switch ($route_name) {
    case 'help.page.amu_hal':
       return 'some content';
  }
}

This does create a page at

  /fr/admin/help/amu_hal

How can add the correspondong link on main help page

  /fr/admin/help

i found out that the code above create automatically a link in the main help page, as long as the .info file indicate

  name: AMU HAL

and not

  name: 'AMU HAL'


Display of View (using grid) is unevenly distributed Note: as a neophyte user, I'm not allowed multiple links or images. It has been suggested that I edit the hyperlinks so they're not quite right. Hopefully you can sort out what's going on.

Here is my view with taxonomy terms in columns, but you see that the columns are a bit wonky and not evenly distributed.

These are the the grid settings

And this is the page h ttp://imgur.com/puH2v1M

Thanks.

My guess (I cannot be sure without seeing the HTML and CSS) is that the grid display uses HTML tables to create the grid. Because this looks exactly like what HTML tables do: they adjust their column width to the content in it. For instance, "General Fiction" is longer than "Genre" so the first table column is wider than the second. Because your view is grouped, every group would render a separate table, so that's why the columns cannot align.

Assuming that tables are indeed the cause, the solution would be to add custom CSS setting the width of <td> elements in this view to 33.3%. (How you can do that, depends on your theme setup and is beyond the scope of this answer.)


Alert message after add product I am using Drupal 7 and the Commerce module.

How can I set the alert message after adding a product in Drupal Commerce.

you need to use a callback in your submission .. something like this:

        YOURMODULE_form_alter(&$form, &$form_state, $form_id) {
    if($form_id == 'YourFormID') {
          $form['#submit'][] = 'custom_submit_function';
        }
}

        function custom_submit_function($form, &$form_state) {
          drupal_set_message('ALERT MSG HERE');
        }

this drupal_set_message() would give you the normal drupal message

if you don't know how to know your form ID ,, just print $form_id inside hook_form_alter() you'll see it there so you can make your if condition depending on it.


How do I get last inserted record ID? I want to get the record ID for the last inserted row in a database table. I am trying to use db_last_insert_id(), but it is throwing an exception.

  Call to undefined function db_last_insert_id()

How do I get last inserted record ID?

In Drupal 6 you would use code similar to the following.

db_query("INSERT INTO {mytable} (intvar, stringvar, floatvar) VALUES (%d, '%s', %f)", 5, 'hello world', 3.14);
$id = db_last_insert_id('mytable', 'id_fieldname');

The Drupal 7 equivalent code is the following.

$id = db_insert('mytable')
  ->fields(array(
    'intvar' => 5,
    'stringvar' => 'hello world',
    'floatvar' => 3.14,
  ))
  ->execute();


Resolution of Recaptcha Error in Drupal 7 forms I am using Recaptcha module for filtering the spam on the form.
But the form contains some alax file upload field which stop recaptcha to work properly. Every time I upload the file in the form by AJAX it is giving me following message:

CAPTCHA session reuse attack detected.

This made me difficult to use the module. Please let me know if there is any work around to solve the problem.

I am just newbie in Drupal 7. If there is any better spam protection module than recaptcha then also suggest me.

I personally use the Are You a Human PlayThru Module:

PlayThru is designed to be more simple, more intuitive, and more fun than other CAPTCHA options. We use game mechanics to create an experience that’s more enjoyable than figuring out what that awful squiggly text says.
PlayThru is also more secure. Because users interact directly with PlayThru, we can analyze that interaction and track the resulting data to generate a Human Confidence Score: our level of confidence that a user is an actual human.

You can also check out a video about it this module here:
Drupal 7 Are You a Human PlayThru Module - Daily Dose of Drupal episode 78

Update
The Are you a human PlayThru service has shutdown, I recommend you go with ReCaptcha

Uses the Google reCAPTCHA web service to improve the CAPTCHA system
and protect email addresses.
reCAPTCHA helps power massive-scale online collaboration.


How to Display Custom Token in Rules UI Data Selector? We use Rules and its submodule, Rules UI to manage our Rules. We have recently created some custom tokens, which are under the 'node' type. I have tested to make sure that these tokens 1) get the proper value and 2) are present among the Drupal tokens (by viewing them at /admin/help/tokens).

We would now like to use these tokens, both present under 'node'. However, they refuse to show up in the Rules UI. I have tried to add a condition to the Rule that 'Entity has field' of the custom token(s), but they do not appear there.

How can I make a custom token appear in Rules (UI), when it already exists in Drupal's token system?

Update:

The Token is an email address. It appears the token will appear in the field where I can select an email to be sent. However I would really like it to be available in the 'Entity has field' and/or the 'Data is empty' selectors, so I can choose whether or not to send the email based on whether the token has an email address associated with it.

Any ideas for getting it to appear in either of these locations ('Entity has field' or 'Data is empty')?

Here are 2 options you may want to try:

Rework your Rule so that part of the logic of it you move to another (new) Rules Component (which uses "node" as a parameter) and then in your rules component check in its conditions if those tokens become available.
Use the Conditional Rules module so that within your Rules Action you can add a "condition" where these tokens may show up.

As per your "It appears the token will appear in the field where I can select an email to be sent", either of both options should work, if you use those options AFTER the Rules Action where you can already use the token for sending an eMail.


What is causing formatting to break? We are using WYSIWYG with CKEditor on Drupal 7.

When the edit button on a node is clicked, the edit page shows text in a jumbled mess, even if there was careful formatting. The text formats have the "Convert line breaks into HTML" filter enabled,  as well as having the <p> and <br> tags allowed.  As per a comment, I have taken these tags out of the allowed HTML on the filtered HTML format.

WYSIWYG Linebreaks is enabled as well, but doesn't seem to solve the issue.

If breaks are added in, they seem to stay, even when editing the text again.

My question is: What is causing this formatting to break, upon clicking the edit button?

Example of ruined formatting:

On the left is what you see when viewing the page before it has been edited (i.e. the page was written by someone else), and on the right is the jumbled mess that is the edit page. On the edit page, all the paragraph or line breaks have been removed.

You are using using filtered html (Text Format).   [As per your screenshot above]

Filtered HTML only all the following HTML tags

Web page addresses and e-mail addresses turn into links automatically.
Allowed HTML tags: <a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd>
Lines and paragraphs break automatically.

  You need to change text format to FULL HTML if you wish to retain all HTML formatting

As a best practice Full HTML use should be limited


Module broken by drupal core update (mysql_num_rows) So I just updated my Drupal core to the latest (6.2.9) because of the many critical security recommendations.

I have a module which I built and previously, just before the update I had tested the module which uses a hook_cron() function and everything seemed to work as expected.

After the update It seems completely broken, I keep getting a warning "warning: mysql_num_rows() expects parameter 1 to be resource" which I have read a lot about others having the same problem in other threads, couldn't find a solution which worked, but the thing is, it was literally just working for me!!

I ran the $result query in a shell and it seems to return the expected data, I don't know what the problem suddenly is. All other modules appear to work normally.

function httprequest_cron() {
  $result  = db_query("SELECT nid FROM {httprequest}");
  if (mysql_num_rows($result)) {
  // results returned
  $url = 'http://localhost:3000/blog?status=fetch';
  $result = drupal_http_request($url);
  if (isset($result) && in_array($result->code, array('200', '302', '307')) && $result->data != '') {
  db_query("DELETE FROM {httprequest} WHERE nid");
  }
  }
  else {
  // no results, but good query
  }
}

You should use db_affected_rows() function of the Drupal instead of mysql_num_rows() function of mysql to check number of rows result from query.

Your code should be:

$result  = db_query("SELECT nid FROM {httprequest}");
    if (db_affected_rows()) {
    //your code
    }

Instead of

$result  = db_query("SELECT nid FROM {httprequest}");
if (mysql_num_rows($result)) {
//your code
}


How to check whether multi value field is of type field_collection_item or not? I am trying to check the type of multi value field is a field_collection_item or not inside computed field using this code:

$wrapper = entity_metadata_wrapper($entity_type, $entity);
$fields_info = $wrapper->getPropertyInfo();
foreach ($fields_info as $req_field) {

  if ($req_field['type']=='field_collection_item') {
    //do something here
  }
}

The if statement failed as $req_field['type'] returns list<field_collection_item>.

Any ideas?

That's how an EntityMetadataWrapper stores multiple fields. There are only those two types, so just use

if($req_field['type'] == 'field_collection_item' || $req_field['type'] == 'list<field_collection_item>') {
  // So something here
}

Or some variation on that.


alphabetize the taxonomy term page without views Is it possible to alphabetize the taxonomy page without using views?

for example:

THE TERM'S NAME
- A node
- B node
- C node
- D node

Thanks.

CLARIFICATION: I know I can reset the terms themselves to alphabetical, but that does not reset how the node teasers on the taxonomy term page are displayed (these remain in the order they where created). Resetting the display of teasers is what I am trying to achieve.

The taxonomy module uses the taxonomy_term_page function to build the page that list the nodes attached to a term. But the function that really do the query is the taxonomy_select_nodes that is called by this previous function.

Remember: Never hack core

So you can implement a custom module and use the hook_menu_alter to rewrite the page callback for the taxonomy/term/%taxonomy_term path using a new function based on the taxonomy_term_page to call your custom taxonomy_select_nodes function that perform the changes you need to order the nodes that way.

You'll need to do something like this:

function mymodule_menu_alter(&$items) {
  // Rewrite the taxonmy term page callback
  $items['taxonomy/term/%taxonomy_term']['page callback'] = 'mymodule_taxonomy_term_page';
}

After that you'll have to implement the mymodule_taxonomy_term_page function in order to be able to make the changes you need on the taxonomy_select_nodes() call:

function mymodule_taxonomy_term_page($term) {
  # code...

  if ($nids = mymodule_taxonomy_select_nodes($term->tid)) {
    # code...
  }
  # code...
}

Finally:

function mymodule_taxonomy_select_nodes() {
  # code...
}

You'll must JOIN the node table to build the query in the mymodule_taxonomy_select_nodes function because the taxonomy_index table doesn't have the node title.

Notice that will change the behavior of all taxonomy term pages.

For more info about how to create a custom module see http://drupal.org/node/361112.


How to open a new form in a block without reloading whole page? I am using Webform with ajax mode. I have added the Webform in block so as only the block is refreshed instead of whole page, it's working fine.

All I want to do is open new form after getting confirmation message without reloading whole page.

How can I do so?

You need to set the "Redirection Location" to "No redirect (reload current page)" in actual webform settings (/node/x/configure). This will show the confirmation message in block without reloading and provide a link "Go back to form" which will reload your form by ajax.


How to fix rules which unable to evaluate action? I have created two rules to act on some events related to commerce products.
The first is to act on reference node delete event, to remove the product upon node delete.
the second is to delete the node upon expiration event using node_expire
When running the cron to make expired event to be happen no actions executed except if I disabled the first rule
I have tried rules components and rule sets as that two rules have conditions and actions in common But nothing changed.
Edit:
I did some debugging and found that warning and error messages

[warning]
WD rules: Unable to load commerce_product with id "102"
WD rules: Unable to evaluate action entity_fetch.
WD rules: Unable to get variable entity_fetched, it is not defined.
[error]
WD rules: Unable to evaluate action entity_delete.

The error:

  WD rules: Unable to get variable X, it is not defined.

means that Rules can't load the variable X.

If you're using contributed modules, please check if your rules are in the right order and the configuration is right, otherwise check the module issue queue for possible bug issues.

If you're using custom modules, please make sure that these rule variables are passed in the correct way.

For example if you've the following sample rule in hook_rules_action_info:

'foo_rule' => array(
  'label' => t('Foo rule'),
  'provides' => array(
    'object_to_send' => array(
      'type' => 'data',
      'label' => t('Data Object to pass'),
    ),
  ),
),

The object_to_send needs to provide the matching array key, e.g.:

return array( 'object_to_send' => $object);

So the next rule in sequence will "see" that variable, so you can use it.


Creating a layout with Page Manager I'm trying to use Panels and Page Manager in Drupal 8. My current versions of each are:

Page Manager: 8.x-1.0-alpha23+12-dev
Panels: 8.x-3.0-beta4+41-dev

My current problem is having no idea how to actually make a layout (layout_plugin is installed.) I'm seeing this screen:

It doesn't matter what I change "Layout" to, the "Layout Settings" section doesn't change. I'm somewhat familiar with Page Manager in D7, and expected there to be some sort of layout manager in there, allowing me to choose panels/blocks/etc. I know there's a "Block Page"--and this would work for me--but in any of the tutorials, I've heard something about Block Page NOT being for production?

Nearly EVERY video/tutorial I've seen uses some other version of panels/page_manager, and the look/structure has changed. So, I'm not sure if I'm doing this right or not, if it's broke, or if I just have no idea what I'm doing.

Panels, Page Manager and CTools was supposedly synced with their alphas last year, but they look like they've separated and I'm hesitant to use 5 month old versions of modules on a new release like D8 (particulary, CTools.)

Go to all recommended versions.

I was using different/more recent dev/alpha/beta versions of certain modules, but when I went to the recommended versions of...

panels (8.x-3.0-beta4)
page_manager (8.x-1.0-alpha23)
layout_plugin (8.x-1.0-alpha22)

... everything seemed to work okay. This was as of 7-6-2016


Auto Increment on users table is not functioning I need to Create a new user programmatically. So, I have used user_save method, as shown here:

$usersave = array(
'name' => 'abc',
'pass' => 'abc',
'mail' => 'abc@gmail.com',
'status' => 1,
'roles' => array(
  DRUPAL_AUTHENTICATED_RID => 'authenticated user',
      5 => 'customer'
),
);

$save = user_save($usersave);

But it throws this error message:

  PDOException: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '0' for key 'PRIMARY': INSERT INTO {users} (name, pass, mail, status) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2, :db_insert_placeholder_3); Array ( [:db_insert_placeholder_0] => abc [:db_insert_placeholder_1] => abc [:db_insert_placeholder_2] => abc@gmail.com [:db_insert_placeholder_3] => 1 ) in drupal_write_record() (line 7383 of /home/vijay/public_html/vssb/public/includes/common.inc).

What's the issue?

This is a duplicate of Create a user programmatically and give they a role

// The first parameter should be blank so a new user is created.
user_save('', $new_user);

If you want to use user_save($new_user); you can set $new_user->is_new to TRUE or omit the $account->uid field.


How to promote nodes to front page using MySQL command line What is the command to promote unpromoted nodes to front page using MySQL command line? I want to promote 200 nodes at once. The node type is "story."

UPDATE node SET promote=1 WHERE type="story" AND promote=0 LIMIT 200;


drush arr (drush archive-restore) says: Missing required argument: file I have been requested, against my better advice, to try to ensure that a Drupal site for an associated part of our organisation is up to date, although the site developers left no admin maintenance documentation nor information about any custom setup that they may have done, and now seem to be uncontactable (poor project management on the part of the site owners).
The standard Drupal update did not work, and I now have to try to revert the site back from the drush archive that was taken just beforehand.
However, drush arr (drush archive-restore) says:

Missing required argument: file.

I'm not sure what file I need to specify (our own installation of Drupal is somewhat customised and clear upgrade instructions, working in a different way, are supplied by the maintainers).
Looking in the drush-backups folder, I seem to have two choices:
/root/drush-backups/archive-dump/20200831154526/sitename.20200831_154526.tar.gz
/root/drush-backups/sitename/20200831154744/drupal/

(the latter of which seems to contain the Drupal files as-is (not as a .tar.gz file))
Is the .tar.gz file from the archive-dump folder the file that drush arr is wanting, and then drush will know how to find the rest automagically?

drush arr is expecting a site archive file as an argument. Its sibling drush command,drush ard, creates a site archive file. (see the drush codebase for more details on how this command works) The /root/.../drupal/ path is a backup drush creates when you run drush up
The /root/drush-backups/archive-dump/ path matches the format of drush ard's default output but if you didn't create this archive file you should inspect it (tar -tvf) to confirm it has the code/files/DB backup within it.
So yes, drush arr will restore from a site backup but you should take necessary precautions since you've inherited an undocumented process.


Adding class to form-item I've been trying to add a custom classname to a form-item to use as a 'marker' for theming with my css file.

I've been on stackexchange/overflow and several other sites and forums, including the Drupal documentation, but found no reason why it shouldn't work.

Official documentation state the use of the attribute tag like so:

'#attributes' => array('class' => 'myclass'),

But as seen in my example below, this doesn't work or give me errors.

Am I doing something wrong?

#attributes is not supported by item form elements.

  item

  Description: Generate a display-only form element allowing for an optional title and description.

  Note: since this is a read-only field, setting the #required property will do nothing except theme the form element to look as if it were actually required (i.e. by placing a red star next to the #title).

  Properties: #access, #after_build, #description, #element_validate, #parents, #post_render, #prefix, #pre_render, #required, #suffix, #theme, #title, #tree, #type, #value, #weight

You would then need to add a custom theme call such as:

function MYTHEME_preprocess_form_element(&$vars) {
  $vars['#attributes']['class'][] = 'another-class';
}


How do I capture a page as HTML? I have a controller that generates a custom 500 page.  I have set up a route at the path: '/500'.  I would like to capture this as HTML and save as a static file, so that I don't need to bootstrap Drupal and run that controller when I return a custom 500 page.

I have been using this code:

  global $base_url;

  $contents = file_get_contents($base_url . "/500");

This works for me locally, but we have a lot of restrictions on our QA site so that file_get_contents is blocked.

Is there another way to render the entire page that this controller would return?  For example, with the render service?

Also, I would want it in a logged-out context.  I wouldn't want the admin toolbars, etc. to show up.

I found some code about subroutines.  Is that a good way?  I'm sure there's a way to use the Drupal render service to render a render array with the entire page.  That sounds maybe the best way to do this?

Does anyone know how I might render the entire page programmatically?

I'm thinking in order to render the metadata and page classes based on a route, you're pretty much required to make a request.

There is another question about rendering parts of the page, but not the entire page.

If you bootstrap Drupal, you can just tell it to serve a particular page. Consider the content of index.php:

<?php
use Drupal\Core\DrupalKernel;
use Symfony\Component\HttpFoundation\Request;
$autoloader = require_once 'autoload.php';

$kernel = new DrupalKernel('prod', $autoloader);

$request = Request::createFromGlobals();
$response = $kernel->handle($request);

If you replace the Request::createFromGlobals with a new Request(...), you can pass explicit values for the $_GET etc parameters. The function signature copied from Symfony is as follows:

/**
 * Constructor.
 *
 * @param array           $query      The GET parameters
 * @param array           $request    The POST parameters
 * @param array           $attributes The request attributes (parameters parsed from the PATH_INFO, ...)
 * @param array           $cookies    The COOKIE parameters
 * @param array           $files      The FILES parameters
 * @param array           $server     The SERVER parameters
 * @param string|resource $content    The raw body data
 */
public function __construct(array $query = array(), array $request = array(), array $attributes = array(), array $cookies = array(), array $files = array(), array $server = array(), $content = null)
{
    $this->initialize($query, $request, $attributes, $cookies, $files, $server, $content);
}

So your custom script could require the autoloader, bootstrap Drupal, create a fake Request object, tell Drupal to handle it, then save $response->getContent() to a file.


I want to show the limited amount of products using JCarousel module? I am using Jcarousel module for products to show the front page. So I want to show the limited amount of products. I mentioned in views  Use pager: Display a specified number of items | 5 items .But it doesn't work it.. It shows the all produtcs in the front page.. How to configure it..

The solution is to add the following code around line 147 of jcarousel.views.inc

if ($view->query->pager->options['items_per_page'] != 0){
    $count = min($view->query->pager->options['items_per_page'], $count);
}

You can read more about the issue at https://www.drupal.org/node/2408883


How to alter menu parent select list on node form? I would like to modify select list for choosing menu parent for creating node (from the Menu tab). I am looking in $form variable but I don't see this list data. How can I alter this select list?

Menu module does form alter to add the Menu Fields to the node creation form using function menu_form_node_form_alter in menu.module

Check your custom module weights to catch this data in your custom module to do form alter...

There is a new drupal 7 API called hook_module_implements_alter() which lets you alter the execution order for a given hook WIHOUT altering the module weights table.


What can cause a site to hang when deleting a user? When I try to delete users the whole site hangs, i.e. Drupal does not respond anymore. What can cause that?

The site does not have any special user profile modules installed.

Edit:
There is only one custom (self made) module with a hook_user which switches on $op. The 'delete' case looks unsuspicious:

case 'delete':
    $sql = "DELETE FROM {mynewsletter_users} WHERE uid = %d";
    db_query($sql, $account->uid);
    break;

Doesn't look bad to me. Should not invoke a hook_user-circle.

Edit:
The problem is gone all by itself. No idea what happened.

For me, this has happened when there is a misconfiguration on hook_user in a custom module. Specifically, check all of your implementations of hook_user to make sure there are no functions that lead to additional calls for hook_user.

That is, if you have a module that calls foo_do_magic_to_user() under hook_user (or, some other function that hits hook_user), and foo_do_magic_to_user() calls user_save(), then you have an infinite loop on your hands.

Update

If you're absolutely certain that it's not a hook_user loop, then there could be any number of module-associated hangups. These often involve external services that are non-responsive (e.g. sending a "Goodbye" email but sendmail (or equivalent) isn' set up properly).

In your shoes, I would try:

1) Disable all non-core modules and see if the problem persists. If this still happens with only core modules, then you might have a deeper and more fundamental issue (correct version of PHP?)

2) If not #1, then re-enable contrib modules one-by-one and see which one is causing the issue. Inspecting that module's hook_user should give you a good clue as to what the root issue is. Most likely, one of the modules is calling some other service that is non-responsive.


Is it possible for the Contact page to have 2 URL aliases? or clone it? My client is wants the Contact page to be available in more than one place in the menu system. Problem is this would interfere with how sidebar menus load. so ideally it would be nice to have 2 URL aliases for it,  …or as alternative just clone the page.

Does anyone know how to do either of these options. I need to do the same for the User page.

big thanks in advance!

The Redirect module would allow you to create another url for for your contact page. One would simply redirect to the other.


How to put a site in maintenance mode by non-admin Is there a module (or other way) to give permission to non-admin-users to put the site offline (and only that permission)?

There is a module for that!

Maintenance Mode Permissions

  Placing a site in or removing it from maintenance mode is allowed
  under a permission that has wide spread administrative access
  (administer site configuration). Sometimes you'd like to give
  permission to put the site in maintenance mode to someone but not give
  them complete access. This modules enables this case.


In views formatted as table, columns with taxonomy term fields are sorted according to term ID, not label In Drupal 8 I have View formatted as table, where user can click to any column header to sort displayed records according to the given field. This works well for numbers (ascending/descending), as well as for plain text (ascending/descending for title or any other text values), records are then sorted correctly alphabetically. But this does not work for taxonomy terms - they are sorted according to taxonomy term ID and not alphabetically according to label.

I.e. I wish to display in the table column with a taxonomy term (only one value is allowed per node) and be able to sort the table alphabetically.

In my use case I have records about plant specimens containing plenty of fields, including e.g. species or life form. These are taxonomy terms. I'm displaying the specimen records in table filterable according to various criteria, e.g. various traits. The table is also sortable according to any column, e.g. species, but in this particular case, it is sorted according to taxonomy term ID and not naturally by label.

I found several answers to similar problems, but nothing exactly fitting my problem. Views Natural Sort module might also help, but its development status is not very promising.

That's because the stored value of the field is the term ID, the label of it is just how it is displayed.

To sort on the name, you need to instead add a relationship using that field to terms, and then add the name field of that relationship. Then you should be able to sort it as well based on that.


Drupal 7 Custom Theme - Administration menu missing or not showing This should be an easy query for those that have been using Drupal 7 for some time and have created their own custom themes.  I have created a custom theme which appears to be working, but it does not show the administration menu which is normally located at the top of the screen does anyone know what needs to be done to get it too show - e.g. what line needs to be added to the html.tpl.php file ...

one source suggested

<?php print $closure; ?>

But this might have been more geared towards Drupal 6 ... I'm working with Drupal 7... another source suggested adding:

<?php print $page_top; ?>

But that doesn't appear to help either.

Anyone got any ideas on how to added the administration menu which normally shows at the top of the page?

Side Note:
Are other themes making use of template.php files and hooks to get the administration menu to show?

You need to print the $page_bottom just before the  tag in html.tpl.php.

You do need $page_top too, and $page, so taking the default html.tpl.php as an example:

<body class="<?php print $classes; ?>" <?php print $attributes;?>>

    <?php print t('Skip to main content'); ?>

  <?php print $page_top; ?>
  <?php print $page; ?>
  <?php print $page_bottom; ?>


Views content pane - return half the results I'm trying to work a view into a panels layout and would like to break up the list of results with another type of panel in the middle. Is it possible to create a views content pane returning the first half of all results, then a second views content pane returning the second half? Or is there another way to do this?

I can imagine some options using a custom template for the view, but I'd prefer to do this through Drupal config if possible.

When editing your view, click on (+Add) button at the top and select block. So now you should have 2 blocks.

In block 1, for pager, select Display a specified number of items, then for items to display, put 10 and leave offset 0.

In block 2, do the same, except you need to put an offset 10, so it starts displaying at row 11.

Then add block 1 and block 2 to your panel.

EDIT: Possible solution when you don't know the number of items

In summary: We are going to move row x and everything below that using jquery.

You would have to use php in the template file and divide the view
total count by 2 and round up the answer (cause you might have 21 in
total).
Add a Global view result counter field, to your view.
So now we are able to target each row.

So for example if total is 21 then /2 = 10.5, roundup to 11. The 11 will be saved as a variable.

Then just do an if statement if

( $fields["counter"]->raw = $variable) { print "<div class"move"> ... all the other stuff }

Then use the total to close the div at the last row.

Then just do an if statement

if ( $fields["counter"]->raw = $total) { print all the other stuff ... "</div>" }

You would also have to print the calculated number (11) inside a div, so then we can grab the total using jquery.

If your middle pane varies in height, you would have target the div and calculate the height with jquery so then we can add this number to the jquery $('.move').css()

Also, you would need to caculate the height of the "move" div and and assign that to the last panel div.

Lastly, you move the "move" div using jquery .css() by the height of the middle pane + 5 or so more px.


Manually trigger AJAX from custom JavaScript I'm in the process of developing a form where the user enters a UK postcode and the textfield is replaced by a select list. This all works quite nicely when using the blur event, but it is not always obvious the field has changed.

I would like to use the keyup event instead, but there is a small delay each time the key is pressed as the AJAX keeps firing, I have an existing function which is bound to the field:

$('#edit-postcode').bind('input', function(){
  $(this).val(function(_, v){
    return v.replace(/\s+/g, '').toUpperCase();
  });
});

I already have a simple regex /(^[A-Z]{1,2}[0-9]{1,2})\s?([0-9][A-Z]{2}$)/i to ensure it's broadly the correct format. I would like to add the validation into the previous function and if the string passes validation trigger the existing AJAX functionality.

N.B. the default Drupal autocomplete functionality works almost perfectly apart from not being able to hide the ID which relates to the postcode which is why I've resorted to this method instead.

It turns out that it's actually much easier than I thought, by using a custom jQuery event, in my case I called in postcodeValid:

'#ajax' => [
  'callback' => [$this, 'checkPostcode'],
  'event' => 'postcodeValid',
  'wrapper' => 'postcode-container',
],

I changed the JavaScript function I already had to:

$('#edit-postcode').bind('input', function() {
  var trigger = $(this);
  $(this).val(function(_, v) {
    if (isValidPostcode(v)) {
      trigger.triggerHandler('postcodeValid');
    }
    return v.replace(/\s+/g, '').toUpperCase();
  });
});

The isValidPostcode function is a simple test against my postcode regex, thanks to Delay ajax call on textfield to allow for typing I was able to discover this.


Image / ImageField / ImageCache (automatic thumbnails) I'm getting pretty frustrated here:

I'm a complete newbie with Drupal, just installed some modules like CCK, and made a new Content Type for my website to display products (no webshop purpose, just displaying them).
It also has an image field, for the user to upload an image, but what I'm trying to do here is have a thumbnail somehow automatically created (to display in the overview).

It seems like such a simple thing which every CMS should be able to do easily (and I'm sure it's possible) but I just don't know how it's done.

After googling quite a while I found a lot of articles on the subject however they all seem to refer to modules such as ImageCache, ImageField, and after some research about the mentioned modules it seems to me they have somehow been merged into one module: Image in Drupal 7.7

This is driving me crazy, and I would very much like to hear a simple explanation on how to get to the desired result.

Here is a tutorial that will walk you through adding images.

http://www.youtube.com/watch?v=l0I5f9YmmI0


How would you assign a taxonomy term on user registration programmatically? I'm struggling to figure out how to programmatically assign a taxonomy term to a user in Drupal 7.

I have a term reference field [field_event_location] on the user registration screen. What I want to occur is to have an Administrator (role) create a new user and assign the meeting manager (role) to a set term.

Once the meeting manager(role) creates a new customer(role) through the user registration form, the term reference field will be automatically set to the term associated with the meeting manager user that was previously set by the Administrator.

I haven't found a contrib module that does this, so I was starting down the path of creating my own module using HOOK_user_presave

 /**
  * Implements hook_user_presave
  */

  function mycustommodule_user_presave(&$edit, $account, $category) {
    global $user;
      if(isset($account ->is_new) && !empty($account -> is_new)) {
        $roles = user_roles(TRUE);
         if(in_array('meeting manager', $user->roles)) {
          //set user they are creating to the role of 'customer'
             $rid = array_search('customer', $roles);
             $role = user_role_load_by_name('customer');
             $edit['roles'][$rid] = 1;
         //assign the customer to the same location as the venue admin
           $edit['field_event_location'][LANGUAGE_NONE][0]['target_id'] =  field_get_items('user', $user, 'field_event_location', LANGUAGE_NONE);
      }
    }
 }

Have you considered using Rules?
You could have it react on updating an After saving a new user account,

check for the role being set,

Click on Add Action, select Set Data Value

For DATA Data Selector put account:field-[name] In mine I named/called the term reference field test
For VALUE Data Selector put site:current-user:field-[name]
We use site current user, because the current logged in user is the Meeting Manager, so we use their term ref field value.

Result:
This is how it should look like for you. Except for you the authenticated user in condition should be customer and in Action the test should be your term ref field name.


How to customize the edit link in Views I have added an edit link before the title in my View by adding the field Content: Edit link on top in the fields list, excluding it from display and not adding any text in the field "Text to display". I also rewrote the output of my title field like so: [edit_node] [title].

That gives me a link with the text "Edit" just before the title (in spite of leaving the text field empty as explained above). But I would like to change that text into a symbol. I have tried a number of things including CSS, but I am stuck on this thing.

Can anyone help?

Simply rewrite the results of Content: Edit link and add image with HTML.

<img scr=".....">

For Example:


How can I programmatically enable permission for anonymous users to view comments on a single node? How can I programmatically enable permission for anonymous users to view comments on a single node? Comments are open, but by default anonymous users are not allowed to view comments. I would like them to on one single node.

There are a couple ways to handle this and it depends on when you want to make the change.

What you'll want to change is $node->comment to one of the following:

COMMENT_NODE_CLOSED
COMMENT_NODE_HIDDEN
COMMENT_NODE_OPEN

You could use a hook_node_presave() function to change the value prior to saving based on some logic.  Or you just need to get access to the node object through other means like node_load().  Just make sure to save the node if you're loading it up to make the change.


Creating a list of node-options in different node I am looking for a way to list nodes in a different node. Not sure how to explain this, so I will do it with an example.

Let's say I'm for example making a website for a Tennis tournament, this is not the real purpose, so if you have a different solution for this, it's probably not what I need, I want to achieve what I'll say in this example:

I have the following nodes:

Player
Match

In player I have:

Player name
Player age
Player ranking
etc...

In the node match, I have a few settings, including:

Player 1
Player 2

What I want to achieve is that in the node "match" I can choose 2 players from the node "player". In the list it shows the player name, however, I should be able to get the extra information as well when rendering the match node.

Any ideas if a certain module excists that could help me out?

Thank you very much!

Edit 22/07/2014:

As an addition, I would also like a different list to inherit his items depending on a previous selected item.

So for example I have 3 nodes:

Car
Brand
Model

The first thing that I would do is:
I make different brands as "Brand" nodes content:

BMW
Mercedes
Volvo
...

Afterwards I make a Model. In model I make the models
- 'Z4' => And in the list I choose "Brand: BMW"
- 'S60' => And in the list I choose "Brand: Volvo"
- 'V70' => And in the list I choose "Brand: Volvo"
- ...

Now I want my third node "car" to be for example for a seller of cars.
So the seller sells a car. He makes a car node and enters the following information:

Buyer: Person A
Address: Address X
Age: 99
Licenseplate: 1 XXX 999
Brand: ....
Model: ....

So what I'm trying to achieve is that the seller has a list of all brands.
If he chooses brand "Volvo" for example, then the Model list should appear and show all models for the chosen brand.

I think what you're wanting can be accomplished with views.  You may need to add some fields to make the context work for your needs.


Accessing contents of a node id not working in .theme file I have a page(node) with a certain ID.
On the front page, I want to pull a field called field_image1 and field_link1.

To do that I added the following to my themename.theme:

function themename_preprocess_page(&$variables) {

    $variables['vanilla_spice'] = Node::load(61);

    $variables['variable'] = "tetsing the variable";

}

page--front.html.twig:

{{ kint(vanilla_spice) }}
{{ kint(variable) }}

When I visit the page, the variable is null :(

How can I load this information inside the variable?

Note: I based myself in this answer here, but even if I assign a normal string to the vanilla_spice variable

$vanilla_spice = "tetsing the variable";

I still see a null.

First, you are using the wrong hook. peeprocess_node won't send new variables into the page template. You need preprocess_page for that. The page template is not the same as the node template.

Second you are not assigning any new variables. You have to add or alter what is in $variables array or they are not passed to the template.

$variables['vanilla_spice'] = "testing the variable";


How to make mail messages use the UTF8 character encoding? I am sending mails to users about products, using the SMTP Authentication Support and Mime Mail modules. I set UTF8 as charset in the mail header, but the header is changed from UTF8 to multipart on this line in the mail.inc file:

$message = $system->format($message);

It actually changes the Swedish characters to some strange characters. So that's the problem: I can't display them correctly.

Any suggestions to correctly display them?

Content-Type: multipart/alternative; means that there are parts that can have their own encoding set. If your mail sending modules decide they need multipart, mail should be formatted like that:

MIME-Version: 1.0
Content-Type: multipart/alternative; boundary=boundary

--boundary
Content-Type: text/plain; charset=utf-8

This part uses UTF-8.
--boundary
Content-Type: text/plain; charset=iso-8859-1

This part uses ISO 8859-1.
--boundary--

code sample source here

If you called everything the way module docs tells you to, and UTF-8 data is not in the UTF-8 part, then you just found a bug in one of your modules.


how to delete the files uploaded in the file field? if i remove the files that were uploaded in a File field,and then upload a same name file, the file removed just now is still present in the server and the new uploaded file gets renamed to a name with index ,say, xxx_0 ,xxx_1.

What I want to do is when I remove a file, it should be deleted from the server, to save space in the server, How can I do this?

I also crossed this issue.
I just did these following steps.

edit the node, and delete the file from the field (dont upload now) and save it.
then edit the node, now upload the file (with same name) and save it.

Its worked for me. without xxx_0 like that.

Thanks


How to resolve the error when adding an entity reference relationship? Multifield Contributed Module - https://www.drupal.org/project/multifield

Company Content Type has multifield

1) Company Division - Entity reference
2) Company Categroy - list

While adding relationship as entity reference node company division in views an error is thrown.

  SQLSTATE[42S22]: Column not found: 1054 Unknown column 'field_fieldname_node.id' in 'on clause'

It looks like your issue is because of the Multifield issue Add Views API integration for the multifield field type. And that the patch attached to comment nr 96 of this issue solves it.


"An AJAX HTTP error occurred.HTTP Result Code: 200" I'm new to Drupal, and I'm working with a Drupal site that someone else wrote. From the admin menu, when I go to Structure -> Pages -> Edit Content -> Gear Menu -> Edit (or Settings), Drupal throws up this error:

  "An AJAX HTTP error occurred. HTTP Result Code: 200 Debugging
  information follows. Path:
  /panels/ajax/editor/edit-pane/panel_context%3Apage-join_step_two%3Apage_join_step_two_panel_context/4
  [...] RESPONSE = nullnullnullnullnullnullnullnullfalseCancelled: Error
  bad character content for element
  'data_key'________nullnullnullfalsenullnull"

The code is also inserting the line

  "RESPONSE = nullnullnullnullnullnullnullnullfalseCancelled: Error bad
  character content for element 'data_key' ________
  nullnullnullfalsenullnull"

at the bottom of every page.

I know that Firebug can cause the Ajax HTTP 200 error, but I don't have it installed. I've spent hours looking through help pages for this error, and nothing has worked. Can you help? Thanks!

we need to uncomment .htaccess file in php_value auto_append_file none may be it work.
in ajax return value must be defined.if not exist show this kind of error.clear cache.
 one other solution if you working on the local you need to disable newest module than check it[first you need to take DB backup].


Multistep form loses input when visiting previous step I am developing a custom module with the ability to store data on an external database using Drupal 7 Form API.
I started with the multistep form example, added few more steps and other fields.

To implement the ability to edit those data I created a class that retrieves returns an array suitable to fill the $form_state['values'] element in order to have a default value for each form element. Here follows the code I have in the form callback when going to edit my data:

if( !empty($form_state['build_info']['args'][0]) ) ) {
    $a = new ind();
    $a->get_ind( $form_state['build_info']['args'][0] );

    $form_state['values'] = get_object_vars($a);
    unset($a);
}

Problem is when I hit the previous/next buttons because of the form is being rebuilt always with the data from the class so every change in a field is lost when hitting "Previous"; suddenly every change gets lost when I click "Next" after "Previous" (fields are empty!).

How do you achieve editing with multistep form with existing data? I am stuck here attempting to put the code above at submit and previous handlers with no success.

I think you should add if statement with #triggering_element or #clicked_button. Example:

function PREVIOUS_STEP_submission_OR_SOME_KIND_OF_CALLBACK($form, &$form_state) {
  if($form_state['clicked_button']['#value'] == 'BACK') {
    //show_previous_step()
  }
  else {
    $a = new ind();
    $a->get_ind( $form_state['build_info']['args'][0] );

    $form_state['values'] = get_object_vars($a);
    unset($a);
    // or your logic
  }
}


How do I configure subdomain url as one.mysite.com/subdomain1 I am a Drupal Developer currently working on Drupal 7.15 multi domain site. In my site, I have already installed Domain module and configured the domains as:

Main domain - mysite.com (say 1st level)
Sub Domains - one.mysite.com, two.mysite.com, ... (say 2nd level)

Now I need the 3rd level Domains as:

one.mysite.com/subdomain1,
one.mysite.com/subdomain2,
one.mysite.com/subdomain3.

But my control panel only has the option of setting this as one.subdomain1.mysite.com

Can any one help on this. Either how to configure the subdomain as of my requirement or else how to re-write the url?

Thanks

The Subfolders Domain module sounds like it'll handle what you're after. Additionally, you may want to read through my blog entry about serving Domain Access-controlled sites from subfolders instead of subdomains.


Get parent of an entity reference I have an entity reference inside node. How can I retrieve the parent node?

I tried with the following code, where $node is my entity reference, but it doesn't work.

$entity_ids = $query
    ->condition('type', 'user')
    ->condition('status', 1)
    ->condition('field_product_document', $node->getTitle(),'CONTAINS');

What is wrong in the code? What code should I use?

An entity reference field is implemented from the \Drupal\Core\Field\Plugin\Field\FieldType\EntityReferenceItem class. If you look at the code for EntityReferenceItem::preSave(), you will notice it is setting its target_id property to $this->entity->id().

public function preSave() {
  if ($this->hasNewEntity()) {
    // Save the entity if it has not already been saved by some other code.
    if ($this->entity->isNew()) {
      $this->entity->save();
    }
    // Make sure the parent knows we are updating this property so it can
    // react properly.
    $this->target_id = $this->entity->id();
  }
  if (!$this->isEmpty() && $this->target_id === NULL) {
    $this->target_id = $this->entity->id();
  }
}

I take your code should be changed to the following one.

$entity_ids = $query
    ->condition('type', 'user')
    ->condition('status', 1)
    ->condition('field_product_document', $node->id());

The change makes also sense: A node title cannot be used to uniquely identify a node, since there could be more nodes with the same title; the node ID uniquely identify a node on a Drupal site.


Alter field instance settings form on admin/structure/types/manage//fields/node../storage I'm trying to figure out how to add an extra field to content type field settings page.

Basically I want to alter field instance settings form on admin/structure/types/manage//fields/node../storage .

I'm going with hook_form_FORM_ID_alter for FORM_ID field_config_edit_form.
The new form element appears on the form but after submit I'm not able to see the value.

Am I missing something? Is an extra form submit function required other than the default one to submit my new value?

Here is my snippet -

/**
 * Implements hook_form_FORM_ID_alter().
 */
function mymod_form_field_storage_config_edit_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {

  $form['enabled'] = array(
      '#type' => 'checkbox',
      '#title' => t('Enable'),
      '#description' => t('If enabled then this module will alter the field settings.'),
      '#default_value' => $form['enabled'],
  );
}

Here is an example -

/**
 * Implements hook_form_FORM_ID_alter().
 */
function mymod_form_field_storage_config_edit_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {

  $form['enabled'] = array(
      '#type' => 'checkbox',
      '#title' => t('Enable'),
      '#description' => t('If enabled then this module will alter the field settings.'),
      '#default_value' => $form['enabled'],
  );

  $form['#entity_builders'][] = '_my_additional_form_field_storage_submit';
}

/**
 * Entity builder.
 */
function _my_additional_form_field_storage_submit($entity_type, Drupal\field\Entity\FieldStorageConfig $fieldStorageConfig, &$form, \Drupal\Core\Form\FormStateInterface $form_state) {

  if ($form_state->getValue('enabled')) {
    $fieldStorageConfig->setThirdPartySetting('my_additional_settings', 'enabled', $form_state->getValue('enabled'));
  }
  return true;
}


Webform Content with admin approval Hi I have a webform which user will fill and get a confirmation link.On clicking the confirmation link the user is a confirmed user.I want an add on functionality of admin approval in it so that after the admin approval the approved user name is displayed in a list.Any help please.Thanks in advance

There is a module for that. Check Webform Confirmation.

This is confirmation module. It sends an e-mail to users who submit the webform for verification by taking the email id from the webform.
On clicking on the confirmation link in the email, the user confirms that he/she is not a spammer. It works both for both Authenticated and Anonymous users.
Also, the administrator is able to keep a track of users who have confirmed their submissions.
Optionally, you can disable sending the confirmation link in the mail which would only send a "thank you" mail.


Deleting all terms from a vocabulary after timeout When I tried to delete a vocabulary, Drupal timed out and I don't think any or all of the terms in the vocabulary were deleted. How can I delete them manually in the database?

Can you run sql queries directly against the database? What makes you think the terms are still there? The vocabulary table contains data about the vocabulary, and you could do a left outer join with term_data to see if there are any "orpaned" terms. So something like (assuming you haven't used a prefix on your drupal database):

SELECT *
FROM term_data t
LEFT OUTER JOIN vocabulary v
ON t.vid = v.vid
WHERE v.vid IS NULL;

You can do a delete on a join if you need to but I suspect you won't find any orphans.

EDIT:

You should also probably check term_node as well that links terms to nodes. If you're going to run these deletes please back up your database first! Also as these queries are written, the term_node needs to run first.

-- Run this first
DELETE n
FROM term_node n
JOIN term_data t
ON n.tid = t.tid
LEFT OUTER JOIN vocabulary v
ON t.vid = v.vid
WHERE v.vid IS NULL;

-- Then run this query
DELETE t
FROM term_data t
LEFT OUTER JOIN vocabulary v
ON t.vid = v.vid
WHERE v.vid IS NULL;

Remember to back up your database first!


How to make table-responsive in drupal views I have created the views which renders table. I want to make table responsive without any contrib module. Is it possible?

Consider the Views Responsive Grid module. Here is a quote about it (from its project page):

... provides a views plugin for displaying content in a responsive (mobile friendly) grid layout. Rather than trying to force the standard Views grid display to work for mobile this provides the same functionality, but in DIVs instead of tables. Provided is also the ability to specify a horizontal or vertical grid layout which will properly stack the content on a mobile display.
Features:

Horizontal or vertical grid layouts
Custom classes for use with responsive themes

Of course, this requires the use of a contributed module (which is something you want to avoid as per the edited version of your question).
Assuming that it's OK to use a contributed "theme", you may should consider using a responsive theme, such as (popular) Omega or Zen themes. There is also the Beep Edition "theme", which (quote from project page) "is designed from the ground up as a mobile-first responsive theme". However that has like 5 module dependencies ...
For a list of way more (less known) responsive themes, refer to 26 More of the Best Responsive Drupal Themes. Quote from that link:

All of these free Drupal themes have responsive layouts, and they include great features like Bootstrap frameworks, Google Fonts, sliders, Font Awesome icons, Facebook integration, social networking icons, and more.


custom table view: delete/edit row D7 I've spent hours trying to find good examples or working scripts, but couldn't find anything yet. What I desire to achieve: I have a sortable table with database entries in it, each row has a edit and delete link with each its own ID. So far so good. Now I have to add the functionality to actually delete/edit DB rows. Im totally lost..

Its a custom module and don't want to use other modules to achieve this, so these answers are useless : Help needed for adding and edit & delete link in a column in a view table

I also found this website

but the description is way too complicated and I think the whole script is incomplete.

I've also tried the http://drupal.org/project/examples but that didn't get me any further

does anyone have really good examples or a complete working module?

thanks for your input

So first of all you want a page callback to handle the deleting. You either want to use confirm_form() or add a token to the link to avoid CSRF. node.module does the former, so I'd go with core. You can also use that as a reference: node_menu() (look for $items['node/%node/delete']), node_delete_confirm(), node_delete_confirm_submit().

Regarding the actual deleting, this page has some instructions. Please update the Q if you have specific issues.

Here's an example, not tested:

/**
 * Implements hook_menu().
 */
function MYMODULE_menu() {
  $items['MYMODULE/%/delete'] = array(
    'title' => 'Delete',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('MYMODULE_delete_confirm', 1),
    'access arguments' => array('PERMISSION_TO_CHECK'),
  );

  return $items;
}

/**
 * Form function returning a delete thingy confirmation form.
 */
function MYMODULE_delete_confirm($form, &$form_state, $id) {
  $form['#MYMODULE']['id'] = $id;

  $name = MYMODULE_get_name_from_id($id);

  return confirm_form($form,
    t("Are you sure you want to delete %name?", array('%name' => $name)),
    '<front>',
    t("This action cannot be undone."),
    t("Delete"),
    t("Cancel")
  );
}

/**
 * Submit handler for MYMODULE_delete_confirm.
 */
function MYMODULE_delete_confirm_submit($form, &$form_state) {
  if (isset($form['#MYMODULE']['id'])) {
    $id = $form['#MYMODULE']['id'];
    db_delete('MYMODULE_thingy')
      ->condition('id', $id)
      ->execute();
  }
}

/**
 * Loads the name of the thingy from its id.
 */
function MYMODULE_get_name_from_id($id) {
  return 'thingy ' . $id;
}


How to make custom entity type revisionable with existing content? I'm trying to make a custom entity (with existing data!) revisionable, but I run into multiple very serious issues including schema update errors, difficulties with creating revision data for existing content, and so on...

Has anyone done something similar successfully? Is there a fairly simple way to do it?

Yes, it is highly complicated and there is currently no easy for such a switch.

Upgrade path between revisionable / non-revisionable entities is the core issue to make this easier. You could rely on the patch there but I'm not sure if it is fully working right now.


How do I use Drush correctly to restore a site via the arr command? I am having an issue with the Drush arr command working correctly.  I use drush to backup an archive on a testing server and then move it to a live server, or vice versa when needed.

Here is a typical command I use for restore

drush arr --db-url=mysql://name:pass@localhost/mydb

The database credentials on the test server are different from the live server.  When drush completes the restore process it does so correctly and then says "the database credentials are appended to the bottom of the settings.php file"

That's great, and it indeed appends the correct information about the database, but this never works.

drupal always tries to read the original database configuration that comes before the appended information.

So, I always have to open up an editor, open up the settings.php file, scroll down to the bottom, remove the appended information, then manually go back and change the config information.

This is a huge waste of time.

How do I use this command correctly to avoid that? I want to seamlessly be able to type the command and immediately start using the site without having to manually edit anything.

Also, given that the database config variable is an array, how do I just tell the settings.php file, via drush, to use one or the other? If I have config for a testing environment and a live environment, I simply want to tell it which one to use as needed.

EDIT:

I wanted to add some more information as to the errors I get as well as the settings.php information.

So, immediately after using the command above, this is the error I get on the server I am restoring to:

PDOException: SQLSTATE[28000] [1045] Access denied for user 'root'@'localhost'
(using password: YES) in lock_may_be_available() (line 167 of
/var/www/vhosts/domain.com/httpdocs/includes/lock.inc).

Here is what the settings.php file contains for the original db configuration:

$databases = array (
  'default' =>
  array (
    'default' =>
    array (
      'database' => 'mptest',
      'username' => 'root',
      'password' => 'mypass',
      'host' => 'localhost',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
    ),
  ),
);

Here is what is appended to the end of the settings.php file:

// Appended by drush archive-restore command.

$databases = array (
  'default' =>
  array (
    'default' =>
    array (
      'driver' => 'mysql',
      'username' => 'name',
      'password' => 'pass',
      'port' => '',
      'host' => 'localhost',
      'database' => 'livedb',
    ),
  ),
);

This looks to be the same except that the sequence for the config is different than the original.  Even so, I get the error as stated above. Could the config property sequence be causing this?

settings.php is just an executable php file, so it seems on the surface that there should be no reason for you to do the editing step described above as long as

a) you have not inserted anything in your settings.php file (like a 'return' statement) that halts execution before the end

and

b) the database information that Drush writes at the end of settings.php is the same as the database information you hand-edit into the normal location.

If you are doing the editing information because the database information on your testing server is DIFFERENT than the database information on your production server, then you would be better off using sql-sync to migrate your database from one to the other, and migrate your code with either drush rsync or a version control system such as git.  By default, drush rsync will not transfer your settings.php file, so you can customize it in each location and not have to worry about it being overwritten.  If you use a vcs, you could exclude settings.php e.g. by using a .gitignore file.

Finally, I should add that it is only viable to use sql-sync or archive-dump/restore to move a whole site from testing to production BEFORE you have user generated content. If you ever have users who create accounts, add content, post comments, etc., copying the whole site will overwrite all of that information.  Usually, folks copy the database from live to test only, and copy only code from test to live.  To move configuration, look into the features module, or drush ctools export bonus.

Update: archive-dump / archive-restore does support changing database specs, and seems to be working correctly per your use case described above. Note, however, that you said in your updated text that the two db records are the same, but in fact they have different database names. This, I expect, is as it should be; I further presume that the database info archive-restore is writing to the end of settings.php matches the info you pass in on the command line.


How to include a rule variable (text) in "Set a data value" direct input mode Originally posted this in the Rules issue queue ( http://drupal.org/node/1547160 ) but then saw how few posts from the last 2 weeks had any replies. Scary!

When setting a data value (text) I am unable to include a rule variable (also text) in direct input mode. I was originally trying to do this to build up a large string from fields while looping through a list of nodes. For the sake of understandability I've reduced this to the simplest possible case. The rule export is below and requires Devel module.

Note: I can perform direct assignment of one variable to another using data selection. (Unfortunately that does not satisfy my use case.) It's just direct input mode where I'm failing.

Please can someone tell me whether I should be able to do this and, if so, what I'm doing wrong?

{ "rules_example_text_inclusion" : {
    "LABEL" : "Example text inclusion",
    "PLUGIN" : "reaction rule",
    "REQUIRES" : [ "rules", "devel" ],
    "ON" : [ "node_view" ],
    "DO" : [
      { "variable_add" : {
          "USING" : { "type" : "text", "value" : "*This is the value of text_variable_1*" },
          "PROVIDE" : { "variable_added" : { "text_variable_1" : "Text variable 1" } }
        }
      },
      { "variable_add" : {
          "USING" : {
            "type" : "text",
            "value" : "*This is the initial value of text variable 2*"
          },
          "PROVIDE" : { "variable_added" : { "text_variable_2" : "Text variable 2" } }
        }
      },
      { "data_set" : {
          "data" : [ "text-variable-2" ],
          "value" : "Overwriting the value of text_variable_2:\r\n[text-variable-1]\r\n[text_variable_1]\r\n"
        }
      },
      { "devel_debug" : { "value" : [ "text-variable-2" ] } }
    ]
  }
}

Okay, the answer is: What I was doing wrong was trying to use a feature that did not exist! However, milesw posted a patch on my d.o issue (  http://drupal.org/node/1547160 ) that totally worked for me (woo!) and that I hope will work for you too if you're looking for the same feature.

Edit: If you are looking for this feature please could you try milesw's patch and feed back on it.


Put form labels left of the fields? This is an age-old debate in Drupal, and I am surprised this has not been asked before on Drupal Answers. Maybe I missed it.

By default, Drupal form labels are always displayed at the top of form elements.

How can I display form element labels to the left (or right) of the element, instead of at the top?

I am talking about entity edit forms, but also other forms.

I am sure I will find a solution with hook_form_alter() or on the theme layer. But the question is, what is a convenient and maintainable way to do this?

I am personally working with Bootstrap theme, but a generic answer is preferable, so others can benefit too.

EDIT: It also would be nice to have an elegant way to control which forms this should apply to, and where it should not. Since I added this later, it should be considered optional.

UX background

The main argument for labels at the top is that they are supposedly easier to read. E.g. here, http://www.wunderkraut.com/blog/why-top-aligned-labels-are-better-in-drupal-forms/2010-12-28

I personally think this is an answer to the wrong question. The form labels might be easier to read this way. But if you look at a pre-filled form, e.g. when editing an entity, then usually the field values are far more interesting than the labels. Often the labels are already evident from the field value. E.g. a street name looks like a street name. An email looks like an email.

And of course with labels on the side the form will look more compact and less cluttered, and more of it will fit "above the fold".

Another design option would be in-field labels. But with these, the label is completely gone when the field is filled out. You may still want the labels to make sure that every value is in the correct field.

So having labels on the side is a valid design goal..

As when it comes to theming stuff, you should always ask your self: Can I do this with CSS? The answer in this case is yes.

label { float: left padding-right: 3px; }

Example

OR (probably best to go with)

label { display: inline }
input { display: inline }

Example 2

You will need to add the css code to your administration theme .css file.


How to inject a new variable into a menu template I have a menu with a machine name of menu-principal, which in turn has a theme hook of menu__menu_principal and a template of menu--menu-principal.html.twig. I'm trying to inject another menu into the template in a variable so that I can render it in this menu template but so far have been unsuccessful.

I tried to add a preprocess function to my MY_THEME.theme but this doesn't seem to work. My code is as follows:

/**
 * Implements hook_preprocess_HOOK().
 */
function MYTHEME_preprocess_menu__menu_principal(&$variables) {
  $menu_tree_service = \Drupal::service('menu.link_tree');
  $menu_name = 'menu-quicklinks';
  $menu_parameters = new \Drupal\Core\Menu\MenuTreeParameters();
  $tree = $menu_tree_service->load($menu_name, $menu_parameters);
  $variables['quicklinks'] = $tree;
}

When I go to to the template and use {{ kint() }} to dump out the defined variables, I don't see the variable. I only see the following:

I then found this answer and tried the following, using the example from the answer there:

/**
 * Implements hook_theme_registry_alter().
 */
function MY_THEME_theme_registry_alter(&$theme_registry) {
  $theme_registry['menu__menu_principal']['variables']['quicklinks'] = [];
}

I used dd() to verify that $theme_registry['menu__menu_principal']['variables'] existed and that the variables were definitely being set in the theme registry, but it still didn't work.

I had the same issue, but i was using {{ dump() }} to debug the template

The problem

I have the same arguments when i am using {{ dump() }} inside macro tags. For example:

   {% macro menu_links(items, attributes, menu_level ) %}
       {{ dump() }}
       ... code ...
   {% endmacro %}

If you focus on function menu_links(), you realize that variables are available in your degug trace. So, the macro tags have isolated the bunch of code and variables can't be accessed.

The solution

If you place the debug code outside of macro tags, you can see the variables that has been passed throught a preproccess function. For example:

   # You can see here your variables
   {{ dump() }}

   {% macro menu_links(items, attributes, menu_level ) %}
       ... code ...
   {% endmacro %}

How can you pass variables to macro ?

There are an invocation of menu_links() in template, so you only need to add all the arguments you want to pass them to the macro.

   {{ menus.menu_links(items, attributes, 0, my_custom_argument ) }}

   {% macro menu_links(items, attributes, menu_level, my_custom_argument ) %}
       ... code ...
   {% endmacro %}


How to prevent anonymous users not viewing any webform content I have created a web form contact us page. Anonymous users can see the contact us page at xxx.com/node/add/webform. After they submit the webform, they can see the content of the form at xxx.com/node/x.

In People > Permission page, I have given two permissions to anonymous users:

webform: create new content
View published content

If I uncheck number 2, anonymous users can not view anything. I also went to structure > content types > webform and I did not see anything there to set the permission.I also searched google and I could not find the specific answer.

Do you know how I can prevent anonymous users not viewing the web form published content except adding the webform content?

You'll have to look at the content_access module which will allow you to configure default access control on a per node type or per node basis.

Content Access:

  This module allows you to manage permissions for content types by role and author. It allows you to specifiy custom view, edit and delete permissions for each content type. Optionally you can enable per content access settings, so you can customize the access for each content node.


MetaTag with JSON API won't serialize I'm attempting to get MetaTag info for a decoupled site but the JSON API is not converting the object to JSON correctly. I'm seeing other fields show up fine - the issue is isolated to the MetaTags.

The output appears like this:

field_meta_tags: "a:2:{s:5:"title";s:10:"Test Title";s:11:"description";s:21:"Test Body Description";}",

From what I can tell, s:5 represents an string of 5 characters ("title"), s10 represents 10 characters ("Test Title"), etc etc. Has anyone seen this before?

Drupal 8
Metatag version: '8.x-1.5'
JSON API version: '8.x-1.16'

In fact, the metatag field IS serialized. As stated by Monkeybrain, the result you get as field value is a serialized PHP array.

This is due to the nature of the metatag field, which internally stores its value as a string (serialized PHP array). By using the JSON API module alone, you'll get this value only.

If you need the serialized PHP array to be an unserialized JSON object, you will have to do some custom programming.

Either implement an own REST API endpoint, or - probably easier to do - use the JSON API extras module. It introduces an additional resource field enhancer plugin type to process the values of JSON API entity fields. So you can create an own custom module providing a ResourceFieldEnhancer plugin for the metatags field, which could do your desired unserialization.

Bear in mind, that the value saved within the metatag field(s) does not contain entity defaults. If these are required, you should also use the Metatag module's metatag.manager service to additionally fetch this information.


How to lock a node from a certain role after changing state in workflow? Workflow module lets you set who can change a certain state to what state. What modules can I use to be able to prevent a certain role from editing a node that is in a specific state?

Ex: if a node has been approved and is in Approved state, it should be final and can't be edited anymore by content authors.

For this you should have to implement hook_node_grants and hook_node_access_records. It look something like that -

 /**
  * Implement @hook_node_grants
  */
 function MODULENAME_node_grants($account, $op) {

  $grants =array();
  $grants['Node_Edit_Permission_Content'][]=array($account->uid);
  $grants['Node_Edit_Permission_OtherRole'][]=array($account->uid);
 return $grants;
}

/**
 * Implement @hook_node_access_records
 */
function MODULENAME_node_access_records($node) {

  $grants = array();

  if ($node->type == 'node_type') {
    $user_id_content = /* list of user id which you want to block */;

     // Revoke Permissions from these Users
    if (!empty($user_id_content ) {
      foreach ($user_id_content as $uid) {
        if (isset($uid)) {

          $grants[] = array(
            'realm' => 'Node_Edit_Permission_Content',
            'gid' => $uid,
            'grant_view' => 1,
            'grant_update' => 0,
            'grant_delete' => 0,
            'priority' => 0,
          );
        }
      }
    }

    $user_id_other_role = /* list of user id which you want to block */;

     // Grant Permissions from these Users
    if (!empty($user_id_other_role ) {
      foreach ($user_id_other_role as $uid) {
        if (isset($uid)) {

          $grants[] = array(
            'realm' => 'Node_Edit_Permission_OtherRole',
            'gid' => $uid,
            'grant_view' => 1,
            'grant_update' => 1,
            'grant_delete' => 0,
            'priority' => 0,
          );
        }
      }
    }
  }

  return $grants;
}


Create form via a controller I have a template in which I've manually built a form. It renders some variables that come from a controller.

I've looked over the Form API and I think I should build the form using that. But I'm not quite sure how to go about it.

I'm relatively new to Drupal 8 and to be perfectly honest the Documentation is good, if one knows what to look for. It's not the case here.

Basically what I'm asking, is it possible(or rather advised) to somehow grab the form in the controller, and instead of passing the variables to the template, simply pass the created form to the template?

I'm assuming it would be better to do that, although I'm note quite sure that's the case.

This is definitely possible (and preferable). There are a few ways to do this, but I think the preferred approach is to first specify your form in your routing entry (mymodule.routing.yml)

mymodule.some.route:
  path: '/foo/bar'
  defaults:
    _form: '\Drupal\mymodule\Form\MyForm'
    _title: 'My form title'

The routing system will automatically build your form for you. The class \Drupal\mymodule\Form\MyForm should implement FormInterface. An easy starting point is to extend \Drupal\Core\Form\FormBase.

There are several examples of this in core. For instance, the entity.user.admin and user.admin_permissions routes in users.routing.yml.


How to use tokens in the Completed URL? I need to send data in the URL to the receiving server so that two fields from a survey form is put in the Completed URL string. It looks like it should be possible to use tokens for this, but I can't seem to figure out the correct syntax to use.

I need to send the response to a URL on the form

https://server.tld/sub/value1/value2

where value1 and value2 are fetched from form fields and the rest is static.

According to https://www.drupal.org/project/webform/issues/3021818 this should be possible, if I only could find the correct syntax to use to add the tokens.

Background
The user gets a link to the survey form in a text message. After filling in the form, the Remote Post handler functionality in Webform should post the results to an external server that expects the survey ID and user alias as parts of the URL (for reasons unknown to me, but apparently expensive and difficult to change) for the purposes of knowing when the user has filled in the survey so as to avoid sending out a reminder.

What I have tried
I have tried formatting the Completed URL string in various ways; like for example

http://example.com/%value[my_fieldset][a_value_in_the_form]

and

http://example.com/%value

but I just get a URL invalid error response when I try to save the setting.

I managed to get it going using the standard tokens so in Completed URL I had https://URL/API?query=[webform_submission:values:fieldname] - so just swap out fieldname for the key in the webform you want to pass


Drush: Wrong PHP version when trying to sql-sync with SSH I'm trying to upload a database on the server with SSH by using sql-sync, but I'm getting the following error:

  PHP Parse error: syntax error, unexpected '{' in /home/luken/programs/drush/includes/environment.inc on line 517 X-Powered-By: PHP/4.4.7 Content-type: text/html [...]

As you see from the error message, it is using PHP 4.4.7, while I want to use PHP 5.4.

I tried adding the following line to .bash_profile.

export DRUSH_PHP=php54 (that is php version I wanted to use, and it works when I normally log in)

I also tried with PATH=/home/luken/programs/drush:${PATH}.

What else can I do?

phpinfo() gives this path to PHP: /usr/local/php54/.

Breaking news:

Ok, now I'm totally confused, it appeared that the whole database WAS copied, regardless of error that sql-sync has been producing (suggesting that nothing has been accomplished). I hope that anyone who will get this error will check now if it really didn't do anything, and now the winner will be the one who can explain that O_o.

Check the user that is specified in your Drush alias file.  From the error message above, my guess is that you have configured your alias file to use the web server user, and your web server user is probably not configured to use php-cli -- that's probably why you're getting an old php-cgi instead.  Log in as the web server user (you may need to edit /etc/passwd and change the shell to /bin/bash first), and then configure your path and DRUSH_PHP environments as you describe above.

Alternately, you could use some other user in your Drush alias file.  I like to create a user called 'www-admin', or something similar, and make all of my web files owned by that user.