Webform Status in Webform Submission Twig Template I'd like to use the current open/closed status of a webform in a conditional on the webform-submission-information.html.twig. There is a "webform" variable available to use in the template_preprocess_webform_submission_information function, but all that seems to do is print a link to the webform. When I try to use the usual methods that I'd usually use on a webform object, I just get WSOD. Something tells me that variable isn't actually an object.
For example, perhaps I could get the webform id and use that to figure out the status of the webform...
$form = $vars['webform']['details']['nid']['#value'];

Also, is there a resource for figuring out the pathing to the API is for the Webform? The documentation exists on the Drupal site certainly, but it'd be a lot easier if there was some kind of resource that gave us the path to all these data endpoints. As it stands, even if I figured out the correct function for extracting the webform's ID, I wouldn't have any clue how to find the status (open/closed) endpoint. There are some old d7 articles and issues out there, but it'd be nice if we didn't have to rely on issues and, instead, if there was intuitive documentation.

Indeed, calling {{ webform }} inside webform-submission-information.html.twig only contains a link. But since you have the webform_submission you can get the webform and from there can call isOpen and isClosed.

  {{ 'Current Webform status'|t }}: {{ (webform_submission.getWebform.isOpen) ? 'Open'|t : 'Closed'|t }}

or

  {{ 'Current Webform status'|t }}:
  {% if webform_submission.getWebform.isOpen %}
    {{ 'Open'|t }}
  {% else %}
    {{ 'Closed'|t }}
  {% endif %}


How to remove View/edit option of a node in admin menu? Drupal 7 node edit and view are showing in admin menu. How do I show it under node title?

Actually when the node is loading, the view edit options of the node is showing under the node title but when fully loaded, the view/edit options of that node is showing in the admin menu.
When I checked it with the firebug, it's under admin menu css.

How do I show the view/edit options under the node title?

Go to Configuration -> Administration -> Administration Menu.
Under System Tweaks, uncheck Move local tasks into menu.
Flush the cache and clear browser cache.


Place output of a custom module in a specific region I am using the following code in a custom module to get the title of the node form in the node creation form, i.e, if i add a new content of type BLOG then on top of that node_add_blog form i get a heading/title "Create New BLOG". SO for this i got a custom module from this very forum (kudos). Now i want to know how can i place the output in a specific region, say as the right sidebar.

<?php
/**
 * Implements hook_form_BASE_FORM_ID_alter().
 */

function show_title_form_node_form_alter(&$form, &$form_state, $form_id) {
  // For the node add form.
  //<pre
  //<?php /** print_r($form);*/?>
  //</pre>
  //<?php
  if (!$form['nid']['#value']) {
    // Add "new" to the page title.
    $node_types = node_type_get_names();
    var_dump($node_types[$form['#node']->type]);
    drupal_set_title(t('Create new @type', array('@type' => $node_types[$form['#node']->type])));
   echo "Create"." ".$node_types[$form['#node']->type];
   ;
  }

Regards

If some variable you are looking for isn't available in the scope of your hook, there is a good chance that you are doing it wrong.

Title of the page can be accessed in your theme's page.tpl.php file (or its variants). You can use a hook_preprocess_page() in your template.php file and populate a new variable if the path matches (node add forms have node/add path) so you can put it in the appropriate sidebar in the page.tpl.php.

You cannot control stuff to be shown in the page with a form_alter hook.
For Drupal 7, you could use hook_page_alter() or hook_page_build() to inspect and set sidebar contents.

For an example:

template.php:

function mytheme_preprocess_page (&$variables) {
  if (arg(0) == 'node' && arg(1) == 'add' && arg(2) && isset($vars['page']['content']['system_main']['nid'])) {
    $variables['sidebar_title'] = t('Create new @type', array('@type' => arg(2)))
  }
}

Now, print the sidebar title in your page.tpl.php's appropriate div.

if (isset($sidebar_title)) {
  print $sidebar_title;
}

Drupa.org article: Setting up variables for use in a template (preprocess and process functions)


How to use the Charts module for creating charts using Views? I am using Drupal 6 and trying to setup the Charts module to work with Views.

On the Charts project pages it says

  Views integration: Display the Views results as charts

so views is supported. However I had no luck at all so far. Even though the module seems very well written, it lacks documentation.

My question: How to set this up?

Here's what I used (running a brand new drupal 6.25 install):

Views 6.x-2.16
Views Calc 6.x-1.3 (required for Charts)
Charts 6.x-1.0

The Charts module comes with a few chart providers (SD Image Chart and Google Charts). You need to enable one of them in the module list to use in views. I enabled Google Charts for this example.

Then, I created a new view. I set the Style option to "Chart". To demo the chart, I just added a Node: Nid field and created some dummy nodes. The chart provider you selected will  render the chart in the preview for you. You can configure the Style Plugin settings and the fields to get the kind of chart you want.


Create a user and auto login I use user_save() to create a new user in a custom module. If the function returns TRUE, is it possible to auto login the user?

EDIT

I've done some more searching and found the user_authenticate()

This is the code I have so far:

$user_info = array(
  'name' => $sessdata['username'],
  'pass' => user_password(),
  'mail' => $sessdata['username'],
  'init' => $sessdata['username'],
  'status' => 1,
  'roles' => array(DRUPAL_AUTHENTICATED_RID => TRUE),
                    'access' => time(),
                    );
  $save = user_save($account,$user_info);

  if($save) {
    $loggedin = user_authenticate($save->name, $save->pass);

    if($loggedin) {
      echo "logged in";
    } else {
      echo "damn";
    }
  }

Well it saves the user but it doesn't logins him.

Actually, user_save() returns a user object, not TRUE. If it doesn't return FALSE, then the function was successful and you can use the returned object to log in that user.

For example, supposing that $user is the user object returned from user_save(), you can use the following code to replace the currently logged in user with that user (the code is for Drupal 7).

drupal_save_session(FALSE);
$original_user = $GLOBALS['user'];
$GLOBALS['user'] = $user;

// Do what you need.

$GLOBALS['user'] = $original_user;
drupal_save_session(TRUE);

The code can be used to do some actions impersonating another user, or when a user follows a link reported him in an email, which allows the user to log in. In the latter case, the last two lines should be removed from the code executed.

Without setting the value of $GLOBAL['user'], there isn't any way to let Drupal think a user is logged in.

user_authenticate() is not working because you are not passing the password for that account. In fact, Drupal doesn't save the password in any places; it saves the hash of the password, but that is not what user_authenticate() needs, as reported from its documentation page:

  Parameters

  $name User name to authenticate.

  $password A plain-text password, such as trimmed text from form values.

  Return value

  The user's uid on success, or FALSE on failure to authenticate.

The function passed its $password parameter to user_check_password(), which execute the following code:

  if (substr($account->pass, 0, 2) == 'U$') {
    // This may be an updated password from user_update_7000(). Such hashes
    // have 'U' added as the first character and need an extra md5().
    $stored_hash = substr($account->pass, 1);
    $password = md5($password);
  }
  else {
    $stored_hash = $account->pass;
  }

  $type = substr($stored_hash, 0, 3);
  switch ($type) {
    case '$S$':
      // A normal Drupal 7 password using sha512.
      $hash = _password_crypt('sha512', $password, $stored_hash);
      break;
    case '$H$':
      // phpBB3 uses "$H$" for the same thing as "$P$".
    case '$P$':
      // A phpass password generated using md5.  This is an
      // imported password or from an earlier Drupal version.
      $hash = _password_crypt('md5', $password, $stored_hash);
      break;
    default:
      return FALSE;
  }
  return ($hash && $stored_hash == $hash);

As you see, $account->pass is used as stored hash of the password, while you are passing that value as password.


Changing a dropdown based on another one I've got a content type with a dropdown with some states. And I've got another list (radio buttons) which should change the dropdown based on the selected item. Is that somehow possible?

I've tried Conditional Fields, but that didn't do what I want. Maybe rules? I'm kind of newbie with Drupal.

If you want to do this hardcoded, you might try to use the #ajax property of the Form API

You can reload your second dropdown on change of the value of the first dropdown and change the value while reloading the form.

I made a little example to give you an idea :

$form['number'] = array(
  '#type' => 'select',
  '#title' => t('Select Number'),
  '#options' => array(
      0 => 1,
      1 => 2,
      2 => 3,
  ),
  '#default_value' => 0,
  '#ajax' => array(
    'callback' => 'ajax_replace_dropdown_default_value_callback',
    'wrapper' => 'wrapper-dropdown',
    'method' => 'replace',
    'effect' => 'fade',
  ),
);

$default_value = !empty($form_state['values']['number']) ? $form_state['values']['number'] : 0;

$form['open_closed'] = array(
  '#type' => 'select',
  '#title' => t('Open / Closed ?'),
  '#options' => array(
      0 => t('Open'),
      1 => t('Closed'),
      2 => t('Progress'),
  ),
  '#value' => $default_value,
  '#prefix' => '
',
  '#suffix' => '
',
);

function ajax_replace_dropdown_default_value_callback($form, $form_state) {
  return $form['open_closed'];
}

In your case you will have to do it in a hook_form_alter and add the #ajax property to your first dropdown and add prefix and suffix to give the second dropdown the proper value.

You can also check this link about AJAX with the FORM API :


Add comments to custom node I have a module which shows content with the page callback. Here is my page callback (just the relevent code):

function my_page_callback() {
    $build=array();
    $build[] = array(
        '#theme' => 'my_theme',
        '#marker' => 'foo',
        '#data' => ...,
        '#contextual_links' => ...,
    );
    $comment=comment_node_page_additions(node_load(getTargetNodeId()));
    $build[]=$comment['comment_form'];
    return $build;
}

However the function getTargetNodeId() retuns a valid id of a node which is generated unter some conditions with this code:

$node = new StdClass();
$node->nid=42;
$node->vid=42;
$node->uid=1;
$node->type = 'my_type';
$node->status = 1;
$node->title = "Fresh generated";
$node->content['mapping'] = 4711; // some internal magic
$node->comment='2';
$node->language = LANGUAGE_NONE;
$node->body[$node->language][0]['value'] = "This text should nobody read.";
node_save($node);

Even if in the code above the nid and nid are fixed I take care of it the ids are unique.

And here is my code where I render my node:

function module_node_view_alter(&$build) {
    if($build['#bundle']=='my_type') {
        $p=my_page_callback;
        $build['body']=$p[0];
    }
}

However the the comment header is generated but the input field is missing. What is the problem?

If my_type is a content type defined in the Drupal site, then I would check in admin/structure/types/manage/my_type/comment/fields that you didn't delete the comment body.

If this is what happened then the node page changes from what shown in the following first screenshot to what shown in the second screenshot.

The screenshots has been taken using the user #1 for my test site, which means what shown happens to every user.

The same thing should happen when the content type has been deleted, or it has never existed on the Drupal site.

There could be other reasons:

The only input format available in that site is not accessible from the user who is visiting the page your code is outputting. This is not clearly the case if you are using the user #1 to visit the page.
It also means the site doesn't have the default input format, which is not possible to disable from the user interface. It could be the default input format has been deleted from the database; if this is the case, users would have problems also editing nodes, as the input formats used for comments are the same used for nodes, even if a comment for a node using (for example) full HTML could use plain text, or filtered HTML.
The content type has been created programmatically, in a way that didn't cause hook_node_type_insert() to be invoked. If this is the case, then the Comment module doesn't have the possibility of adding the comment body field, which is done using the following function.

function comment_node_type_insert($info) {
  _comment_body_field_create($info);
}


Theming user-profile I am on Drupal 7. Hi, I have installed the Devel module and I am using it to help me theme the user-profile.tpl.php. I want to show the e-mail information only when the user looking into the user info page is the own user.

I am checking the currently logged in user with $user->uid.

Now I want to get the uid corresponding to the current user page to evaluate if they are the same so that I can print the e-mail. When I go to the Devel  interface, it shows me the information I need on the Load area, when expanding the stdClass information.

How can I use these attributes on the stdClass? I was expecting to do something more or less like $somethinghere->uid to grab the current page user uid, but my trial-and-error process isn't working, I have tried everything... Thanks.

You should be able to get the account of the current page via

$account = menu_get_object('user');

and then check

if ($account->uid == $user->uid)

menu_get_object will grab the loaded object based on the url


How can I add custom fields to Commerce Discounts? We would like to add a long text description and an image to each Commerce Discount which we will display to Users.

How do I do this, since the Discount data structures are not available in the Admin?

You'll need to implement the field api to attach fields to certain entities.  Or you could within hook_entity_info() (I think), there is a 'fieldable' array key you could set to TRUE.  From there, you may need to programmatically add a field to it.  A good way to get field definition code is to use Field Inspector module, add a field to an entity using the UI, and export that field definition as a base to code yours.


How to do views random sort for all the items in a pager? I created five nodes:

Apple
Pear
Kiwi
Orange
Cheese

Then I created a view with the following settings:

Show content of type Fruit
Display 1 item per page, use mini pager
Sort: Global: Random

Now I flip through the nodes one at a time as an authenticated user.
There should be five nodes, but I don't see all 5 nodes in a random order; instead, I see some nodes twice, and other nodes not at all.
Things I tried

In the query settings for the view, I have tried toggling DISTINCT on/off and rebuilding the cache; it appears to have no effect.
I tried setting the views caching to time-based (1 hour), thinking that this would give me all the nodes arranged in a random order that changes each hour, but I still get some nodes twice and others not at all

Is there a way to sort the nodes in a random order and yet still go through the entire set?
Potential problems with random sorting that don't affect this use case

I am only doing this as an authenticated user; core bug affecting caching that breaks random views for anonymous users
I have caching turned off in the view

In your view under filter criteria, use Aggregation settings -> group results together.
This should remove your duplicate results


Adding conditions to the template file of a view I'm setting up a webshop in drupal and I bought a template.

The tempate has a compare products function embedded, that works with a button on the product pages, however, I would only like that button to show up at certain types of products, like TVs and phones etc., but not for the rest.

The compare button, however, is hardcoded into the template file and not manageable from views, so I have to add the conditions to it there, in PHP - to only appear on the node pages of products that have a certain taxonomy term attached to them.

 <div class="actions">
    <?php print flag_create_link('wishlist', $node->nid); ?>
    <?php print flag_create_link('compare', $node->nid); ?>
  </div><!-- .actions -->
</div>

This is the section in the code of the node--product.tpl.php file that puts out the action buttons. I need the second one, the compare button to only appear for nodes that have a certain taxonomy term.

I don't really know php, except for very very basic syntax, so I would be really grateful, if someone could describe in detail how to implement a solution, perhaps even provide a snippet of code that I can customize and paste there!

Thank you in advance!

Huba

To add a variable in template files you first need to create it in your template.php of the theme folder using template_preprocess_node function.

/**
* Implements template_preprocess_node.
*/
function theme_preprocess_node(&$variables){
  foreach($variables['field_taxonomy_field'] as $values){  //field_taxonomy_field is the machine name of the taxonomy term field of your content type.
    if($values['tid'] == $term_id){  //$term_id if the id of the term you want to compare.
      $variables['compare_products'] = l("Compare Button", 'node/compare');
      //@todo your stuff here.
    }
  }
}

This will create a variable named $compare_products which you can use in the template file as a variable.

In node--product.tpl.php you can add <?php print $compare_products; ?> and the data from the variable will be shown whenever the variable is available.


How to link taxonomy term with its content? This is the code below that i am used

$ch=db_query("SELECT th.tid FROM taxonomy_term_hierarchy th
  INNER JOIN taxonomy_term_data td ON th.tid=td.tid
  INNER JOIN field_data_field_books book ON book.field_books_tid = th.tid
  WHERE td.vid = '6' AND th.parent = $tid AND book.entity_id = $nid")->FetchField();

"
Pages
";

$chap = taxonomy_get_children($ch);
foreach($chap as $ca){
  print "
Chapter===>".$ca->name;
}

how I link taxonomy terms using the above code?

In Drupal 7 you can use l()

  $ch = db_query("SELECT th.tid FROM taxonomy_term_hierarchy th
        INNER JOIN taxonomy_term_data td ON th.tid=td.tid
        INNER JOIN field_data_field_books book ON book.field_books_tid = th.tid
        WHERE td.vid = '6' AND th.parent = $tid AND book.entity_id = $nid")->FetchField();

  $chap = taxonomy_get_children($ch);
  foreach ($chap as $ca) {
    print l($ca->name, 'taxonomy/term/' . $ca->tid);
  }


Database error: Lost connection to MySQL server at 'reading initial communication packet' this has driven me crazy, I just couldn't find out what is wrong with it.

I moved my site onto a test directory under my domain '/drupal_test', I have transferred the database over, set up everything properly, and then I got this error:

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

I have set up settings.php like this:

$databases = array (
  'default' =>
  array (
    'default' =>
    array (
      'database' => 'websitedb',
      'username' => 'websitedbnm',
      'password' => 'thepass',
      'host' => 'xxx.xxx.xxx.xxx',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
    ),
  ),
);

I am really sure all the data is right. I can connect to my database through command lines using this account and I can also see all the right tables in this database.

I also tried commenting and editing this line:

$base_url = 'http://www.example.com/drupal_test';  // NO trailing slash!

I still get this error and can't see my site...what could have gone wrong?

To share a bit more detail: the reason for this is generally that your MySQL GRANT is configured as user@localhost.  Therefore, connecting over the external IP address does not match the @localhost portion, and your connection is rejected.  Specifically, because no users in the mysql.user table match the external address in their host column, the connection is rejected immediately.  You can see this by the simple expedient of telneting to the port:

$ telnet example.com 3306
Trying 255.0.0.71...
Connected to example.com.
Escape character is '^]'.
FHost '255.0.0.70' is not allowed to connect to this MySQL serverConnection closed by foreign host.
$

As you can see, before authentication is even attempted, the connection is killed.  If you had a host entry that could have satisfied this request, you would have gotten an authentication failed message, instead.  But in this case, the connection died before authentication was even requested or sent, thus the lost connection at "reading initial communication packet"; the very first packet sent included a disconnection!

To resolve this, either use a hostname value in your databases array for which there will be a corresponding host column entry in the mysql.user table, or add an explicit grant that covers the use case, e.g.:

GRANT ALL ON drupal.* TO 'drupal'@'255.0.0.70' IDENTIFIED BY 'YjbW7dUT';
FLUSH HOSTS; FLUSH PRIVILEGES;

Note that you can also use '%' as a wildcard, as in:

GRANT ALL ON drupal.* TO 'drupal'@'255.0.0.%' IDENTIFIED BY 'YjbW7dUT';

or even:

GRANT ALL ON drupal.* TO 'drupal'@'%' IDENTIFIED BY 'YjbW7dUT';

Don't use this last one unless you have a firewall in front of your MySQL server.  (Which you already have anyway, right?  Right.)

Bonus Section

MySQL treats localhost specially.  Specifically, localhost means to use the UNIX socket, whereas 127.0.0.1 means to use TCP/IP networking.  Therefore, you can run into the strange case where the two are not interchangeable, despite the fact that in every other part of the *NIX world, they are.  This can commonly happen when you have skip-name-resolve specified in your my.cnf; your GRANTs for localhost now don't cover access over TCP/IP, and vice versa.

To fix, either add a localhost GRANT for each 127.0.0.1 one (and vice versa), or change all host columns in the user table to %—which, at the risk of repeating myself from earlier, should only be done if you are behind a firewall in which you are eminently confident.


How to handle free and paid orders with post processing? I'm going around in circles trying to use Drupal Commerce to make an ecommerce site where some orders cost money and some don't (because some users have coupons that make products free).

I've set up the Checkout process as seen in the screenshot below and have created a rule as such

Rules Event: Process checkout pane
Rules Conditions: Price comparison (commerce
order = $0)
Rules Actions:

Change pane properties (disable billing
information, off-site payment redirect, Payment)
Update the order state to (pending/complete)

With this setup when the user goes through without a coupon it all works fine. When the user uses a coupon to get the price to zero on the Checkout page the user presses the Continue to next step button and goes to an empty Review page (the panes have been set to disabled so there is nothing to see) and they can't progress any further.

Pressing the Continue button on that page just bounces them back to the same page. If they press Cancel and go back to the shopping cart, then on through checkout and press "Continue to next step" again (the coupon has been remembered and the total is still $0) then get sent to the Checkout Complete page and hook_commerce_checkout_complete($order) is called.

I've tried adding extra actions to the rule, to complete the checkout or change the order status, but they have strange side effects like going to the Review page anyway, or calling that hook twice.

Can anyone help me set up the checkout and rules so that a free order goes straight to complete from the checkout page, whilst still maintaining the normal path for orders that require payments?

You would be better to implement a custom payment method that can be active when the order has a 0 balance.

If the order has payment required, use the standard payment method.
If the order has no payment required, complete checkout.

e.g: https://drupal.org/project/commerce_no_payment


Views relationship working back from a content type This is a very specific issue with Views Relationships, I essentially want a table view incorporating 3 content types which are linked by an Entity Reference and field collection module. I'm having trouble setting up the relationships so I have drawn a mapped out picture of what it is - and how it should be:

The content types are "Curriculum", "Observation" and "Students". I can accomplish my table layout if I work from the Observation and include relationships, but I'm unsure how to connect the relationships to work backwards from Curriculum. The view should list all the Curriculum node titles (eg ELG 01 through to ELG 16) - this is why I need to work backwards from this content type and not just list ones that are set in the Observations.

An Observation will allow a user to tag a student (entity ref to Students content type) and it allows you to list a "Curriculum Area" and a "Curriculum Level" (these are grouped under the field collection field_curriculum_area_level.

If I was performing the views from an "Observation" perspective it would look like this:

But I need to start by listing all the Node Titles from the "Curriculum Areas" and then list the associated "Observations"

This is how the view looks (though the filter should work from "Curriculum" and not "Observation"

So to recap, I can get a list of "Observations" showing "Students" and "Curriculum" strands that are related, but I can't setup the relationships by starting with a view that starts with "Filter: Content Type: Curriculum Area" - I need to essentially setup relationships to work my way back from these "Curriculum" areas and show the Observation titles and Student Names -- if anyone has any ideas that'll be brilliant.

Cheers,
Garry.

If I have understand your problem, you want display a list of "Curriculum" and inside each "Curriculum" show all observation of this item (like your second screen).

If you aren't blocked by add some module to your project, you can try "views_field_view".

In your View, you create a first display who list all your "Observations" filtred by "Curriculum" nid (like your second screen).

Then, you create a second display who list all your "Curriculum" with a View field who use the first display.


In a View, does the order of pages/blocks/attachments matter? & Why isn't my block showing up? Views 7x3x:
I have two pages & a block in my view in this order:

[Page1] [Page2] [Block1]

Page1: path/%
Page2: path%/%
Block1: (no path)

I have the same contextual filter on all three, Page2 has a second contextual filter. My block is not appearing as expected. I have the block in the proper region without any restrictions in the block configuration.

In the contextual filter for the block, I've set it to hide the view if the value isn't present in the url. In the view preview, arguments produce results as expected. However in the live view, nothing shows up. (I'm providing the same filter arguments in the url)

When I change the contextual filter to display all results when filter value is NOT available, everything works as expected, but this isn't the behavior I want.

What else could be hiding my block/view?
Does the lack of a path for my block mean it can't see the argument?

You likely arent providing the argument to the view in any fashion it can use it. Try not hiding the view but echoing the args to the view title or header and see what you are getting. Please consider using panels module or providing default arguments to your view instead. This works if the arguments are simple like node/user/term id.

If you post more specifics about your actual conditions i can help.


Nested Relationships I have three content types: A, B and C. C references B (one to many) and B references A (one to many). Each content type has a Title field; A also has a Type field.

I want to output the titles of all the nodes from a C node, where Type in an A node is equal to XY. I don't seem to be able to set up relationships in view for B -> A.

Can anyone point me in the right direction?

your question is not clear.I don't understand what you want.
But I think it can help you.
Node relationship


How to get node id in a block_view theme page? I have added blocks to my custom module. A same block should be displayed in two pages. I have to display the field
 $node->field_tag['und']['0']['value'];
in my block.

$nid = explode("/", $_GET['q']);
$node = node_load($nid[1]);

I got the node id by this. When it goes to another url it is not loading.
So how can I get the nid in the block_view theme page without using the url?

You want menu_get_object() to obtain the node object when visiting a node page.


Know a term to get the parent in Views Is there a way to use a taxonomy term name to get all the parent terms in Views?

If the taxonomy terms are the following, is there a way to get "one" and "two," given "three"?

one

two

three

taxonomy_get_parents_all will do what you're looking for, but I don't believe it's possible in views.
http://api.drupal.org/api/drupal/modules--taxonomy--taxonomy.module/function/taxonomy_get_parents_all/6

That being said, there's a module that might help you with that. It's called Taxonomy Views Integrator http://drupal.org/project/tvi


How do I use FAQ module views with accordion effect? I want to use a setup similar to the hard-coded faq-page, having the questions grouped by category, but having the answers hide/show with the accordion effect. I would like to add a jump menu attachment at the top of the page, but this requires setting up anchor links in the original view. I have tried using the various Views displays provided by the module, but these don't have the accordion effect. Is there a magic combination that I'm missing?

Thanks!

If the FAQ module uses views to display the answers, then you can install the Views Accordion module, which creates a new plugin in views to render each result.
Views Accordion:

Views Accordion provides a display style plugin for the Views module.
It will take the results and display them as a JQuery accordion, using the first field as the header for the accordion rows.
For Drupal 7 the module integrates the jQuery UI Accordion plugin as a views style plugin. You can configure the options provided by the jQuery UI plugin.
For Drupal 6 the module used it's own jQuery code, so a different set of features is available for D6.


Redirect from node page after form submission? When editing some fields, after I click the save button, I want the page to redirect to a particular page. Is there any module for this requirement?

Another approach is to simply implement hook_form_alter and put this code into it:

    function MY_THEME_OR_MODULE_form_alter(&$form, &$form_state, $form_id) {
      // dpm($form_id)
      // dpm($form)
      if($form_id == 'article_node_form') {
        $form['actions']['submit']['#submit'][] = 'my_node_form_submit';
      }
    }

    function my_node_form_submit($form, &$form_state) {
      $form_state['redirect'] = 'MY_URL';
    }


Ajax in a form produces an error suppose this form:

function test_ajax_form($form, &$form_state){
  $form['school'] = array(
    '#type'             => 'textfield',
    '#title'            => t('School'),
    '#required'         => True,
    '#ajax' => array(
      'callback' => 'get_formations',
      'wrapper' => 'formationsWrapper',
    ),
  );

  $form['formations'] = array(
    '#type'             => 'select',
    '#title'            => t('Formations'),
    '#required'         => True,
    '#options'           => array(),
    '#prefix'           => '
',
    '#suffix'           => '
',
    //'#access'           => empty($form['values']['formations']['#options']) ? False : True,   );

  return $form;
}

and the callback:

function get_formations($form, &$form_state) {
  $formations = array(
    0 => t('No'),
    1 => t('Yes'),
  );

  $form['formations']['#options'] = $formations;
  return $form['formations'];
}

Everthing works fine, my callback is called and the values populate the select. If I change the school value, then the callback is recalled and I have an error:

  An illegal choice has been detected. Please contact the site
  administrator.

I think it's beacause I try to re-populate the options but I don't know how to fixe.

Any idea ?

You need to do the logic in the form function not the callback. The callback should only return the relevant part of the form. If you add options or change form structure in a callback then you get these illegal choice errors (it's a security feature to stop people from tampering with the forms).

function test_ajax_form($form, &$form_state){
  $form['school'] = array(
    '#type'             => 'textfield',
    '#title'            => t('School'),
    '#required'         => True,
    '#ajax' => array(
      'callback' => 'get_formations',
      'wrapper' => 'formationsWrapper',
    ),
  );

  $form['formations'] = array(
    '#type'             => 'select',
    '#title'            => t('Formations'),
    '#required'         => True,
    '#options'           => array(),
    '#prefix'           => '
',
    '#suffix'           => '
',
    //'#access'           => empty($form['values']['formations']['#options']) ? False : True,   );

  if($form_state['triggering_element']['#name'] == 'school') {
    $formations = array(
      0 => t('No'),
      1 => t('Yes'),
    );

    $form['formations']['#options'] = $formations;
  }

  return $form;
}

And the callback:

function get_formations($form, &$form_state) {
  return $form['formations'];
}


How can I make a link to a node obtained from an SQL query? I'm trying to make a module for a users profile page which shows all of the content of certain types they have created. I have got the query to work and list the results in a block - however I can not get the returned list to contain links to the nodes. Here is my code:

function get_articles()
{
  if(arg(0) == 'user' && is_numeric(arg(1)))
  {
    $account = user_load(arg(1));
  }

  $result = db_query('SELECT node.title FROM {node} node WHERE (( (node.uid = :uid) AND (node.status = \'1\') AND (node.type IN (\'article\')) )) ORDER BY `created` DESC LIMIT 5', array(':uid' => $account->uid));

  if($result->rowCount() > 0)
  {
    $list = array(
      '#theme' => 'links',
      '#links' => array(),
    );

    foreach($result as $record)
    {
      $list['#links'][] = array('title' => $record->title, 'href' => $account->name . '/' . $node->title);
    }

    return drupal_render($list);
  }
  else
  {
    return t('This user has no Articles.');
  }
}

Thank you in advance to anybody who answers.

foreach($result as $record)
{
  $list['#links'][] = array('title' => $record->title, 'href' => $account->name . '/' . $node->title);
}

You have $node->title in this code, but there is no $node object.  The href appears to be the user's name, and then the title of a node?  So the link would be http://example.com/johndoe/My Page Title, which doesn't seem right.

Is this what you're trying to do?  First, add node.nid to your list of SQL columns

foreach($result as $record)
{
  $list['#links'][] = array('title' => $record->title, 'href' => 'node/' . $record->nid);
}

You might also look into bypassing the $list array, and the drupal_render() function, and simply use:

$links = "
";

foreach($result as $record)
{
  $links .= "
" . l($record->title,'node/'.$record->nid) . "
";
}

$links .= "
";

return $links;


How use bulk action (VBO) with table pagination? I have a table result with n pages. I would like to be able to select checkboxes from several different pages of results and then execute a bulk operation. However, when I have selected a checkbox and go to the next page my previous choices are lost. How can I keep my choices saved across page loads?

This is only supported in the Drupal 6 version of VBO (the option is called "Preserve selection across pages" and I think it's enabled by default).
There's an open issue request for the Drupal 7 version: http://drupal.org/node/1207348
This is not a priority for me so I don't see it fixed in the next few months (unless someone else takes the lead).


No results view filtering on newly added field of content type I have a content type called Parts. I just added a new boolean field called is_accessory with the default value being false. I added a filter on an existing view to show only Parts where is_accessory is false. When I run the view, no parts show up.

If I go to a Part page, select edit, then select save (without changing anything) that part will show up.

Do I need to write a hook_update_N function that loads and saves all the Part records?

You can set the views filter operation to Is not equal to and the value as true.

This should work for new entities that have the value as false and old entities where it just isn't set.


Override Profile2 with account fields and values I have created a new Profile Type with Profile2 module. Now I want to override it, importing three existing fields from my original Account (First Name, Last Name, Email) with their own values (that have already been set in the registration process).

I think I must try copying profile2.tpl.php on my theme page, but no changes seems to happen. Any idea about how to do it?

Profile2 modules gives profile entity apart from we have in default as user.I am not putting the codes , but here is my idea,

manually add those three fields to the profile you have created.
loop through all users, load their profile, I guess you can use profile2_load_by_user() to load the profile inside the loop
Check if you are getting the added fields in the loaded profile object.
Map the fields on user entity to profile entity.
save the profile using profile2_save() 5.
Delete the fields from user entity, once you ensure mapping is in the way you want.

NOTE: function listed may need a replacement,as I have not tested the workflow.


Getting Xdebug to work with Dev Desktop I'm trying to get xdebug to work with Dev Desktop.

I am following the instructions in this guide:

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

and I still get the message, "waiting to connect" well after it should have already connected and the site is showing in my browser.

My zend_extension also starts out as:

zend_extension="C:\Program Files (x86)\DevDesktop\php5_5\ext\php_xdebug.dll"

And I'm not sure which version to get off of here:

http://xdebug.org/download.php

I'm somewhat lost - I have no problems getting xdebug to work on OSX or Linux, but I seem to be having real trouble getting it to work on Windows

Well to address your concern about which version to download, if the instructions state Program Files (x86) then you want the 32-bit version of the dll. I'm not sure VC++ 9 or VC++11 should matter. As far as thread safe, you should check phpinfo() in your DevDesktop environment to make sure it's thread safe or not.

The XDebug site has a nifty wizard form where you can copy/paste your phpinfo() into it and it will point you to the version you need.


How to bulk add information to the profiles of users? I have hundreds user profiles where I want to add a one or two fields like the adress of the company they work for. For some group of users this adress will be the same and for others it will be different. How do I mass bulk add these kind of informations? Through the database? (I'm on phpmyadmin)

Step 1

Use the Rules module to create a Rules Component, which includes whatever Rules Conditions you might need (if any), and with a Rules Action to Set a data value, for each of those fields you want to be updated.

Step 2

Create a view of the group of users for which those fields should be added. Then transform that view into a view that uses Views Bulk Operations, and use the technique documented in "How to use Rules to create a custom bulk operation for a VBO view?". In doing so, you'll then be able to use the Rules Component from Step 1.

Tutorial

To get the idea, have a look at the video about Using Rules components with VBO" which uses a Rules Component with (only) 1 parameter. If you want even more, then also watch the subsequent "Using Rules components with more than one parameter" video.

Attention: to process like 100.000 entities at once is quite a challenge (memory requirements, etc). Therefor you might want to also watch the video about "More details about VBO settings" ... Before you are tempted to use VBO for processing them all at once ...

PS: this answer is for D7 ...


How to customize the subject of a Commerce order confirmation e-mail? Here you can learn how to customize the content of the order confirmation mail, but what about customize the subject of the mail?

In a custom module you can try something like:

/**
 * Implements hook_mail_alter().
 */
function mymodule_mail_alter(array &$message) {
  // Order receipt.
  if ($message['id'] === 'commerce_order_receipt') {
    /** @var \Drupal\commerce_order\Entity\OrderInterface $order */
    $order = $message['params']['order'];

    // Change the email subject.
    // @todo Remove this if/when it becomes configurable.
    //   https://www.drupal.org/project/commerce/issues/2924159
    $message['subject'] = t('Some other email subject #@number', [
      '@number' => $order->getOrderNumber(),
    ]);
  }
}


Security update for patched module Is it necessary to re-patch an existing patched module when doing a security update for that module?  I am not interested in keeping it patched. Or will this potentially break something?

Most likely you will need to repatch the module, if you doing it manually.

If are using composer to manage your drupal set up, you can use "cweagans/composer-patches", and this composer plugin it will reapply the patch for you automatically and let you know if the patch will no longer work on the newer version of the module.

This is a big time saver.


No administrative CSS for arabic language I have a multilingual website with English, French, and Arabic; I updated from Drupal 7.22 to 7.23 and I found that I don't have the CSS for the homepage in Arabic, as the image below.

Why is it happening? How can I fix this?

Notes

I'm aggregating and using Advanced CSS/JS Aggregation advagg.  I'm using Boost module.

By default, many themes have a separate RTL template or CSS. Depending on what theme you are using, you may have to create RTL CSS or change the behavior of which CSS files it's looking for. Try searching for a *-rtl.css file (where * is some name that comes before the suffix.)


Webform custom Options file location My question is; When you create a custom option list in Webforms, where or how does the list get stored?

Explanation:
In the Webforms Module (8.x-5.0-rc13) you have the ability to create custom options lists. The Options configuration page lists reusable predefined options/values available for select menus, radio buttons, checkboxes and Likert elements. (example: gender, sizes). The option lists that are included when the module is installed can be found as a yml files in docroot>>modules>>webform>>config>>install. After creating a custom option list I can not find the files anywhere or find a table in the database with the vales.

WHY?
I have a list of 500 colleges that I want to populate a select list with different option values option text. pasting the list would be much easier and faster than using the interface to create the list.

I tried using a term select but cannot figure out how to define the value. I can only define the display text in the terms.

Sample yml code customized from one of the predefined option lists:

langcode: en
status: true
dependencies:
  enforced:
    module:
      - webform
id: my_colleges
label: US Colleges
category: Demographic
likert: false
options: |
  361623: ALASKA PACIFIC UNIVERSITY
  362001: ANCHORAGE COMMUNITY COLLEGE
  362503: UNIVERSITY ALASKA
  362814: SHELDON JACKSON COLLEGE
  363495: UNIVERSITY ALASKA

Webform options are config entities. You can export and import then via /admin/config/development/configuration.

You can also just bulk edit the options YAML. (/admin/structure/webform/config/options/manage/time_zones/source)

Or you can use hook_webform_options_alter() or hook_webform_options_WEBFORM_OPTIONS_ID_alter() to dynamic populate options from database or web service.


Using compass in Aegir limited shell (user o1.ftp) I installed the latest BOA-stable and after it RVM with Compass and SASS. According to the changelogs of BOA-2.0.4, I should be able to use Compass commands:

  Fixes:

  Allow all standard compass/sass commands in limited shell.

As root, I am able to execute 'compass watch', but I am not with the limited shell (as user o1.ftp). It says:

sh: 1: compass: not found

For me it didn't work in combination with RVM. I needed to install it the normal way:

- apt-get install ruby
- apt-get install rubygems
- gem update --system
- gem install compass

I think that because of the isolated gem installs that RVM creates, the limited shell user has no access to the commands.


How to programmatically add / remove a value for an unlimited multivalue field? I was looking at http://php.net/manual/en/function.array-push.php but it seems one cannot use it as multi value fields are associate arrays. Any built in functions perhaps?
Here is an example array

$myfield["und"][0]["value"] = 23424;
$myfield["und"][1]["value"] = 76786;

You can use the entity_metadata_wrapper() function with entities (you'll find good examples here); it makes things a bit cleaner, but not that much.

Other than that, no - you're stuck using vanilla PHP for this, Drupal doesn't have any built in functions to help.

There's no reason you can't use array_push as normal though:

array_push($myfield[LANGUAGE_NONE], array('value' => 23424));

Although that's actually more verbose and less readable than the original.


Maintenance mode and user session When I put site in maintenance mode and after turn site back all users sessions are not active (is need to log in account), but I put session to work 2 month and it work.

How to prevent users logout when put site in maintenance?

This is intended behavior, if user does not have "access site in maintenance mode" permission, then user is logged out.

For Drupal 7 take look on user_menu_site_status_alter

For Drupal 8 take look on Drupal\user\EventSubscriber\MaintenanceModeSubscriber


Can I import "id" into "uid"? I'm trying to import over 5000 users into drupal by using Feeds module. Can I import user "id" into "uid"? If so, how can I do that? I saw the GUID mapping target, but that is not "uid". Thanks.

The user ID field on Drupal is auto-incremented, so you don't want to import your ID values into that field. It's much better to add an original_id field to retain the legacy user IDs.


How do I increase the length of a text-field with saved values? I have a multi-value text-field, projects. Its length is 4, and I would like to increase it to 255, but there are values saved in the database for that field.

How can I increase its length?

I got an answer from my friend as well. I would like to share his code here:

/**
 * Update field.
 */
function MODULE_update_8301() {
  $db = \Drupal::database();
  $field_name = 'field_MY_TEXT_FIELD';
  $table_prefixes = [
    'node',
    'node_revision'
  ];
  foreach ($table_prefixes as $table_prefix) {
    $db->schema()->changeField(
      "{$table_prefix}__{$field_name}",
      "{$field_name}_value",
      "{$field_name}_value",
      [
        'type' => 'varchar',
        'length' => 255,
        'default' => '',
      ]
    );
  }

  $config = \Drupal::configFactory()->getEditable('field.storage.node.' . $field_name);
  $settings = $config->get('settings');
  $settings['max_length'] = 255;
  $config->set('settings', $settings);
  $config->save();
}


Adding class to the webform submit button By default, the web form is displayed with <?php print drupal_render($form['submitted']); ?> .

I need to make a small edit and add class="btn" to the submit button.

I can change its value with $form['actions']['submit']['#value'] = "click to become a member";

But I couldnt find a way to add the class.

Please help!

Thank you

I think that you have to do something like this (add an array):

$form['actions']['submit']['#value'] = "click to become a member", array('attributes' => array('class' => array('btn'), 'style' => array('CUSTOM STYLE DIRECTLY') ));

I'm not really sure if is there is the right place the you have to add that code, but that generally it's this code:

, array('attributes' => array('class' => array('btn'), 'style' => array('CUSTOM STYLE DIRECTLY') ))


How to disable a module and its dependents modules with Drush? Is there any way to disable a module and its dependents modules with Drush.

Let's say I need to disable views but I have enable views_accordion as well.

If I run $ drush pm-disable views I don't get the views module disable.

You should update your drush by the sounds of things. Doing drush dis views should result in the following:

drush dis views
The following extensions will be disabled: views, views_bulk_operations, og_ui, views_content, og_example, views_php, views_ui
Do you really want to continue? (y/n)

Which means the dependents are disabled at the same time.


When should "'target' => 'slave'" be used in a query? Looking at Drupal code, I notice that sometimes a query is being executed using array('target' => 'slave') as options, and I don't understand in which case that should be done.

I thought it was done when query where executed in parallel to others, but then I thought that could be said for almost any query executed by Drupal, when more than one user is looking at the pages of a site.
In which cases should array('target' => 'slave') be used?

  // node_update_index()
  $result = db_query_range("SELECT n.nid FROM {node} n LEFT JOIN {search_dataset} d ON d.type = 'node' AND d.sid = n.nid WHERE d.sid IS NULL OR d.reindex <> 0 ORDER BY d.reindex ASC, n.nid ASC", 0, $limit, array(), array('target' => 'slave'));

// search_index()
$node = db_query('SELECT title, nid, vid FROM {node} WHERE nid = :nid', array(':nid' => $linknid), array('target' => 'slave'))->fetchObject();

Also, looking at Drupal core code, why is array('target' => 'slave') sometimes used, and sometimes no?

SELECT (read) queries can go to the slave, other such as UPDATE and DELETE (write) queries should go to master then propagate across to the slave database.

  Also, looking at Drupal core code, why is array('target' => 'slave') sometimes used, and sometimes no?

That's probably just historical / legacy reasons due to the nature of how the Drupal code base is gradually committed. Potentially any SELECT queries could target the slave database.


How to link 1000 parked domains to nodes, each with node title corresponding to the domain name I want to build a drupal site in D7 that can host thousands of parked domains as landing home pages. The purpose is to create a system for a domain broker to host many parked domains, each with its own sales page on its parked domain root.

The domain access module serves similar purpose but my experience is that it works for up to 10 domains, after that there are serious usability and performance issues arising.

So I'm looking for a simple alternative. What I need is only one page per domain, with the domain as title (example.com) and a contact form that potential buyers of the domain can use.

Assumption: the 1000 domains have been parked on the drupal installation domain.

If I create 1000 nodes hwith corresponding titles (example.com) how do I make each node the homepage of each parked domain? Maybe using .htaccess rewrites, but Im not good at that. The parked domain must stay as browser address when redirected.

Alternative might be to create one custom panel page and use tokens to use the domain URL in the title and the sales text and contact form. The contact form is just a standard contact form that sends an email to the site administrator.

I'm assuming you have a field on your nodes with the name field_domain.

On your website:

Create a new node. This will be a place holder.
Get the NID.
a) Go go /admin/content/
b) Click edit on this placeholder node
c) Check the url. It will be in the form:
       /node/<NID>/edit
      Get that NID.
Go to your theme.
On the templates folder, create a file with the name:
node--NID.tpl.php so something like: node--78.tpl.php
On this file, put the following content:

  &lt?php
    $query = new EntityFieldQuery();

    $query->entityCondition('entity_type', 'node')
      ->entityCondition('bundle', 'article')
      ->propertyCondition('status', 1) // published
      ->fieldCondition('field_domain', 'value',  $_SERVER['SERVER_NAME'], '=');
    $result = $query->execute();

    $nid = array_keys($result['node'])[0];
    if($nid) {
      $nodeObj = node_load($nid);
      $nodeRndr = node_view($nodeObj);
      print(drupal_render($nodeRndr));
    }

    You need to update 2 things:

       article to the machine name of the content type you're using.
       field_domain to the machine name of the field you're using.

Now, go to admin/config/system/site-information
Change the front page to node/NID where NID is the value from #4.

Explanation:

What that code does is checks $_SERVER['SERVER_NAME']. This should be the domain that's being used. Using that, it looks to see if there's a node with the field field_domain that has a value that matches $_SERVER['SERVER_NAME'].

If there's a match, it will load the node and render it.

If not, it should still load the placeholder node you created. This could be your default home page.

Hope this helps.

Original comment:

Have you considered writing some custom code?

If the only thing different is the title. I would create a small module that:

On installation creates a table with a domain and a title column.
When a page loads, reads the table and matches the domain and selects the title.
With the title, on... hook_preprocess_page (probably) you can set the title

I think there's a bit more functionality you want. If you're acting like a broker or if it's only a single owner, you probably are sending an email. So you would need the domain that was visited in the form as a minimum.

You can do this by having a hidden field and setting the value on load as well.

Or when submitting the form, reading it and processing it.

If it's more like a marketplace and you're sending an email to the owner which would vary per domain.

I think that processing that after the fact and only having one form would probably be more efficient than having a form per domain.

It depends on the use case. Just offering another option.


How to compare values from two views I have two views, "viewA" and "viewB;" "viewA" contains all the users that post within the day, and "viewB" contains all the users. I need to get the difference between the two so I can get the users that don't have any post. I could use views_get_view_result() and views_get_current_view(), but I don't know how to implement the code.

Instead of trying to compare the result of two views and find the difference, which is highly inefficient and difficult, it will be a lot easier to create a new view that filters out the users that that has posted within a day.

You should be able to duplicate ViewA and reverse it's filter(s). It should at least provide a good starting point.


User being logged out of drupal when using form redirect Looking at my logs I have an issue. I have not been able to recreate it myself.

I have a form which an anonymous user fills out. This form takes an email address. When submitting the form I take that email address and either log the user in or create an account and log the user in.

This code is working fine. As I have several watchdog() calls going in as the user who has been logged in.

The code then creates an order in Drupal commerce (with the user account above). I have a valid orderid created with the above user.

I then have:

watchdog('MyMod', t("Logged in as user));
drupal_goto('checkout/' . $orderid . '/review');

The watchdog() goes in as the user. When I hit checkout/????/review I then get an access denied for an Anonymous user.

This is only happening some of the time. As I said I have not been able to reproduce. What could be causing the drupal_goto() to log my user out.

Update

I now use

watchdog('MyMod', t("Insert in ref table complete"));
$formstate['redirect'] = 'checkout/' . $orderid . '/review';

To redirect my user however I am still getting the same issue.

Update 2

With some code.

Log out user

function _mymod_logout_user() {
  global $user;
  if ($user->uid > 1) {
    module_invoke_all('user_logout', $user);
    session_destroy();
  }
}

Create User

function _mymod_create_user($mail) {
  global $user;
  _mymod_logout_user();
  if ($user->uid != 0) {
    return $user;
  }

  $account = user_load_by_mail($mail);

  if ($account == FALSE) {

    $password = 'random12!££SsjsjaJAAJA3'; //made up

    //set up the user fields
    $fields = array(
      'name' => $mail,
      'mail' => $mail,
      'pass' => $password,
      'status' => 1,
      'init' => 'email address',
      'roles' => array(
        DRUPAL_AUTHENTICATED_RID => 'authenticated user',
      ),
    );

    $account = user_save('', $fields);
  }

  // If the user is 1 then we want to return false as they will be logged in as admin
  if ($account->uid == 1) {
    return FALSE;
  }

  $form_state = array();
  $form_state['uid'] = $account->uid;
  user_login_submit(array(), $form_state);

  return $account;
}

Create Order

function _mymod_create_order($sku, $mail) {
  global $user;
  $user = _mymod_create_user($mail);

  // User is trying to create an account under user 1 so return nothing.
  // can only do this if logged in a user 1 not anon
  if ($user == FALSE) {
    return;
  }
  $uid = $user->uid;

  $order = commerce_order_new($uid, 'checkout_review');
  $product = commerce_product_load_by_sku($sku);
  $line_item = commerce_product_line_item_new($product, 1, $order->order_id, array());
  commerce_line_item_save($line_item);

  $order_wrapper = entity_metadata_wrapper('commerce_order', $order);
  $order_wrapper->commerce_line_items[] = $line_item;
  commerce_order_save($order);
  return $order->order_id;
}

Insert into custom table

function _mymod_insert_ref_table($orderid, $ref) {
  db_insert('mymod_reference_table')
    ->fields(array(
      'orderid' => $orderid,
      'ref' => $ref,
    ))
    ->execute();
}

Form submit function

function mymod_form_submit($form, &$formstate) {
  global $conf;

  $sku = //Code that generates a SKU;

  $orderid = _mymod_create_order($sku, $form['email']['#value']); //email has all ready been validated by drupal

  $ref = // Call to WS that returns a reference number
  _mymod_insert_ref_table($orderid, $ref);
  watchdog('My Mod', t("Insert in ref table complete")); // This watchdog message goes in as the logged in user!
  $formstate['redirect'] = 'checkout/' . $orderid . '/review';  // When I reach this page I am logged out sometimes...

}

You should better use $form['redirect'] within a form rather than drupal_goto().

  If you use drupal_goto() you will short cut the form processing skipping any other form_submission functions that have attached themselves to the form. Thus, if you use path_auto and do a drupal_goto while processing a node form, a nice path will not be added to your node because the drupal_goto() was executed before pathauto's node submission handler was called.

Source

This was before the original post was edited. Regarding the logout issue, let us review your procedure.

So essentially: when a form is submitted, mymod_form_submit() calls _mymod_create_order(), which calls _mymod_create_user(), which in turn calls _mymod_logout_user(). All of them unconditionally so far.

If not user 1, you will logout the user and then back in _mymod_create_user() you will attempt to create if necessary and then log the user in.

When you attempt to login the user via user_login_submit(), Drupal will call drupal_session_regenerate(). There, in an attempt to prevent several nasty security possibilities such as session fixation, will generate a new session ID. I suspect the trouble is somewhere there, depending on what exactly happens in the code that displays the redirection page "checkout/...".

In order to deal with this issue I would recommend you to adopt the procedure that other modules use to deal with the possibility that an anonymous user needs to login / be created. Ubercart and Drupal Commerce certainly deal with that. Personally I would suggest to take a look at Ubercart file "uc_cart/uc_cart.pages.inc", function uc_cart_checkout()


Coming from Drupal 7, which files should I be versioning with git in Drupal 8 projects? So, having read through:

What are all the directories for in the new Drupal 8 structure?
https://drupal.stackexchange.com/questions/126660/how-do-the-seasoned-oo-php-people-go-about-setting-up-a-professional-development?rq=1
Cloning site and $config_directories
https://www.drupal.org/node/2360331 (especially #19 and #20)

... I'm still not sure what is best way to go when setting up a D8 project with git.

modules and themes

Apparently, the contributed/ custom modules and themes folders have moved from D7:

/sites/all/modules
/sites/all/themes

to:

/modules
/themes

in D8. When I copy modules to /sites/all/modules D8 does recognize them. But when I add modules via Admin UI, they get downloaded to /modules So, which folder to git? Is it generally bad practice now to go for sites/all?

Formerly, we had this file and git structure (D7):

/
↳ www.example.com
  ↳ sites
    ↳ all -> /repo/repo.git/all
↳ repo
  ↳ repo.git
    ↳ all

Now, I imagine it way more complex:

/
↳ www.example.com
  ↳ modules -> /repo/repo.git/modules
  ↳ themes -> /repo/repo.git/themes
↳ repo
  ↳ repo.git
    ↳ modules
    ↳ themes

just for the modules and themes.

This leads me to the question: what about sites/default/files/conf*?

I understand that this folder is being used for the configuration files, but:

is it right that my local dev environment and the staging/ prod environments have their very own folder?
is the usage of configuration files necessary when we only tend to have one "real", always up-to-date main database (prod/live)?
should the conf be tracked and deployed with git? Why?

Thanks a lot!

Drupal comes with an example .gitignore file, just rename "example.gitignore" to .gitignore and you have a pretty good starting point. It also comes with a lot of explanations.

Many of your questions go way beyond just answering that should be added to get, there are also some different opinions.

Yes, put your modules in /modules and so on, it's a lot easier to work with.
Whether or not to commit /vendor depends on your deployment process. if you deploy your git repository directly and have no intermediate deployment process, you probably still want to commit the vendor directory. There are various alternatives, starting from just building an archive yourself and deployment that, to automating that with scripts/build tools to using solutions like platform.sh that run composer install automatically for you. If you use any of those, you likely want to ignore vendor as the example .gitignore file does by default.
It's also common practice to have a settings.local.php and add settings.php to git, see instructions in settings.php at the end.
I don't understand your repo.git and repo folder examples. It's not more complex than in Drupal 7, just different folders.
Yes, you probably want to move your config folder out of files (you need to update the path in settings.php) and commit it. You shouldn't only have one environment, and config allows you to make changes on one site, export it and import it on production. There are many questions here and documentations about this available.


Why are cache queries so slow? I noticed that some of the queries to retrieve data from cache tables is really slow (> 100ms). For example:

SELECT cid, data, created, expire, serialized FROM cache_views WHERE cid IN ('views_data:en')

SELECT cid, data, created, expire, serialized FROM cache_field WHERE cid IN ('field_info_fields')

SELECT cid, data, created, expire, serialized FROM cache_bootstrap WHERE cid IN ('system_list')

SELECT cid, data, created, expire, serialized FROM cache WHERE cid IN ('entity_info:en')

Most of those tables only have 10-100 records total. Why would they be so slow?

I don't know this for a fact but I think it's because the serialised objects contained in the data column are pretty large.

I just checked a production site of mine and the data column for views_data:en contains a serialised string that is 572824 characters long. I kid you not! Imagine loading that on each page request (fortunately that doesn't happen in my case).

The main cache table on the same website is currently at 1.4MB, with just 16 records in it.

On another, less-than-a-week-old dev site, the cache_form table is at 6.3MB, with just 142 records.

I know 1.4MB and 6.3MB aren't large amounts of data as such, but if you take into account the fact that it has to be processed and passed from MySQL to PHP I think that's where you'll find the bottleneck.


Trigger context by filter value? I need to essentially trigger a context when a certain filter value is selected.  Basically, in a view, when a filter is selected, based on the value selected I need to display a certain block.

Does anything like this exist?  Or am I going to have to build my own extension to Context?

With Drupal there are so many way to do things - here is one way to achieve what you need:

Go to admin/blocks and add your block to the region you want it to show up in, then set it to display on only the page for that view
In your theme css hide that block (display:none)
Add some javascript to display the block and bind it to the onchange event for the value you want, either add the js in your module or your theme.

I have not gone into specifics as each step can have variations on how you would like to implement them, but the above is one potential solution to the problem

Using context could work if you submit the view filter to a different path and then set a context to show the block on that path, but if you wnat to do it via an onChange its easier using Js & Css.

Modules that may also help:

http://drupal.org/project/views_hacks
http://drupal.org/project/views_dependent_filters


Drupal Ajax breaks after one fire This is a very frustrating and recurring problem for me because it seems to come and go at random, one minute it is working beautifully, the next moment I make a change and it breaks.  Even if I change everything back the way it was and clear the cache again it is still broken.

I have a form, in the form is a table that allows users to enter ingredients into the form.  There is a "More ingredients" button.  Once clicked an AJAX call is made and the form is rebuilt and a new row is appended to the table.  For some reason This "More ingredients" button has been broken.  On click, it adds one ingredient, then on the second click, nothing.  The button will not even trigger the receding animation as it does other buttons, it is as if the button has just disapeared...

Here is the code.

relevant form function

 if (isset($form_state['add_ingredients'])) {

//reset add ingredients under form_state
unset($form_state['add_ingredients']);

//Get number of added ingredient for proper naming below.  Allows us to use row theme instead of table theme for loading only an ingredient.
$ing_number = count($node->recipe_ingredients['ing']);

//Be sure ajax returns proper row number.
$form_state['ing_number'] = $ing_number;

//Add ingredient to our ingredients array.
array_push($node->recipe_ingredients['ing'], array('ri_id' => NULL, 'name' => '', 'quantity' => '', 'unit_key' => '',  'note' => '', 'weight' => $max_weight + 1));

//Theme this row only, uses $ing_number to designate it will only be themed by row theme function, not table.
$form['recipe_ingredients']['ing'][$ing_number] = array(
    '#theme' => 'ingredients_row',
    '#row_number' => $ing_number
    );

$form['recipe_ingredients']['ing']['1'][]
. . .

$form['recipe_ingredients']['recipe_more_ingredients'] = array(
'#type' => 'submit',
'#name' => 'ingredientadd',
'#value' => t('More ingredients'),
'#description' => t("If the amount of boxes above isn't enough, click here to add more ingredients."),
'#weight' => 1,
'#submit' => array('recipe_more_ingredients_submit'),
'#limit_validation_errors' => array(),
'#ajax' => array(
  'callback' => 'recipe_more_ingredients_js',
  'wrapper' => 'ingredient-list',
  'effect' => 'fade',
  'method' => 'append'
  )
);

Submit

function recipe_more_ingredients_submit($form, &$form_state) {
//Set Drupal's form rebuild option to true...  not sure if this is really needed...
$form_state['rebuild'] = TRUE;

// If they clicked the more ingredients button, flag it in form_state['add_ingredients']
  if ($form_state['values']['recipe_ingredients']['recipe_more_ingredients']) {
   $form_state['add_ingredients'] = TRUE;
  }

}

Ajax Callback

function recipe_more_ingredients_js($form, &$form_state) {

return $form['recipe_ingredients']['ing'][$form_state['ing_number']];

}

Row theming function

function theme_ingredients_row($variables) {

$form = $variables['form'];

$row_number = $form['#row_number'];

// Build the table row.
$row = array(
    'data' => array(
    drupal_render($form['ri_id']) . drupal_render($form['quantity']),
    )
  );
  $row['data'][] = drupal_render($form['unit_key']);
  $row['data'][] = drupal_render($form['name']);
  $row['data'][] = drupal_render($form['note']);
  $row['data'][] =  '<button class="ing-remove" type="button">Remove</button>';

//Start HTML of row
$output = '
';

//Wrap each cell in proper HTML tags
foreach ($row['data'] as $key => $value) {

    $output .= '' . $value . '	';

}

$output .= '
';

watchdog('ROW', $output, null, $severity = WATCHDOG_NOTICE);

return $output;

}

Sadly that still doesn't work...  The problem is not that php, it calls the website only the first time.  The second time the button is broken.  It does not click, call Drupal or anything.  Also any buttons added to page with ajax do not work either, even though their pre-loaded counterparts work perfectly fine with jquery.


How to log and display all the users that have edited a node (without revisioning)? We need to keep the usernames of the latest editors of content, along with the edit date.

How can we do so? Or should we use custom code?

We do not want to enable revisioning, as it is more complex than we want.

The Activity module does some user activity logging that may covert your need.

  The Activity module keeps track of the things people do on your site
  and provides mini-feeds of these activities in blocks, in a
  specialized table, and via RSS. The module is extensible so that any
  other module can integrate with it. The messages that are produced are
  customizable via the admin interface and are context sensitive. Some
  theoretical example messages include:

  You wrote a comment in response to "example comment title"
  Jim wants to be your friend. Approve this friendship here
  Nancy is Phil's latest fan


Automated Drupal issue queue workflow Working in the issue queue on any busy project can be quite a bit of work.

Lots of files (patches) to manage, interdiffs, and ideally a branch for piece of work, moving patches forward with rebase etc.

What (if any) automated workflows are there to ease these tasks? This could either be code, such as some form of git wrapper, or perhaps just an explanation of how to use existing tools.

As well as drush_iq, you might consider patch manager.


Insert values into custom field's extra columns in database I'm new to drupal 7.

I've create a custom field with extra columns via field api, and create the field well(via UI), but I can't "save" it while using the field.

I've google for it and found some keywords like

hook_field_storage_write()、hook_field_attach_submit()

But still can't get what I want.
Can someone give me advices?

Can you provide more details how did you implement schema, widget, formatter etc.
I guess this link can be helpful for you http://www.slideshare.net/zugec/fields-in-core-how-to-create-a-custom-field


Views Slideshow with numbered navigation disappears So a little background on my current setup. The views slideshow having issues is on the homepage:
http://pacificwhale.org

I am running Drupal 6, and using Views slideshow 2.4 with nodequeue to feed 6 nodes that are of the photo content type. The slideshow that I am working closely with sits on the homepage of my website. Sometimes it works, sometimes it doesn't. When it stops working, the numbered navigation disappears from the page, and in the source code, I'm noticing that the jQuery.extend function call in the html page header is missing this code:

  "viewsSlideshowSingleFrame": {
  "#views_slideshow_singleframe_main_nodequeue_1-block": { "num_divs":
  6, "id_prefix": "#views_slideshow_singleframe_main_", "div_prefix":
  "#views_slideshow_singleframe_div_", "vss_id": "nodequeue_1-block",
  "timeout": 5000, "sort": 1, "effect": "fade", "speed": 700,
  "start_paused": 0, "delay": 0, "fixed_height": 1, "random": 0,
  "pause": 2, "pause_on_click": 0, "pause_when_hidden": 0,
  "pause_when_hidden_type": "full", "amount_allowed_visible": "",
  "remember_slide": 0, "remember_slide_days": 1, "controls": 0,
  "items_per_slide": 1, "pager": 2, "pager_type": "Numbered",
  "pager_hover": 1, "pager_click_to_page": 0, "image_count": 0,
  "nowrap": 0, "sync": 1, "advanced": "", "ie": { "cleartype": "true",
  "cleartypenobg": "false" } } } });

To view the html for the slideshow you can do a view source from our homepage.

To make the numbered navigation work, I must from the admin area of drupal6 perform a "flush all caches" from a page other than the homepage. After doing this, if I navigate to the homepage while logged into the admin area, the slideshow will not work, and there will be no numbered navigation. However, if I log out of the admin area and then navigate to the homepage and view the slideshow, I notice that the numbers are working and the slideshow automatically rotates through my images.

An interesting oddity, is that if I am logged into the admin area and I perform a "flush all caches" from the homepage, then the slideshow will display navigation and work inside the admin area, but if I log out of the admin area, it will not display the numbered menu, and for me or any other viewer of the website the slideshow is broken with no navigation, and the jQuery.extend function is missing the viewsSlideshowSingleFrame variable settings.

Another interesting oddity is that the slideshow navigation once fixed by flush all caches, later on it will revert back to not working, and I must go through the steps again to get it to work, and I'm in a hopeless cycle to get it to work again.

I've attached a screen capture of my views setting for nodequeue_1. You'll notice that I've turned off caching for this view/nodequeue, so I don't understand why flushing all caches makes a difference in fixing the slideshow navigation.

Hi I don't normally post replies but I had a similar issue to you where my Carousel module with slide show stopped working in December 2013

Only when logged in as admin would I see the correct view

I was sure this has stopped about the time i updated some modules

After a bit of trial an error I noticed that the upgrade from 1.3 on 1.4 on Responsive Menus Module caused the issue

By using a 1.3 module the problem went away

Check which version you are using under 'Modules' and 'USER INTERFACE' section of administrator menu


Does Drupal Disqus Commenting have a Server Side rending for SEO indexing? Having to outsource the commenting service to disqus saves alot of time, but is there a way to have these Disqus comments rendered on the server side before displaying it to the end user? My main concern is for SEO indexing. What solutions are there to keep the SEO indexing in tact when using Disqus commenting?

Disqus itself does support this (see this post for example) but I do not believe that the Disqus Drupal module supports this. It would probably be a worthwhile contribution to that module (or perhaps a companion module).


search form at admin/content I try to administrate a lot of content in Drupal 7.

How may I add a search form at Content administration page (admin/content)?
I need it so that I can easily find a node when there are hundreds of nodes.

You can use Views Bulk Operations, which allows you to replace that administrative page with a view. As you are using a view, you can add an exposed filter to filter the list of nodes by the title, or any other parameters you choose; the screenshot shows a view that can filter the node list by the author or the state of the nodes.

As far as I recall, VBO comes with an example view that can replace the administration page for the content; you just need to change the URL used for the view, and customize the view itself.


Open preview in new window/page I'm using drupal 7.

Normally, during the creation of a contents, the preview is added above the form.

I would wish that the preview opens in a new window, and that it is separated from the form of creation of contents.

Do you know a solution?

This module looks like something that might fit your need: Simple preview


Rewrite the markup of panels page title I'm trying to rewrite the output of the title of a panels page. I would like to add a class, for example. Actually, if I understand well, panels takes the layout from page.tpl.php then from the selected layout for its contents.
I tried to use taxonomy-term.tpl.php (I'm using the taxonomy page override by panels) but it doesn't work. Still, panels takes header, navbar and title styles from page.tpl.php.
Is there a way to avoid this? Is there a way to add a class or an id to the title element of a panels page?

Edit:
I found this which is for node_view panels template. I don't know if for term_view is different.

Following the comment on the panels issue linked in the question, I managed to make the panels page override for term_view works.
This is the code added to mytheme/template.php

function MYTHEME_preprocess_page(&$vars) {
  // if this is a panel page, add template suggestions
  if($panel_page = page_manager_get_current_page()) {
    // add a generic suggestion for all panel pages
     $variables['theme_hook_suggestions'][] = 'page__panel';
    // add the panel page machine name to the template suggestions
    $variables['theme_hook_suggestions'][] = 'page__' . $panel_page['name'];
        if($panel_page['name'] == 'term_view' ) {
           $vars['theme_hook_suggestions'][] = 'page__term_view';
}
}
}

Then, inside the mytheme/templates/ folder, I added page--term_view.tpl.php with my custom page title display.


Facebook Comments Widget disappears for logged in users EDIT: I would clarify that this only affects Chrome, works in IE\Firefox\Opera.

I am using the following code after the opening  tag

Then in my module I've created a block for the FB Comments, so that I can add it via Panels to the pages I'd like commenting to be enabled in like this (omitting the typical block code required):

function _fb_comment() {
  $url = "http://" . $_SERVER['HTTP_HOST'] . request_uri();
  $comment = '

';
  return $comment;
}

Visitors on my site are able to see the Comment widget, but for logged in users it's not visible and I just can't determine why. It feels like FB is hiding the widget due some problem, but there are no errors in the Console to help debug the issue. Inspecting the actual dom shows us that when it works, the markup is following (visitor):

  …

And for logged in users it shows up like this:

  …

As we can see, FB for a reason or another decides to hide the widget -- what causes this I have no idea, I have tested disabling contextual filters so as not to fiddle with the markup of the block in any way and not aggregating JS, not caching blocks and  just about everything.

As we traverse further down to INSIDE the Facebook iframe, the logged in users one has

..

This might be key, but I've not the slightest clue what may cause it. Was hesitating over asking this in StackOverflow instead of Drupal, but since it's a problem with being logged into Drupal, I might not be the first one to tackle the issue.

This bug, in the end, was a MODERATOR specific bug in the Facebook Commenting widget itself. FB has now fixed it.


Which implementation is better for custom breadcrumb and why? As per answers received here, we can implement custom breadcrumb either via module or via HOOK_preprocess_breadcrumb.

Via module:

In custom_breadcrumb.module file

<?php

namespace Drupal\custom_breadcrumb;

use Drupal\Core\Breadcrumb\Breadcrumb;
use Drupal\Core\Breadcrumb\BreadcrumbBuilderInterface;
use Drupal\Core\Link;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\node\NodeInterface;

/**
 * Class Breadcrumbs.
 *
 * @package Drupal\custom_breadcrumb
 */
class Breadcrumbs implements BreadcrumbBuilderInterface {
  use StringTranslationTrait;

  /**
   * {@inheritDoc}
   */
  public function applies(RouteMatchInterface $route_match) {
    return $route_match->getRouteName() == 'entity.node.canonical' && $route_match->getParameter('node') instanceof NodeInterface;
  }

  /**
   * {@inheritDoc}
   */
  public function build(RouteMatchInterface $route_match) {
    $node = $route_match->getParameter('node');
    $breadcrumb = new Breadcrumb();

    // By setting a "cache context" to the "url", each requested URL gets it's
    // own cache. This way a single breadcrumb isn't cached for all pages on the
    // site.
    $breadcrumb->addCacheContexts(["url"]);

    // By adding "cache tags" for this specific node, the cache is invalidated
    // when the node is edited.
    $breadcrumb->addCacheTags(["node:{$node->nid->value}"]);

    // Add "Home" breadcrumb link.
    $breadcrumb->addLink(Link::createFromRoute($this->t('Home'), '<front>'));

    // Given we have a taxonomy term reference field named "field_tags" and that
    // field has data, add that term as a breadcrumb link.
    if (!empty($node->field_tags->entity)) {
      $breadcrumb->addLink($node->field_tags->entity->toLink());
    }
    return $breadcrumb;
  }

}

and then in custom_breadcrumb.services.yml

services:
  custom_breadcrumb.breadcrumbs:
    class: Drupal\custom_breadcrumb\Breadcrumbs
    tags:
      - { name: breadcrumb_builder, priority: 100 }

Via HOOK_preprocess_breadcrumb, as mentioned in the answer here

Both the ways are achievable, but the question is which one should be followed and why as a best practice?

When you build a module which for example provides a new content or entity type you can include a breadcrumb builder, because you might have data fields that the standard breadcrumb builder doesn't know of and you want to process them in your breadcrumbs. An example for this would be  Drupal\book\BookBreadcrumbBuilder from the core book module.

When you build a theme and want to modify the breadcrumbs already built by the installed core, contrib and custom modules you use a theme based solution in a preprocess hook.

So best practice depends on which level you are working on. Not a good idea would be in this example if the book module would use a preprocess hook.


Customize Commerce Event Ticket PDF content I'm running Drupal Commerce and Commerce Event Tickets on a client site. I'm trying to figure out how to customize the content of the ticket PDF that is generated by the module, and I'm stumped. It's not managed by any of the generated views. Has anyone done this before?

You can customize the PDF content by using the HOOK function <YourCustomModule>_commerce_event_ticket_pdf_alter($pdf, $ticket, $context) or for simpler manipulation use <YourCustomModule>_commerce_preprocess_commerce_event_ticket_pdf_info(&$variables).

Take a look at:
https://www.drupal.org/node/2407879 and https://www.drupal.org/node/2269659

It's also possible to replace the theme function by altering the theme registry:

function <YourCustomModule>_commerce_theme_registry_alter(&$theme_registry) {
  if (!empty($theme_registry['commerce_event_ticket_pdf_info']['function'])) {
    $theme_registry['commerce_event_ticket_pdf_info']['function'] = '<YourCustomModule>_commerce_commerce_event_ticket_pdf_info'; // Your function to alter the content...
}

You should also have a look at the repository on GitHub -> gausie/commerce_event_ticket


Feeds XPath parser - how to map to complex content types (eg to field collection field) I've managed to import nodes of content using the XPath imporer, but where there are deeper levels of data structures, there seems to be no way to map data to a node.

I would have liked to have created these content types using the Field Collection module,
but there's no support for that.

You can use Field collection feeds module which provides feeds integration for field collection module.

You can read here how to import field collection using feeds.


variable Panels image page element I'm not sure if this is possible, but I want to create a panel with a header image.

The way I'm planning to do this is to add a new Page element within panels called "Banner" (in this menu http://puu.sh/jfBbm/8c09cfe2fe.png).

Is it possible to have it so then when a user clicks the "Add Panel -> Page Elements -> Banner -> Chose image?" or is it not possible to have a variable image with this way?

First install Fieldable Panels Panes module. This module allows you to create different fields for Panels pane. Then go to admin/structure/fieldable-panels-panes, Click on Manage Fields of Panes Pane

Add an image field, It is going to be like this

Now click on Add Entity tab and create a new entity. You must also create a Category in Reusability, This Category will be displayed in the Panels Content menu, I called it My own Panels Pane

Now save it.

If you open a Panel and click on Add content the My own Panels Pane is available, click on it and select the content you created.

From the list of Panels Pane in Fieldable Panels Pane there is a direct link to edit this image. I mean this (for testing I created 3 entities ):

Now you can easily edit the image and use it's direct link.


Alt attribute inserted as empty When coding my formatter, I give user an option to provide alt, title and classes attributes for an image. All render beautifully, except for the alt title, which is output as flag-type, empty "alt" attribute (meaning: no equal sign or quotes), regardless of what I try to insert there.

Could the Media module be the reason - such as overriding the alt value with some hooks? If not, any ideas on what could be causing that?

Media module is almost certainly the reason.

There are patches in both http://drupal.org/node/1307054 and http://drupal.org/node/1343022 that you may find useful.


Two branches of theming: templates and functions Here is the description of theming overrides in Drupal. That (pdf page) great colorful scheme is relevant to Drupal 6, however, as I got that, there are no basic changes in the 7th version that are worth mentioning now. Anyway, Drupal (theme() function) either calls hook as a function (i.e. theme_smthing) or as a template, i.e. template_preproces_smth() -> template_process_smth() -> smth.tpl.php

When I have to override deafault Drupal markup, what way I should do this: with theme_ ... or template_ ... ? Why are there two mechanisms that do the same think? (Or it's resonable and I just haven't understood proper;y what id writen there). Can anybody explain these basics?

Thank you.

Theme functions and preprocess functions do not do the same thing. A preprocess function is a precursor to a theme function. A theme function may optionally be implemented as a template file (.tpl.php) rather than a function.

Preprocess functions are created when a module implements hook_preprocess(). If you read the documentation for that hook, it explains that the purpose of a preprocess function is to prepare variables for use within a theme function or template. Also, not all theme functions have a complimentary preprocess function.

Similarly, a theme function (or template) is created when a module implements hook_theme(). A theme function or template is the place where the variables previous prepared in the preprocess function are printed to the screen and wrapped with any desired HTML.

So, the idea is that a preprocess function prepares the variables/data in question and the theme function presents the data to the user, usually wrapped in HTML.


Drupal Views rewrite link dependent on boolean value I have a view that has a boolean field in it and a field that links to a file.  I want to use the boolean field to where if it is checked, it will direct to a static link, regardless of what file is uploaded.  If it is unchecked and there is no file, I want it to output nothing.  If it is unchecked and there is a file, then output the file link.  I tried setting up Views PHP and setting this up there, no luck.  First question is does Views PHP recognize rewrite rules that you've established in other fields, and if not, how can I accomplish this?  Below is the code I tried in Views php.  All it does is output the node id for every entry.

<?php
  if($row->field_booleanval) {
    echo 'Link';
  }
  else if(!($row->field_booleanval) && !($row->field_file)) {
    echo ' ';
  }
  else {
     echo $row->field_file;
  }
?>

I finally got it to work as follows:

PHP field, Value Code:

return $data->field_field_booleanval[0]['raw']['value'];

Output Code:

<?php
  print_r($value);
?>

This returns the correct VALUE for the boolean field. So you can skip the Value Code unless you plan on using the variable elsewhere, and output could look something like:

<?php
  $booleanval = $data->field_field_booleanval[0]['raw']['value'];
  $fileval = isset($data->field_field_file[0]); // shouldn't be set if no value

  if($booleanval) {
    echo 'Link';
  }
  else if(!$booleanval && !$fileval) {
    echo ' ';
  }
  else {
     echo $row->field_file;
  }
?>


How to clone an existing View and change the format from table to CSV? I have managed to figure out how to Install the Views data export module and create a View in order to export to CSV so that I can import this into WordPress.

Someone else has already created all the Views. Here is a screenprint of how the view looks like:

What I want to achieve next is to clone these views and then convert them to CSV format from a Table format. I simply cannot see how or where this can be done.

What I am trying to do is click on the "Working Papers Other" and then clone this View. Once it is cloned I am trying to change the Format from Table to CSV.

There surely has to be a way to do this easily, else it will take an eternity to do all of these Views.

Here are the steps to get you going (referring to the screenprint you added):

Click the drop-down list in the upper-right that says view Working Papers Other, where you should then see another list item with label clone Working Papers Other.
Select (click) on that list item with label clone Working Papers Other.
Note that you'll then have an extra (and same named!) button to the right (or below) the 8 buttons you already have, with the very same label Working Papers Other, and the newly added one will be highlighted (grey / black), and selected.
To improve readability, hurry to go change the line (upper-left) that says "Display name: Working Papers Other" (by clicking on that Working Papers Other link). I suggest you change the Display name to (eg) Working Papers Other (CSV).
Change the line (upper-left) that says "Format: Table | Settings" (by clicking on that Table link). At this point you should be able to change the style of the view from Table to the Views display offered by the Views data export module, with label "Data export".
Tune (refine) the "Settings" of the Data export views display to fit your needs, whereas you can see how the result will look like in the preview near the bottom of your page.
Change the line (upper-middle) that says "Path: /publications/working-pa..." (by clicking on thatPathlink). I suggest you change the path by only adding some suffix such as-csv`.
Don't forget to use the Save button (upper-left) to permanently store the updated configuration of your view.
Click the button (upper-right) that says view Working Papers Other (CSV) (if you used my suggestiuon in item "4.") to actually view (browse) the Views result produced by the various changes described above ... Is it a CSV file that fits your requirements? If not: must be that you did something wrong in the steps described above ...

Note: If you want to become more familiar with Views, checkout the (free) set of 30 video tutorials about the Views module.


How do I change text on the submission button in the node form? I'm trying to change the submit button text "Save and keep published", but with no luck. I'm using the standard hook_form_FORM_ID_alter().

function mymodule_form_node_news_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  // This is the problem, what should I put here
  $form['actions']['publish']['#value'] == '';
}

This is what dpm() returns.

'publish' => array(7)
  '#value' => object Drupal\Core\StringTranslation\TranslatableMarkup(5)
    protected string -> string(18) "Save and keep published"
    protected translatedMarkup -> NULL
    protected options -> array(0)
    protected stringTranslation -> NULL
    protected arguments -> array(0)

How do I change text on the submission button in the node form?

In #value is a translatable string. You can override it with a simple text value:

if ( isset($form['actions']['publish']) ) {
   $form['actions']['publish']['#value'] = 'New Text';
}

Or you can put there a new translatable string with the t() function, if you want to translate the new string in different languages:

if ( isset($form['actions']['publish']) ) {
   $form['actions']['publish']['#value'] = t('New Text');
}

Edit: Answer the question in comments

What you see in dpm() is the result of t(), which is used in the original form in NodeForm.php:

$element['publish']['#value'] = t('Save and publish');

In D8 this is an object, which will result in the translated text when used in a string context. For the enduser you simply use it like a string value, but magically it will always be translated. You don't have to look into this object to find a way to change it. To set a new value you simply generate a new translatable object and put this into the place of the old one.


Adding Display Suite fields to Search API results Problem

I have some Display Suite token fields, and I want to include these and other entity fields in the Search API search results.

I also want to include the Search API Excerpt field in the results.

What's the easiest way to get these DS fields into the search results along with other entity fields?

What I've tried

I have tried using Fields for the view's Format > Show setting, but the DS fields don't appear as field options.

I have tried using Rendered entity for the view's Format > Show setting, but the Excerpt field doesn't appear as a field option in any of the display configurations.

I have tried adding custom theme templates to override the display, and I get a fatal error.  I haven't resolved this error after a bit of searching, so theme overrides doesn't look like the easiest route.

When a #lazy_builder callback is specified, no properties can exist; all properties must be generated by the #lazy_builder callback. You specified the following properties: #attributes.

I missed it earlier, but it turns out that Search API just exposed the Excerpt field to view modes.

Updating Search API to 8.x-1.x-dev and a cache rebuild gave me the functionality I need.


How to use Entity Reference and Views Been reading a lot of questions and playing around alot and I haven't been able to figure this out.

I have a node with a field for entity references.  I'm trying to make a view that I can put on the node page that will grab the fields I want from the referenced entities but I haven't been able to make this happen.

I've created a view that that gets the current NID and I've set up relationships to the entity reference field on the node.  I've also created a node with a the reference field filled out and in the views preview I'm passing that NID, but nothing is returned.

Does anyone have an idea why the view isn't returning the referenced entities that I've defined on the specific node?

Thanks,
Paul

Turns out I needed to use the relationship on the filters as well.