How do I compare two strings in a template file? The template file I am using contains the following code.

foo is '{{ foo }}'
item.url is '{{ item.url }}'
{% if item.url == foo %}
  equal
{% endif %}

I was expecting this code to output foo is 'test' item.url is 'test' equal, but instead it outputs foo is 'test' item.url is 'test'; the equal part doesn't appear.

The following code works.

{% if 'test' == 'test' %}

This code doesn't work.

{% if item.url == 'test' %}

Why doesn't the code I am using work?

This depends on the context, but most likely item.url is not a native string variable test, but a function or a render array with the string representation / render result test.

This is similar to Drupal's well known content variable: When you render {{ content }}, you will get the string representation like
content...
. But when you do a dump or kint, you will see that content is an array, and doing a comparision {% if content = '
content...
' %} will be false too.

I'd recommend to always avoid boolean operations with rendered representations, always head for the raw data. E.g. don't do {% if content.field_something.0 == 'my_value' %}, instead inspect the entity {% if node.field_something.0.value == 'my_value' %}.

If you have to compare to a render array, you could do somehting like {% if some_var|render == 'my_string' %}.


image field point to another image field I have users whom are part of a group, this group has an image field that can be changed by the administrator.

When a user writes a new article, i wan the article to display the image of the group.
To do so, i'm modifying the hook_node_presave(). I'm loading the group of the user and i modify the image of the article to match the one from the group with a simple affection ( $node->field_image = $userGroup->field_image_group; ).

It's working pretty well, however if the group changes its image, the article will still keep the old one.

Is there a way to make the image change automatically ? Same question if I change the author of the article or if the author changes group.

Thank you.

What you need is a change in the way the content is displayed, so it is much better to do it in theme layer rather than content level.

I would recommend using template preprocessing for node.

Add this function to the template.php file in your theme folder:

<?php

/**
 * Implements hook_preprocess_node().
 *
 * Replaces the node's image field with anbother node's image field
 */
function YOURTHEME_preprocess_node(&$variables) {
    $node = $variables;
    // Make sure we only alter nodes that we intend to!
    if ($node->type == 'article') { // assiuming your article content-type is 'article'
        // Get the view mode for this node, e.g. full or teaser
        $view_mode = $variables['view_mode'];
        // Get the group node
        $another_node = get_another_node($node); // Somehow!
        // Retrieve the image field of that node using the same view mode of the current node
        $another_image_field = field_view_field('node', $another_node, 'field_image', $view_mode); // assiuming it is called 'field_image'
        // Replacing the other field with the current node's field
        $variables['content']['field_image'] = $another_image_field; // assuming it is called 'field_image'
    }
}

You will need to update the code to retrieve the node object for the group and also make sure that the field names are correct for your case.


How do I create a view from the user interface, and get the code to create it programmatically? Is there a way to get the program code for creating a view from an existing view?

I first created a dummy view with the user interface. I would like to get the code that I have to insert in my module to create that view, so that my module replicates what I did with the UI. Is this possible?

That is a feature that the Views module already has. In Drupal 7, you need to follow these steps:

In the page listing all the views defined in a site, select the "Export" operation

In the next page, the Views module will show you the code that defines the view.

This is only the code that defines the views.

Another way, is the following one; in this case, you get the complete code to use to write a module.

Enable the Bulk Export module that is listed under the modules that are part of the Chaos Tools Suite module
On admin/structure/bulk-export, select the view(s) you want to export in a module, and enter the name of the module

After you click on the "Export" button, the next page will show you the content of the .info, the .module, and the .inc file you can use to write a module that implement the view

In Drupal 6, you need to follow these steps:

Enable the View Exporter module that is part of the Views module (I am referring to version 6.x-3.0.)
On admin/build/views/tools/export, select the view(s) you want to export in a module, and enter the name of the module

After you click on the "Export" button, the next page will show you the content of the .info, the .module, and the .inc file you can use to write a module that implement the view


Photo Gallery attached to Story - How to Create I figured out a way to add a photo gallery to the bottom of a story using a custom content type for the photos, then creating a view with clickable thumbnails and saving it as a block. The problem is I can't reuse this for the next story. I would need to create yet another content type and another view. How can I set it up so I can post a different gallery to a different story?

Is there a module that might help with this?  I tried Views Galleriffic, but it doesn't seem to work as a block.  I couldn't find any way to make the gallery appear at the bottom of a story.

I ended up add the images directly to the story with new fields so they could be shown as a gallery of thumbnails with a block.  I used a view with a grid and followed directions to create a contextual filter from this helpful post:
http://www.drupalwoo.com/content/blog/easy-gallery-image-option-your-content-editors-drupal-7


autocomplete field show name pass uid to form In my module I'd like to allow admin/moderator to add some user specific settings e.g. user steve1 has to work between 8am and 3pm.

To make work easier for the admin I'd lke to use autocomplete field for choosing user.

Suggestions are made via user name, but to form, I need to pass uid instead of a name.

Is this possible via modyfinig my autocomplete code, or should I change provided name to uid during form_submit operation?

$matches = array();
$query = db_select('users', 'u');

$return = $query
  ->fields('u', array(
    'uid',
    'name'
  ))
  ->condition('u.name', '%' . db_like($string) . '%', 'LIKE')
  ->range(0, 10)
  ->execute();

foreach ($return as $row) {
$matches[$row->name] = check_plain($row->name);
}

// return for JS
drupal_json_output($matches);

In your foreach you can add it

foreach ($return as $row) {
   $matches[$row->name . '[uid:' . $row->uid . ']'] = check_plain($row->name);
}

And in your submit handler you can find it with a simple preg_match like this one :

preg_match('/\[uid:(\d+)\]/', $form_state['values']['user_autocomplete'], $matches);
$uid = $matches[1];

Note that the $matches variable are not the same from the auto-complete part and the submit handler part.


Will groups with more number of users cause the page to load slower? Anonymous page takes 1 to 2 secs to load
After the successful login, we are showing the same page but with some menu. I have disabled that menus too. But the page load takes 10 secs to load with same content.
We have groups. To check,have disabled the groups assigned to the user, then the page loads faster 1 to 2 sec. At first we though that, assigning groups might cause the issue. But the scenario is like, if I add single group which have more content(700) and  users like (1500) cause the issue.Except dat grp,if I add more  groups to the user,the page loads faster.
After disabling organic subgroups, and adding that single group causes the page to load faster.
Can you share your thoughts?

The more modules you add to a site, the more code that likely has to execute, which equates to more overhead per request. Organic Groups particularly can be heavy, depending on what you are trying to achieve. I do not know how much progress they've made in the last few years, but in my experience it was always pretty heavy.

Logged in users also bypass caching, whereas anonymous users see as much cache as possible. This isn't as true for 8.x, but the differences in 7.x can be pretty black and white. Juggling multiple logged in users simultaneously can put a hurt on low end setups or especially if you haven't implemented caching. Or a runaway module could be calling functions every single request per user, adding to that time.

Honestly, the best tools that will help you pin down potential bottlenecks are xhprof and using a service like New Relic. It will give you far more intel about your application than anyone here ever could.

Other things you can do simply comes down to good planning. Are pages made up of lots of Views? Implement Views caching on displays that don't change often. Are you using Panels? Do you need to use Panels? Are you running memcache, does PHP have 256M memory limit, is your server underpowered?

I would start with New Relic, honestly, and xhprof. New Relic is easier to setup than xhprof, depending on your experience. You will need to profile your site before you know what steps to take first.

If you are running Drupal 8, also install the Web Profiler toolbar included with Devel.


How to call a drupal custom module function from a basic page? * if i will click a input button in basic page a particular function should be called from my custom module. I have already enabled my
 module in my instance.*

<?php
$name = $_POST['name'];
$pwd = $_POST['pwd'];
homeFun($name,$pwd)
?>
<form method="post" action="<?php $_SERVER['PHP_SELF'] ?>">

Name
 <input type="text" name="name">

Password:
<input type="password" name="pwd">

<input type="submit"  value="Register">
</form>

i am using this code...and its working but the problem is while refreshing the page, function automatically gets called without clicking button...
I wrote this code in Basic Page...

  Please guys tell me the proper way to call the functioin from my basic
  page.

I just wanted to execute my cutome module function after clicking submit button...is there any simple way to do that...

I guess you want to create a menu callback which will call your form right?
Here is how to-

Create your menu hook like bellow:

function mymodule_menu($node) {
  $items['my-frm'] = array(
    'type' => MENU_CALLBACK,
    'page callback' => 'drupal_get_form',
    'page arguments' => array('my_form'),
    'access callback' => TRUE,
  );
  return $items;
}

Than create your form like below:

function my_form() {
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit'),
  );
  return $form;
}

And after that here is your form submit:

function my_form_submit() {
  drupal_set_message("Hello World my form submit hook is called here");
}

Do a clear cache and navigate to yoursite/my-frm link you should see your form.


Allowing content access only though aliases and views I'm building a site in Drupal 8 that will have complex content best viewed using views. The basic pages should use nice and clean URL aliases.

Is there a way to stop the visitor from accidentally using /node/x in the URL and only allow accessing the views and pages that have aliases and organised in the website menus?

Yes, in Drupal 7 this functionality was covered under the Global Redirect module. It has since been merged in the Drupal 8 version of Redirect.

Under the Redirect settings (/admin/config/search/redirect/settings), the Global Redirect section contains options to enable alias, non-clean, & canonical redirecting. This will enable you to redirect any requests from /index.php?q=node/X or /node/X to /my-canonical-content-alias.


Ubercart thumbnail saving in sites/default/files - Its messy - How would I get it to save in a specified folder? All of my ubercart thumbnail images are saving in sites/default/files and its getting way too messy. Is there a way I can tell them to save in a folder inside this directory? There is a media style for them and they get the prefix thmb_ but I cannot figure this out. Thanks

Try the File (Field) Path Module:

  The File (Field) Paths module extends the default functionality of
  Drupal's core Upload module, the FileField module and many other File
  Upload modules by adding the ability to use node tokens in destination
  paths and filenames.

  In simple terms, File (Field) Paths allows you to automatically sort
  and rename your uploaded files using token based replacement patterns
  to maintain a nice clean filesystem.

This can be applied to the Field holding the image


Is it possible to post a file with drupal_http_request? Is it possible to use drupal_http_request() to post a file? If not, what function can I use to submit a file to a webservice?

All you need is to set correct header information.
I'd do it like so:

$boundary = 'A0sFSD';
$headers = array("Content-Type" => "multipart/form-data; boundary=$boundary");
drupal_http_request('some/url/you/want/to/post/file/to', $headers, 'POST', multipart_encode($boundary, $params));
if ($request->error) {
    watchdog("ipaper", "Request failed - ". $request->error .' - '. http_build_query($params));
}

...............

function multipart_encode($boundary, $params){
    $output = "";
    foreach ($params as $key => $value){
    $output .= "--$boundary\r\n";
    if ($key == 'file'){
        $output .= multipart_enc_file($value);
    }
    else {
        $output .= multipart_enc_text ($key, $value);
    }
    $output .="--$boundary--";
    return $output;
}

function multipart_enc_text($name, $value){
    return "Content-Disposition: form-data; name=\"$name\"\r\n\r\n$value\r\n";
}

function multipart_enc_file($path){
    if (substr($path, 0, 1) == "@") {
        $path = substr($path, 1);
    }
    $filename = basename($path);
    $mimetype = "application/octet-stream";
    $data = "Content-Disposition: form-data; name=\"file\"; filename=\"$filename\"\r\n";
    $data .= "Content-Transfer-Encoding: binary\r\n";
    $data .= "Content-Type: $mimetype\r\n\r\n";
    $data .= file_get_contents($path) . "\r\n";
    return $data;
}

You might also consider using cURL for this purpose.


How to show field in snippet? I use PHP filter module, and write this in other field in my node:

<?php
  $node = node_load(52);
  $field = field_view_field('node', $node, 'myfield');
  print $field;
?>

It doesnt work.
And how i can load id for node?

field_view_field returns a renderable array for the field value. So you should use render() function:

<?php
  $node = node_load(52);
  $field = field_view_field('node', $node, 'myfield');
  print render($field);
?>


How to compare with a rules condition vote:uid to 10 instances? Principle: limit user's votes to 10.

Modules used: Voting API, Rate (or maybe Plus1)

Context: Users can vote on projects with 10 possible votes to distribut on all projects, by 1 to 10 votes on each project of their choices, up to a total of 10 votes.

When a user has distributed 10 votes, he loses the permission to vote.
To swith the permission with rules, I create a role "Voter". All users have the role by default.

At that point, I have this:
- Event : content is viewed (of type project)
- Condition : site:current-user:uid equals vote:uid
//And now I'd like to say something like "AND vote:uid appears 10 times in the 'votingapi_votes'.'uid' SO
- Action : Add/remove user role to simple AU (without vote permission)

So how to compare with a rule condition vote:uid to 10 instances?

In the scenario you describe, a simple solution could be to create a profile field to store the number of votes per user. This field will be:

set to 0 as a default value
incremented when the user votes (you can use Rules for that, there is an action called "Set a data value")
compared with your defined maximum (ex: 10) in Rules, so that when the user reaches 10, something is triggered (ex: Remove user role: "Voting User")

You can then set the voting API permissions to this role ("Voting User"), and use it as a display condition to hide the voting buttons (Plus 1 or Rate).

Hope it helps!
Cheers


Views 3.8: Show taxonomy hierarchy in three columns (grandparent, parent, child) I have a taxonomy with a three-level hierarchy, and would like to display the three levels in a views table, but separately. I'd also like to have an exposed filter using that taxonomy and let my users pick the term.

Here's what I've done:

Added the contextual filter Has taxonomy term id depth modifier
Added the relationship Content: Taxonomy terms on node with an identifier "term"
Added the relationship Taxonomy term: Parent term with an identifier "Parent" and set its relationship as "term"
Added the contextual filter Taxonomy term: Parent term and selected the "Parent" relationship
Added the taxonomy term field

At this point I can display the hierarchy in a single column and can choose between the lowest level child or all three (e.g. Grandparent > Parent > Child). However, I want to be able to display the grandparent, parent and child in separate columns.

Is this possible? I was hoping to maybe add the field three times and pick the hierarchy level, but I don't see how to do that.

If you've only 3 level of hierarchy then you can create a view as below:

Above view should give the output as below:

Hope this helps.


Filter a view by the value of a field I have just started using Drupal (Drupal 7) and I would like your help to do something.
I have created a field called : Current Project where each user writes the project they are currently working on.
I want to create a view in each user's profile page that will show all the other users that work on the same project.
I tried to create this using the Views module but I can only insert a specific value as a filter. What I would like to do is to create a view that will show all users that have the same Current project as the viewed user.
Thank you very much for your help.

I don't think that's the best way to make this but here is an quick and dirty way :

Create your view and instead of using filter Click advanced and add contextual filter , then chose your field.
enable the PHP filter in modules
Create a block in admin/build/block and chose php filter there you will embed the php code below
now you have to load the profile of current user profile for this use this function, there you will find the current working project field and pass it to the views (I suppose that you added this field in profile 2) :
$path = drupal_get_path_alias($_GET['q']);
$path = explode('/',$path);
// if the position of viewed user id in the path is 1
$uid = $path[1];
$current_user = profile2_load_by_user($uid);
//make print_r($current_user) to find your field of project currently working on
$arg = $current_user["main"]->your_custom_field["und"]["value"]; // if I remember
print   views_embed_view('your_view_machine_name','your_view_display_machine_name',$arg);

//to find out the machine name of your view hover over its ling and you will see then name in the link below

This solution is for just one argument , if you have multiple field value (more than one current project) you will have to select mut pass arguments like this :

foreach ($current_user["main"]->your_custom_field["und"] as $record) {
            $values[]= $record["value]";
    }
$args =implode('+',$values);
views_embed_view('your_view_machine_name','your_view_display_machine_name',$args);

Hope this will help


Problems with logging out users I was running through some tests on my site with a client, and I was logged in as a normal authenticated user. I then logged out with the intention of logging back in as the superadmin (uid -> 1).

I navigated to a node page where there was a login form, and the site automatically logged me in as the authenticated user that I was logged in as previously.

Do you have any ideas of what could be causing this? The page that where this auto-login occurred reads off of a custom node.tpl file and I've got a few user_load() calls in that code.

If you are also using the global $user object in your code, doing something like $user=user_load($node->uid) can 'log you in'.  This is a security issue and should be corrected.


How can I list the current user's orders with Drupal Commerce? I need a View which shows the list of all orders belong to the currently logged in user.

I looked at the Administrators Order View, there are some stuff with Commerce-Line Items but I couldnt figure out how they made that

There already is one provided with commerce_order_ui called commerce_user_orders. By default it's available at user/[uid]/orders. It needs the permission View own orders of any type.


Replace placeholder in custom block with preprocess hook This is the first time I'm using the preprocees hook, apologies in advance.
I added a placeholder, {{user-uid}}, in a custom block body field, Advisor Page
.
My code is very simple, I have this hook theme.
    function boostrap_kampuster_preprocess_block(&$variables) {
        if (isset($variables['content']['#block_content'])) {
            $content = $variables['content']['#block_content'];

            /** custom block ID is 4 **/
            if( method_exists($content,'id') && $content->id() == '4') {

                $body = $variables['content']['body'][0]['#text'];

                $vars['user'] = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());
                $body=str_replace('{{user-uid}}',$vars['user'],$body);
            }
        }
    }

I am not getting any errors but the function is not doing what it is supposed to do and replace {{user-uid}} with logged in user's ID either.
FYI, I cleared caches several times.

In addition to @sonfd answer you also need to consider caching. The easiest way would be to add a cache context:
$variables['#cache']['contexts'][] = 'user';

But then the database needs to store a cached version for each user.
Better for performance would be to postpone replacing the placeholder by attaching a lazy builder to the render array:
function mytheme_preprocess_block(&$variables) {
  $variables['#attached']['placeholders']['{{user-uid}}'] = [
    '#lazy_builder' => ['_mytheme_replace_uid', []],
  ];
}

which then returns the markup of the user UID:
function _mytheme_replace_uid() {
  return [
    '#markup' => \Drupal::currentUser()->id(),
    '#cache' => ['contexts' => ['user']],
  ];
}

Drupal 9
Drupal 9 requires using only trusted callbacks. So define a class implementing TrustedCallbackInterface or RenderCallbackInterface:
mytheme/src/MythemeLazyBuilders.php:
<?php

namespace Drupal\mytheme;

use Drupal\Core\Render\Element\RenderCallbackInterface;

class MythemeLazyBuilders implements RenderCallbackInterface {

  public static function replaceUid() {
    return [
      '#markup' => \Drupal::currentUser()->id(),
      '#cache' => ['contexts' => ['user']],
    ];
  }

}

and add it to the render array:
function mytheme_preprocess_block(&$variables) {
  $variables['#attached']['placeholders']['{{user-uid}}'] = [
    '#lazy_builder' => ['\Drupal\mytheme\MythemeLazyBuilders::replaceUid', []],
  ];
}


views - group by first letter of results As the title describes, I am trying to group the results of a view by their first letter. Googling revealed a way for me that half does the trick : display title twice, exclude from display, limit to 1(st) character, group by that. Clever I must admit but i need to reveal a grouping field even if there are no results in it such as:

A
  Alpha
  Anekin

B
  Bravo
  Borvo
C

D
  Delta
  Dooku

Any thoughts on how to go about doing that?

A simple solution would be to add a field that only had the first letter and group by that.

Views also supports doing glossary, which is a but different, but allows you to group by the first letter and count the number of results and show fx

A(2) B(2) C(0), as an exposed filter, this is done through contexts in views 3.


How to access referenced entities programmatically I have an entity (a node) with a term reference field. I'd like to access the referenced term entities programmatically, i.e. the fully loaded term objects.

Note that my question could equally apply to any referenced entity, e.g. node entities, user entities, etc.

Here's what I've got so far:

$node = \Drupal\node\Entity\Node::load($nid);

$term_ids = array();
$items = $node->field_tags->getValue();
foreach ($items as $item) {
  $term_ids[] = $item['target_id'];
}

$terms = \Drupal\taxonomy\Entity\Term::loadMultiple($term_ids);

It works, but I'm not very happy with it:

It lacks abstraction (how am I supposed to know that the id of the referenced entity is in $item['target_id']?)
It's not very generic (it works if the field references terms, but what if it references nodes or users?

Any better solution?

The following $node->get('tags')-referencedEntities() will return a list of all the referenced entities.


Drush or Drupal console command to list modules with security updates? Is there a command for Drupal 8.x that shows available updates?

I added forms_steps 1.1 that has an SA and a security update required in the Web UI, which is saying to update to 1.2

I tried drush pm:security but it reports that there is no outstanding security.

root@d568732a8640:/app# drush pm:security
 [success] There are no outstanding security updates for Drupal projects.

I might have overestimated the capability of this command so I'm looking for alternatives to get both update and security update in the console. My goal with this is to add a schedule job in our CI that will report on those.

drush pm:security should be fine in listing Drupal modules with security updates.

There was a bug from the drupal-composer/drupal-security-advisories project that resulted in not listing the forms_steps module and some other modules.  It was promptly fixed and now it works!


How can I programmatically apply text formats? I've created a custom text format I'm trying to apply to a field programmatically. As best I can tell, the format IS getting applied, but it is not stripping HTML tags like it is supposed to. The below screenshot shows how my text formatter is configured:

As you can see, its supposed to filter <span> tags. The Nodes where this will be used get created programmatically, and I apply the text formatter as follows:

'field_career_job_description1' => ['value' => $job['jobdesc'],'format' => 'careers_html_formatter']

This appears to be working correctly, if I print the variables passed to twig, I see that the formatter is, indeed, my custom format:

However, as you can see in the sshot, <span> tags are still in the text.

Note that I am displaying the field in question in Twig as follows:

{{ content.field_career_job_description1[0]['#text'] | raw }}

As I was pressing post on this question, I realized the problem. It's the twig code. In order to get the text formatter properly applied, I had to call my field as follows:

{{ content.field_career_job_description1 }}

Leaving this question up because I couldn't find anything like it on google


default value imagefield -> get from field collection item I've got a contenttype "gallery" with an imagefield "thumbnail", used in listviews oder teaserviews. This contenttype also has a field collection with "image", "title" and "description". So what would be great now, if there's no value set for the "thumbnail" field, the default value should be the value from the first field-collection image.

any chance to realize this? Thanks for your help

EDIT:

i tried this:

That's not a solution

function channelportal_gallery_node_presave($node) {

    $galleryimage = field_get_items('node', $node, 'field_gallery_and_caption');
    $firstimageID = $galleryimage[0]['value'];

    $item = field_collection_item_load($firstimageID);
    dpm($node->field_thumbnail);

    $node->field_thumbnail = field_get_items('field_collection_item', $item, 'field_gallery_image');
    dpm($node->field_thumbnail);
}

But nothing is stored, to the field, even if the first dpm gives back an empty array and the second one containing the values it should contain. But after all, nothing is stored to the field and it's empty again...

Thanks for your answer Chad Payne

I would look in to something like

hook_node_presave

As a rough example I would have it work like this

function MY_MODULE_node_presave($node) {
     if(!isset($node->field_thumbnail)) {
          // load field collection and save that image to this image field
     }
}

I haven't tested this code but i think this would be the direction you would want to go in.


How to define a function in drupal core How should I define a function in the core of drupal 7 that I can use the function in the blocks, pages and etc?

Simple answer - don't :)

You shouldn't change anything in the core files, it'll just make things difficult when you try to update.

Drupal's way of extending functionality is through Modules; it's easy to write your own.

When a module is enabled, all the functions defined in the 'MODULENAME.module' file are available during the page build. So if you define a function

function MYMODULE_say_hello() {
  return 'Hi!';
}

That will be available for use in code in the same module, other modules and themes.

As Drupal doesn't currently use namespaces, it's important to prefix your 'global' function names with the name of the module. This just helps to make sure you avoid collisions with other functions of the same name (imagine another module also wanted to say_hello()), which would otherwise result in a fatal error.

There's also a convention in Drupal programming to prefix 'private' function names (those that should only be used internally by your module), with an underscore, e.g.

function _MYMODULE_say_hello_quietly() {
  return '<hush>Hi</hush>';
}

This doesn't technically stop them from being available to other modules (which is actually a good thing in a lot of cases), but it's a good pattern to fall into for Drupal 6/7 development.

For Drupal 8, thankfully, we'll have a much more OO focused core. But that's a topic for another day...


Is there a way to manually run cron with Drush? I want to be able to accomplish this:
http://mywebsite.com/admin/reports/status/run-cron

But it should be done through the Drush interface.

Can any one help me out ?

You can try drush core-cron

  $ drush help core-cron
  Run all cron hooks in all active modules for specified site.

  Aliases: cron


Error Drupal 7 body content missing when adding new content Hi my drupal 7 creating a new content, suddenly the body field disappear? and i dont know what cause this? is there anyone can help me

The body field is field attached to content type, so if its remove from particular content type, then it mean you have removed the fields from the content type.

You can enable the fields again for the content type by Administrator -> Structure -> Content type -> [type] ->Manage fields.

In the section "Add existing field", you can select the fields "body" and add to content type.


How can I remove the "Your vote was recorded." message in the polls? I need to delete the message "Your vote was recorded." when a user votes in a poll.

I tried comment the line containing drupal_set_message(t('Your vote was recorded.')) in the Poll module, but if I do this, the Poll Enhancements module doesn't work well.

What other way has Drupal 7 for deleting specific messages?

The messages set with drupal_set_message() are saved in $_SESSION['messages'][$type] as an array of strings ($type can be "status", "warning", or "error"). The message you see, is set in poll_vote(), which is the form submission handler used for processing a vote, used from poll_view_voting(), the form builder for the vote form.

In order to remove the show string you should:

Implement hook_form_FORM_ID_alter() to add a form submission handler that is executed after poll_vote().
Implement the form submission handler to remove the string added from poll_vote().

Code similar to the following one should work.

function mymodule_form_poll_view_voting_alter(&$form, &$form_state) {
  $form['vote']['#submit'][] = 'mymodule_poll_view_submit';
}

function mymodule_poll_view_submit($form, &$form_state) {
  if (isset($_SESSION['messages']['status']) && is_array($_SESSION['messages']['status'])) {
    $messages = array_flip($_SESSION['messages']['status']);
    unset($messages[t('Your vote was recorded.')]);
    $_SESSION['messages']['status'] = $messages;
  }
}


Where can I find the code for the user menu block? I'm trying to code a custom user menu, but I would like to see the original code of the built-in user menu block. Where can I find it?

In user.module, all functions with prefix user_block_ in name.


Ubercart: PHP message if a Product is in cart I need help with a boolean function in PHP. It's simple (but I'm not PHP savvy enough to do it myself). I just need to create a block with a message (not a system message because I am using better messages and I don't want people to close the pop-out without even reading it) that will only show in the ubercart cart
page, if two of the products are in the cart. Else it won't show.

Of course, if there is a better workaround tio this, I am open to suggestions.

Thanks in advance to whomever might wanna help.

Create a block with input format as php code.  uc_cart_get_contents() function will help you to get current cart products. So use it to check for your products.

eg:

$items = uc_cart_get_contents();
// print_r($items); you can see all items in cart
foreach ($items as $item){
  //check your condition if condition true print your message,
}

Assign the block to a specific region and give display in cart page only


What file and folder permission changes does the Microsoft Web Platform Installer make when it installs Drupal? I have used the Microsoft Web Platform Installer to install both Drupal 6 and Drupal 7 on my Windows Server 2008 R2 servers running IIS 7.5. (see: http://www.microsoft.com/web/downloads/platform.aspx)

I'd like to know what file and folder permissions WebPI is modifying (and why) and the web.config additions it is making so that I can manually install Drupal under IIS for those times when the default installation parameters need to be tweeked (such as where the databases are housed).

Changes made to PHP to make it play nice with Windows + IIS would also be helpful.

You may be interested in this question.

However, a manual install of Drupal has a few variables.

For all versions of Drupal you will need to install PHP.  The recommended way to install PHP is with Fast CGI.  (That is also how the WebPI installs it.)

Since you are running Server 2008, it is recommended that you use Mirosoft's URL rewriter if you want clean URLs.  (That is also how the WebPI installs it.)  If you are using Microsoft's URL rewriter, it will automatically look for a web.config file.  Drupal 7 ships with a default one, which I believe will work for Druapl 6 as well.

Then, you need a database.  For Drupal 6 your only practical option is MySQL.  For Drupal 7 you can choose between MySQL and the more native MSSQL.

Once those three items are installed you are pretty much left with permissions.  By default IIS uses C:\inetpub\wwwroot\ for all web served files.  For IIS to read those files the local IUSR account needs read permissions.  To write the local IUSR account needs write permissions.  I believe the recommended behavior currently is IUSR gets read permissions to everything in C:\Inetpub\wwwroot.  However write permissions are restricted to only where absoultly needed.  The traditional location is ..\sites[sitename]\files as that is the default location for user uploaded files.  However Drupal 7 has a fancy web installer for modules.  For that to work ..\sites[sitename]\modules and ..\sites\all\modules need to be writeable by the local IUSR account.  One final note.  For the default Drupal install process to work ..\sites[sitename]\settings.php needs to be writeable by the local IUSR account.  However, post install it is usually recommended that file be read onle.


How do I modify the URL to a taxonomy term? I have a vocabulary called Industry with four terms. I have edited the terms to keep the URL to be automatically generated. They are following this convention:

industry/term1, industry/term2, etc...

I want the convention to be (without the "industry/"):

term1, term2, etc...

I configured the URL alias patterns like so for Taxonomy Term paths:

Default pattern:
[term:vocabulary]/[term:name]

Pattern for all Industry paths:
[term:name]

However, when I navigate to the URL (i.e. /term1), I get this message:

The requested page "/term1" could not be found.

On top of that, I have a view for a block that generates this vocabulary as a list with the links so users can click on them and go to the taxonomy page. I have the option selected for each term:name that we need to "Link this field to its taxonomy term page". When that block is rendered, it generates a URL like so:

[term:vocabulary]/[term:name]

This is not what I expected. I expected the URL to be [term:name].
I am new to Drupal and still learning things about it. What am I doing wrong?

Please check if you have a URL Alias in the system for "/term1".

It might be mostly the case of all your old Alias existing in the system not the new once. If you don't find the update URL alias under admin/config/search/path. Then it just a simple bulk regenerate (admin/config/search/path/update_bulk).

Please ensure you have selected

Taxonomy term
Update the URL alias for paths having an old URL alias (at Times you may want to use the option Regenerate URL aliases for all paths)


Is there any module that can show whoever edits a node? Is there any module that can show whoever edits a node, just like how happens on Stack Exchange sites, where the user who edited a post is shown together the author of that post?

This article should be able to help you: Adding 'Last edited by name some time ago' information

I'm not sure how you want it to look exactly, but with a preprocess function and a simple template edit, you can add an editors information.  You can style this however you like and add/remove information, but to show the editor's name and the edit date/time do the following:

Add to template.php (or add the code to the preprocess_node function if already exists):

function neuco_preprocess_node(&$variables) {
  $node = $variables['node'];
  $editor = user_load($variables['revision_uid']);
  $variables['edited'] = 'Edited by ' . theme('username', $editor) . ' on ' . format_date($node->changed, 'medium');
}

In your tpl file (node.tpl.php, node-YOURTYPE.tpl.php, etc):

<?php print $edited; ?>

Functions used: template_preprocess_node(), user_load(), format_date(), theme_username()


How do I migrate file uploads? I'm working on a custom migration from Drupal 6 to Drupal 8. Some of the content types have a field used for file attachments (field_attachments).
When I run the migration that connects the files to the nodes, I get this error.

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'title' cannot be null: INSERT INTO {node_field_data} (nid, vid, type, langcode, status, uid, title, created, changed, promote, sticky, default_langcode, revision_translation_affected) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2, :db_insert_placeholder_3, :db_insert_placeholder_4, :db_insert_placeholder_5, :db_insert_placeholder_6, :db_insert_placeholder_7, :db_insert_placeholder_8, :db_insert_placeholder_9, :db_insert_placeholder_10, :db_insert_placeholder_11, :db_insert_placeholder_12); Array ( [:db_insert_placeholder_0] => 2064 [:db_insert_placeholder_1] => 3019 [:db_insert_placeholder_2] => forum [:db_insert_placeholder_3] => en [:db_insert_placeholder_4] => 1 [:db_insert_placeholder_5] => 0 [:db_insert_placeholder_6] => [:db_insert_placeholder_7] => 1558576761 [:db_insert_placeholder_8] => 1558576761 [:db_insert_placeholder_9] => 0 [:db_insert_placeholder_10] => 0 [:db_insert_placeholder_11] => 1 [:db_insert_placeholder_12] => 1 ) (/app/web/core/lib/Drupal/Core/Entity/Sql/SqlContentEntityStorage.php:847)

The migrate_plus.migration.custom_upload.yml file for the migration contains the following lines.
langcode: en
status: true
dependencies: {  }
id: custom_upload
class: Drupal\migrate\Plugin\Migration
field_plugin_method: alterFieldInstanceMigration
cck_plugin_method: null
migration_tags:
  - 'Drupal 6'
  - Content
migration_group: custom
label: 'File uploads'
source:
  plugin: d6_upload
process:
  nid:
    -
      plugin: get
      source: nid
  vid:
    -
      plugin: get
      source: vid
  langcode:
    -
      plugin: user_langcode
      source: language
      fallback_to_site_default: true
  type:
    -
      plugin: get
      source: type
  field_attachments:
    -
      plugin: sub_process
      source: upload
      process:
        target_id:
          plugin: migration_lookup
          migration: custom_file
          source: fid
        display:
          plugin: default_value
          default_value: 1
        description: description
destination:
  plugin: 'entity:node'
migration_dependencies:
  required:
    - custom_file
    - custom_article
    - custom_forum

From the error message, it appears that Drupal is trying to create a node; even though, I'm actually running the custom_upload migration after I ran the migration of all nodes.
I have migrated the nodes and the files already and I can see all the nodes in the database as well as the files in their directory and the database.
What am I missing?

Your custom_upload migration is trying to create nodes; the custom_upload migration is taking a d6_upload source plugin:

source:
  plugin: d6_upload

...and mapping it to a node:entity destination plugin:

destination:
  plugin: 'entity:node'

Since the d6_upload source doesn't have a title field to map to the node:entity field in the process definition of your migration, the migration fails as it tries to insert a titleless node.

You need update your node migration. If your node/file migrations are working, the node migration should have a
process.field_attachments yml property to map field_attachments.target_id to the fid property from your custom_file migration.


Need to override single Drupal 8 plugin function What I want to do is edit what is displayed in the autocomplete/drop selects for an entity reference. Basically instead of just [title] I want to show [title] - [other_distinguishing_field]. I know that I can do this by editing getReferenceableEntities in Drupal\Core\Entity\Plugin\EntityReferenceSelection. All I want to do is override that function. I read that I need to make a plugin for this, but I find all of the tutorials a bit confusing and I don't understand how to implement what I want using a plugin.  Do I need a plugin manager? Do I need to use annotations? Where do I reference Drupal\Core\Entity\Plugin\EntityReferenceSelection? Where do I override the function? Do I need to configure anything on the UI the use my plugin or will it automatically work?

**EDIT
Here is what my Plugin manager looks like using the solution provided by @ya.teck

    <?php
/**
 * @file
 * Contains ExampleEntityReferenceManager
 */

namespace Drupal\example;

use Drupal\Core\Plugin\DefaultPluginManager;
use Drupal\Core\Cache\CacheBackendInterface;
use Drupal\Core\Extension\ModuleHandlerInterface;

/**
 * ExampleEntityReference plugin manager.
 */
class ExampleEntityReferenceManager extends DefaultPluginManager {

  /**
   * Constructs an ExampleEntityReferenceManager object.
   *
   * @param \Traversable $namespaces
   *   An object that implements \Traversable which contains the root paths
   *   keyed by the corresponding namespace to look for plugin implementations,
   * @param \Drupal\Core\Cache\CacheBackendInterface $cache_backend
   *   Cache backend instance to use.
   * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
   *   The module handler to invoke the alter hook with.
   */
  public function __construct(\Traversable $namespaces, CacheBackendInterface $cache_backend, ModuleHandlerInterface $module_handler) {
    parent::__construct('Plugin/EntityReferenceSelection', $namespaces, $module_handler, 'Drupal\Core\Entity\EntityManagerInterface', 'Drupal\Core\Entity\Annotation\EntityReferenceSelection');

    $this->alterInfo('example_entity_reference_manager_info');
    $this->setCacheBackend($cache_backend, 'example_entity_reference');
  }
}

Method #1
You can simply create new plugin which extends class of target Core plugin.

File: modules/example/src/Plugin/EntityReferenceSelection/ExampleSelection.php

namespace Drupal\example\Plugin\EntityReferenceSelection;

use Drupal\Component\Utility\Html;
use Drupal\Core\Entity\Plugin\EntityReferenceSelection\DefaultSelection;

/**
 * Entity Reference Selection with distinguishing field.
 *
 * @EntityReferenceSelection(
 *   id = "example",
 *   label = @Translation("Example"),
 *   group = "example",
 * )
 */
class ExampleSelection extends DefaultSelection {

  /**
   * {@inheritdoc}
   */
  public function getReferenceableEntities($match = NULL, $match_operator = 'CONTAINS', $limit = 0) {
    $target_type = $this->configuration['target_type'];

    $query = $this->buildEntityQuery($match, $match_operator);
    if ($limit > 0) {
      $query->range(0, $limit);
    }

    $result = $query->execute();

    if (empty($result)) {
      return [];
    }

    $options = array();
    $entities = $this->entityManager->getStorage($target_type)->loadMultiple($result);
    foreach ($entities as $entity_id => $entity) {
      $bundle = $entity->bundle();

      $translated_entity = $this->entityManager->getTranslationFromContext($entity);
      $label = $translated_entity->label();
      $distinguishing_field = $translated_entity->get('field_example')->get(0);
      if ($distinguishing_field) {
        $label .= ' [' . $distinguishing_field->getValue()['value'] . ']';
      }
      $options[$bundle][$entity_id] = Html::escape($label);
    }

    return $options;
  }

}

Having this done navigate to field settings page and enable your reference method.

Method #2
For select list widget you can install Entity Reference Views Select which allows to build selection options using Views fields.

Method #3
Content Browser module (not stable yet) offers more advanced way to select entities.

Method #4
You may globally override Entity::label() method for required entity type. So that the [title] - [other_distinguishing_field] pattern will be used everywhere including default entity reference selection plugin.


Programatically insert field value of for a taxonomy term I have a taxonomy vocabulary called, school and the machine name is field_school_name. The vocabulary has a field called school id (machine name:field_school_id). I am able to add a verb successfully using the following code. How do I add the field value programatically? I want to add '1234' as the school id associated with the verb 'ABCD' I created.

$new_term = \Drupal\taxonomy\Entity\Term::create([
    'vid' => 'field_school_name',
    'name' => 'ABCD',
]);

$new_term->enforceIsNew();
$new_term->save();

Should just need to do:

$new_term = \Drupal\taxonomy\Entity\Term::create([
 'vid' => 'field_school_name',
 'name' => 'ABCD',
 'field_school_id' => '1234'
]);


How do I integrate custom PHP application with Drupal? I am a PHP programmer but I have never developed anything yet for drupal. I have used Drupal as a CMS before but I didn't do any custom code since everything I needed at before can be accomplished with existing modules.

Now, with my new project, I have an existing single-page app using a PHP RESTful API and AngularJS on the frontend. I want it to be integrated with a Drupal CMS.

I am aware of the following possible ways to do this:

Rewrite my existing code into a Drupal module - There is very little possibility that this app will be re-used. Furthermore, it is more likely that this app will be used stand-alone without Drupal. I also don't think I have the time to learn how to write a Drupal module.
Keep the backend API as it is now and write the frontend as a Drupal page. - This will put my frontend code inside the Drupal database and NOT in the filesytem anymore so I can't version control the frontend code.

I am not happy with the above two choices and I believe that there is a better way to do achieve what I want.

Additional background of my custom app:

I created this app as a way for me to learn more about single-page applications. It is already currently functioning well as a standalone app. The app basically collects information from several users and collates all those information to be displayed on an HTML table.

I am sure there is also a Drupal way of doing the things that my Angular app does (something like a custom node type with fields coming from the input of different users) but I would like to use my existing code if that makes it easier.

If your application can be displayed inside a Drupal page, writing a small custom module is the easiest clean solution. You don't need to rewrite your application, but only to provide some integration code. Your application should avoid output the complete HTML for the page, only its own content. It should also not initialize the PHP session as Drupal will take care of that. Otherwise it is as simple as:

/**
 * Implements hook_menu().
 */
function your_application_menu() {
  return array(
    'title' => 'Your Application',
    'page callback' => 'your_application_page',
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );
}

/**
 * Page callback: Displays Your Application on the page.
 *
 * @see your_application_menu()
 */
function your_application_page() {
   module_load_include('php', 'your application', 'your_application');
   $path = drupal_get_path('module', 'your application');
   drupal_add_js($path . '/js/angular.js');
   drupal_add_js($path . '/js/your_application.js');
   drupal_add_css($path . '/css/your_application.css');
   return your_application_output();
}

You may also be interested by the Angular JS module, which likely provide a much nicer way to embed Angular JS applications in Drupal.


Why does my newsletter keep sending the same copy our time and time and time again? When I send a Simple News newsletter out in Drupal 6, subscribers get as many as ten copies of the same newsletter. The only way I can stop it is by deleting the page. This problem did not happen in Drupal 5 and only started when upgraded to 6. Any ideas?.

The following issue in Simplenews Issue queue Issue #351379: Keeps sending newsletter provides a few troubleshooting options. It is usually created by an invalid email address (that has a dot at the end for example: email@hotmail.com.)

If you have an existing Newsletter that is still sending emails you can stop it in the simplenews_newsletter table, set the s_status to 2 (sent) and empty the simplenews_mail_spool table.


Ajax callback change "checked" radio button I have a radio button group like this:

$options = array('2' => t('Active (2)'), '1' => t('Upcoming (1)'), '0' => t('Finished (0)'));
$form['active'] = array(
'#type' => 'radios',
'#title' => t('Update state:'),
'#default_value' => $default_entry->active,
'#options' => $options,
);

which works fine. However, based on a drop-down list of entries, it calls an ajax function which should update the selection:

foreach (array('name', 'test') as $item) {
$form[$item]['#value'] = $entry->$item;
}
foreach (array('active') as $item) {
???
}

Now, the "name" and "test" work as expected as they are text fields.... but the active radio button stays the same as it was (i.e. based on the '#default_value').

I have tried

$form[$item]['#value'] = $entry->$item;
$form[$item]['#default_value'] = $entry->$item;

but neither change which radio button is selected. Is there something I'm missing based on updating the "checked" attribute for that radio group?

Any help and/or points in the right direction much appreciated.

You would need to show more code (the form definition), I would recommend you to try:

unset($form['input'][$item]);

Right prior to calling:

$form[$item]['#default_value'] = $entry->$item;

Relative links: https://www.drupal.org/node/1082818#comment-5335080


Where is Pathauto's "Strings to Remove" stored in MySQL? I've tried looking in the "variable" table with SELECT name FROM variable but I think it's not there.

Where does the module save that setting?

It's stored in the variable named pathauto_ignore_words, you can get it directly like this:

SELECT value FROM variable WHERE name = 'pathauto_ignore_words'

or using the Drupal API like this:

$ignore_words = variable_get('pathauto_ignore_words', '');


How long does variable_set last? Is variable_set just creating a session variable or can I retrieve this variable from a cron job?

I can load the page over and over, but I always get this output.  It seems as though the data is not pulled from the variables table, but set only manually each page load.

$default_vals = get_defaults_variable_get();
clean_dump($default_vals);

save_defaults_variable_set();

$default_vals = get_defaults_variable_get();
clean_dump($default_vals);
clean_dump($_GET);

function get_defaults_variable_get(){
    $content[sort_direction] = variable_get('inventory_sort_direction');
    $content[threshold] = variable_get('inventory_threshold');
    $content[hide_zero_inventory] = variable_get('inventory_hide_zero_inventory');
    $content[email] = variable_get('inventory_email');
    return $content;
}

function save_defaults_variable_set(){
    //echo 'save defaults';
    variable_set('inventory_sort_direction', $_GET[sort_direction]);
    variable_set('inventory_threshold', $_GET[threshold]);
    variable_set('inventory_hide_zero_inventory', $_GET[hide_zero_inventory]);
    variable_set('inventory_email', $_GET[email]);

}

output

array
  'sort_direction' => null
  'threshold' => null
  'hide_zero_inventory' => null
  'email' => null
array
  'sort_direction' => string 'DESC' (length=4)
  'threshold' => string '5' (length=1)
  'hide_zero_inventory' => string 'true' (length=4)
  'email' => string 'e@sltwtr.com,bsaltzman@gmail.com' (length=39)
array
  'threshold' => string '5' (length=1)
  'sort_direction' => string 'DESC' (length=4)
  'hide_zero_inventory' => string 'true' (length=4)
  'email' => string 'e@sltwtr.com,bsaltzman@gmail.com' (length=39)
  'save_to_email' => string 'true' (length=4)
  'q' => string '' (length=0)

Straight from the docs:

  Sets a persistent variable.

Yes, it will be available across different requests.


How to add text or description in a form without writing a module? In my fictitious content type form, I have this select/radio question:

"Do you want the pie ingredients?"
yes|Yes
no|No

If the user selects "Yes", then a block of text needs to show up

2 spoons of sugar
1 cup of milk
4 cups of flour
etc...

How do I do this without writing a module?  Why can't I create a custom field of type label/text?  I am already using the conditional fields module so I can make the visibility/hidden fields happen, but it only applies to a field.  Is there a way to inject/embed my text into the form?

As far as I know, there is no way to create custom text within a form unless I write my own module, which I would rather not do!

You are on the right track:

Create a new field in your content type of type "Long Text", call it something like Ingredients Text ("ingredients_text") for the machine name --  the text that will be within this field can change per node as you like.
Then, go to your Dependencies tab in this content type.
Click "Add new dependency" and choose your newly created Textfield as the "Dependent".  Choose your select / radio button as the "Dependee". (Leave the other two settings as is.)
Click "Add Dependency"
You are in a new screen, take the defaults
For Node View setting of the edit screen, try "Hide the dependent if the dependee is not viewable by the user and the dependency is not triggered".
Now when you the user is in the node, he can choose the radio button and the new text field will appear!

You will need to play with the settings but this does work, I just set this up on a site for a client.  Note, the options in step 6 may vary depending on your particular setup.


Adding roles to users I added some users to my site.

Is there a way to add roles to thousands of users  at the same time?

Thank you.

you have to install the Views Bulk Operations and Administration views module. After that, go to the users management interface (admin/people), select the users and select "Change user roles".

PS 1: You can select users by role (1 on the attached picture)

PS 2: If you need to select ALL of the users, just click the button "Select all xxx rows in this view" (2 on the attached picture)

2/ For selecting only users without role:

You'll have to modify the Views who handle the display:

Go to http:///admin/structure/views/view/admin_views_user/edit/system_1
On the "Filter criteria" section, click on "User:Roles"
Check the "Expose operator" box
Save and go back to the user selection page
Select the 'Only has the Authenticated user role' on the "Role" dropdown

That should really do it now! :)


Webform in Lightbox, close in submit I have a form (webform) in a lightbox. I created a link:

show Form

and change 'page--node--lightbox2.tpl.php' (tpl from lightbox2 module) for this:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="<?php print $language->language; ?>" lang="<?php print $language->language; ?>" dir="<?php print $language->dir; ?>">

<body id="lightboxnode-<?php print $node->type ?>">

<?php //dsm($node); ?>

<?php if ($title): ?>

<?php print $title; ?>

<?php endif; ?>
<?php
    $nodo = $node->nid;
    print render(node_view(node_load($nodo), 'full', NULL));
?>

How can I do for when I click submit, send the form and close the lightbox?

I would use jQuery to detect the button click on the submit button and then force the action of closing the lightbox with parent.Lightbox.end();.

The reason I would use jQuery to attach to the event is that you don't have to alter the webform in any way, and can do this passively.


Localhost Drupal Install on Linux shows file and not site I am trying to set up a local Drupal install on my Linux 16.04 laptop install for learning/exploring Drupal.

I have made it through this install guide
, completing all steps, but when launching my http://my_example_drupal_site.localhost/web/
I am getting the below output.

Any idea why this is?

/**
 * @file
 * The PHP page that serves all page requests on a Drupal installation.
 *
 * All Drupal code is released under the GNU General Public License.
 * See COPYRIGHT.txt and LICENSE.txt files in the "core" directory.
 */

use Drupal\Core\DrupalKernel;
use Symfony\Component\HttpFoundation\Request;

$autoloader = require_once 'autoload.php';

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

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

$kernel->terminate($request, $response);

Solved

Followed this guide as suggested and got my install working.

Ran into two issues along the way. Turns out when setting up my Linux Box long ago, I had an entry in /etc/hosts/ file that had a name for 'localhost'.

When pointing my browser at localhost, the default Apache "It Works!" page did not work. However when pointing to the name I had in /etc/hosts/ it did work.
But php file would not load and only showed "Index Of /" in the browser.

After more searching, I came to find I needed to load the mod in apache.

Trying:

a2query -m php7.0
No module matches php7.0

did not work, even though it was already installed which I discovered after trying to reinstall it

php7.0 is already the newest version (7.0.25-0ubuntu0.16.04.1)

Finally stumbled upon this answer in AskUbuntu and low and behold this worked for me, allowing me to enable the mod in apache

sudo apt-get purge php*

sudo apt-get install php7.0-mysql php7.0-curl php7.0-json php7.0-cgi  php7.0 libapache2-mod-php7.0

I don't know how or why, but it worked for me.

Just to get the question answered:

You missed the step about setting up Apache and PHP in the installation guide you read. In particular, you have to follow the How To Install Linux, Apache, MySQL, PHP (LAMP) stack on Ubuntu 16.04 guide from DigitalOcean - linked to in the installation guide.


ocupload module functionality I have installed the ocupload module and works very well at my localhost enviroment.

But the problem appears to me when i deployed to the testing enviroment  the upload failed ant the alert message says error 200 - 401.

I walked throw the installation steps well and give the permissions for files .

I know it isn't a module bug but i need help to fix it or catch where the error comes from (running nginx with authentication required by the web server).

thanks in advance

It solved by :

1- give the right permissions for the images folder (where the uploaded images).

2- disable the web server authentication.

hint (if you use ckeditor add the tag img to the text format)


Include Views output in href I am trying to create a custom button in Drupal 7.  The link which the href should be equal to is dependent on the context such as the current UID.

I have created a view which normally has a plain text output as [title].

I want to use that text output as part of a link field such as

http://my-site.com/page/title

so I had written the code for the above link as such:

<a href="http://my-site.com/page/<?php $block = module_invoke('views', 'block_view', 'profile3-block_4'); print render($block[content]); ?>">LINK TEXT

however the output seems as if it is placing part of a views div tag in the link instead. I tried stripping all html from the views block but no success.  Anyone got ideas? Could it be an improper use of quotes?

You can try like this:

$block = module_invoke('views', 'block_view', 'profile3-block_4');
$url = render($block[content]);
Assume your Output will be
TITLE

then use **$url =  strip_tags($url);**
LINK TEXT
It will be better to use **l()**
l(t('Link text'), 'http://my-site.com/page/'.$url);

If you are still facing issue request you to provide block html output.


is there a way to generate dummy content for paragraphs? I am working in Drupal 8. Is there any way, with devel, to generate dummy content for paragraphs to visually get a feel for how things would look? Is there a module or script to accomplish that might work?

Paragraphs need a host entity to work normally iirc, so if the paragraph is attached to a node type through a reference field, I've had success creating them with Drupal console's node generator: drupal create:nodes which seems to populate all the fields it can.

Beware though: I've had to drupal create:terms first to generate a few taxonomy terms, or else the node generation takes ages! Your laptop may take off before the process finishes ;)


JSON API Filter by URL path I am implementing a headless drupal website with json:api as the gateway to get all the data.  I am able to get data by their node ids, but that is only if I knew the node id and type beforehand.  Is there anyway to get the content by just using the url path?

For example, if one visits the url https://mywebsite/article/test I need to be able to use jsonapi to get all the data from that url, but because I don't know what the node id is for that url, I won't be able to retrieve those data.  So, is there a filter I can use for url path using jsonapi?

Edit:  I tried it by using the filter:

https://localhost:8080/jsonapi/node/blog_article?filter[path]=/us/articlepage/testpage&include=field_custom_container

and it gives the following error:

  Invalid nested filtering. The field path, given in the path path is incomplete, it must end with one of the following specifiers: alias, pid, langcode.

Any ideas?

Thanks

With JSON:API you can't filter by path because of technical limitations; JSON:API filters translate to entity queries on field values; because Drupal path aliases aren't fields you can't use the filter query param to look up articles by their alias.

A couple of different Drupal projects have cropped up around this limitation:

Decoupled Router: Provides a new endpoint where a client can query a path for any possible JSON:API resources.
Fieldable Path: Provides a new entity field (and thus queryable via the filter query param) that is designed to mimic the entity's path (with Pathauto support).

You can assess the tradeoffs from both modules and choose the one that makes the most sense for your use scenario.


Show login or register to anonymous user fro flag I created flag for nodes and trying to show a login or register link to anonymous users instead of the flag button on a node page (panels). A redirect to the signup form would be ok as well. I tried the Flag anonymous module but it doesn't work for some reasons.

Are there any other ways to realize this functionality?

If I understand the question correctly:

You should be able, through permissions, to restrict access to the Flags, so that anonymous users don't see it
you could use the default user login block, or create a custom one that redirects users, and place that block in the same position as the Flags, with a message like "To Flag objects, you must first login" and then restrict that block to show only to anonymous users


Anonymous user form submission I have a situation where after doing the basic registration the user is redirected to a page where he needs to fill a small form.

I aim at implementing the hook_user_insert() and hook_menu() to do something like this

function registration_user_insert(&$edit, $account, $category){
  drupal_goto('splan/'.$edit['uid']);
}

function registration_menu() {
  $items['splan/%'] = array(
    'title' => 'Select a Plan',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('selectplan_form'),
    'access callback' => TRUE,
    'type' => MENU_CALLBACK
  );

  return $items;
}

In selectplan_form() I will define my new form and then, using the user ID, I would save data into user table.

The basic user registration form is being submitted, the user is redirected to splan/uid, but I also get the following error.

  You are not authorized to access this page.

I have changed permissions to allow anonymous users to create and edit webform, but the problem still persists.

Implementing hook_user_insert() this way (calling drupal_goto() inside) is plain wrong:

if there are any other implementations of this hook in other modules meant to be called after yours, they will not get called at all
if for whatever reason hook_user_insert() from user module will not be called before your implementation, the user will not be saved at all
if you look at user_save() function in user.module, you'll see that after invoking 'insert' hook there are many other things this function is doing, so if you use drupal_goto(), they will not be done.

What you can do though is to add your own submit function to user_register_form, and in that function set $form_state['redirect'] to wherever you want (note that updating $form_state['redirect'] in hook_form_alter() will not work in this case, as user_register_submit() sets its own redirect, so you need to do it after this - hence the need for your own submit).


Unable to generate html using theme_table in block view I have created a block_view, In that block I want to show dynamic table.

I have written following code.

$table_headers = array(t('User'), t('Relation'),t('Period') );
foreach ($result as $row) {
            $table_rows[] = array(
            $row->name,
            $row->relation,
            $row->period_from,
           );
         }
 dpm($table_rows);

In above $table_rows array, I am getting following elements

If I am using

$table_html = theme_table($table_headers,$table_rows);
$block['content'] = $table_html;

then getting following error on page

The website encountered an unexpected error. Please try again later.

If I used

$table_html = theme('table',$table_headers,$table_rows);
dpm($table_html);
$block['content'] = $table_html;

I am getting following html on page

Please suggest were I made mistake and what should I do.

Assuming Drupal 7, and assuming $table_rows and $table_headers contain valid data, this is what you need:

$block['content'] = [
  '#theme' => 'table',
  '#rows' => $table_rows,
  '#header' => $table_headers,
  '#empty' => 'Nothing to see here...',
];


How do I enable users to have a browse button (by clicking on the image icon)so that they can upload a picture. I added a user to my website and I gave him the permission to use blocks.
I activated wysiwyg and TinyMCE so that he can add also images.

But he has a problem, when he clicks on the icon to add an image then it opens a window where u can add the image url, image description,... but there is no browse button so that u can upload a picture.

thank in advance!

You need a  combination of the imce module and imce bridge module to do this

IMCE

  IMCE is an image/file uploader and browser that supports personal
  directories and quota.

IMCE BRIDGE

  Allows to use IMCE module with Wysiwyg module.


Where to query database in a module I'm creating a module that is basically a form but needs to use information from a table in the database to react the some of the button presses. Rather than executing the database query each time the button is pressed in the callback function, is there a way to retrieve all of the information from the database when the module loads and store it in a variable so that other functions in the module can use/access it?

Thanks in advance

Code: An example module that is similar to my current one. I need to use results from the database query in the copy_text function, and as I build the form up the same results in the callbacks for the other functions, so I don't see a point in putting the same db_query in each callback - surely that's just unnecessary querying of the database:

<?php

function playground_menu() {
  $items['playground/form'] = array(
    'title' => 'Form',
    'description' => '',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('playground_demo_form'),
    'access arguments' => array('access content'),
  );
  return $items;
}

function playground_demo_form($form, $form_state) {

  $form['input'] = array(
    '#type' => 'textarea',
    '#title' => t('Input text'),
    '#prefix' => '
',
    '#attributes' => array(
      'placeholder' => t('Enter some text here... '),
    ),
    '#suffix' => '
',
  );

  $form['buttons'] = array(
    '#type' => 'fieldset',
    '#title_display' => 'invisible',
    '#attributes' => array(
      'style' => 'border: 0px; text-align: right',
      'class' => array('container-inline'),
    ),
  );

  $form['buttons']['copy'] = array(
    '#type' => 'button',
    '#value' => 'Copy text',
    '#ajax' => array(
      'callback' => 'copy_text',
      'wrapper' => 'out-text',
//          'method' => 'replace',
//          'effect' => 'fade',
    ),
  );

  $form['buttons']['reverse'] = array(
    '#type' => 'button',
    '#value' => t('Reverse text'),
  );

  $form['buttons']['clear'] = array(
    '#type' => 'button',
    '#value' => t('Clear text'),
  );

  $form['output'] = array(
    '#type' => 'textarea',
    '#title' => t('Output text:'),
    '#prefix' => '
',
    '#value' => '',
    '#attributes' => array(
      'placeholder' => t('Your text will appear here...'),
    ),
    '#suffix' => '
',
  );

  return $form;
}

function copy_text($form, $form_state){
  $form['output']['#value'] = $form_state['values']['input'];
  return $form['output'];
}

You've got two options, depending on your needs

Static cache - data is built once during a single request and re-used where needed. Your query will run once but once only on every related request. See drupal_static() for example usages.
Backend cache - the results of your database query are cached, and you query the cache bins for the data instead of your database table. Your query will be run once only, until the cache is invalidated, when it'll obviously need to be run again. You'll still incur the overhead of querying the cache, so if your cache is database-based, this may or may not be worth it, depending on the size and complexity of your data. With this method you'll also need to think about how/when/if you invalidate the cache to get fresh data. See the Cache API docs for examples.


How can I allow the user to choose their language upon registration? There is a solution for showing the site language selection field on the user/register form in Drupal 6 here:
https://stackoverflow.com/questions/5556895/how-to-add-language-switcher-in-user-register-form-in-drupal-6

However, I'm personally not able to convert this to Drupal 7.  Is there another way to do this?

EDIT: When multiple languages are enabled via locale, the "Language Settings" with the list of user languages is shown on /admin/people/create.  This is what I want-- except I want this to be shown on /user/register, where it is not (at least by enabling locale alone) shown by itself.

As Drupal 7 doesn't show the language selector for the users who create their own account, you need to implement hook_form_user_register_form_alter() (see the documentation for hook_form_FORM_ID_alter()) using the following code.

function mymodule_form_user_register_form_alter(&$form, &$form_state) {
  // Only alter user forms if there is more than one language.
  if (!isset($form['locale']) && drupal_multilingual()) {
    locale_language_selector_form($form, $form_state, $form['#user']);
  }

  if (isset($form['locale']) {
    $form['locale']['#access'] = TRUE;
  }
}

The code is generic, and works even in the case a module removed the language selector field (which is something a module should never do, though).

"user_register_form" is the form builder used for the "user/register" path. The code works if the Locale module is enabled. The code will show the language selector if there are more than one language enabled; differently, drupal_multilingual() would return FALSE.

  $items['user/register'] = array(
    'title' => 'Create new account',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('user_register_form'),
    'access callback' => 'user_register_access',
    'type' => MENU_LOCAL_TASK,
  );

The code used from the Locale module is the following one.

function locale_form_alter(&$form, &$form_state, $form_id) {
  // Only alter user forms if there is more than one language.
  if (drupal_multilingual()) {
    // Display language selector when either creating a user on the admin
    // interface or editing a user account.
    if ($form_id == 'user_register_form' || ($form_id == 'user_profile_form' && $form['#user_category'] == 'account')) {
      locale_language_selector_form($form, $form_state, $form['#user']);
    }
  }
}

In general, the equivalent for hook_user('register') in Drupal 7 is hook_form_user_register_form_alter(); the equivalent of hook_user('form') is hook_form_user_profile_form_alter().


Slider via uploaded Image on each node + Fallback I want to create a slider block shown on every page filled with the images uploaded to the active Basic Page, Article, ...
On these pages just the Uploaded Images of the active page should be shown and if there are no images uploaded (e.g. on View pages, Taxonomy pages, ...)
a fallback Slider should be shown.

I've added a Imagefield called Sliderimage to the Basic Page (and the others), created some pages and uploaded individual images to them.

Then I've created a view block with the following settings:
Format: Slideshow (default values from views_slideshow)
Show: Fields
Field: Content:Sliderimage - Rendered File, Original, Display all values in the same row (no seperator)
Filter Criteria: Published
Contextual filter: Content: Nid

But somehow the node id seems not to be delivered to the filters (or I misunderstood it) because
at the contextual filter I choose "Display all results for the specified field" at WHEN THE FILTER VALUE IS NOT AVAILABLE I get all at the different
pages and with "Hide view" I get nothing would would be right.

If the above issue is solved I want to add  the fallback at "WHEN THE FILTER VALUE IS NOT AVAILABLE" as fixed value or php code.
Would that be the right way?

Solved because I've found out that block views don't retrieve node-ids by default.

You have to set at "When the filter value is NOT available":
- Provide default value: with type "Content ID from URL"

Now the block view recognizes the ID as well.


Force Image module to regenerate thumbs I am using the Image module along with ImageGallery to make galleries in Drupal 6. I now have some 'holes' in my gallery where Image can't find the thumbnails, so they need to be regenerated. How do I force that to happen? Have tried clearing caches and running update.php, but I still have the holes. Am I missing something?

Probably the easiest way is to just go to the ImageCache Styles page and re-save the style. Don't make any changes just hit save.

You could also just delete all the thumbnails out of the image_styles folder in your files/ directory.


Drupal Node view modes I have setup multiple new view modes for a specific node. Full,Teaser,New Teaser,Custom Display.

Is there a way to view the same node with different URLS for the different view modes. Please let me know if i need to explain further.

Hopefully this makes some kind of sense.

If you would be okay with having a parameter in the url control your view mode then you can add this code to your custom module using hook_entity_view_mode_alter().

For example:

http://www.yoursite.com?view_mode=Full

http://www.yoursite.com?view_mode=Teaser

.....

/**
 * Implements hook_entity_view_mode_alter().
 */
function my_module_entity_view_mode_alter(&$view_mode, $context) {
  // If there is a view_mode parameter in the url change the view mode to it.
  if (isset($_GET['view_mode'])) {
    $view_mode = $_GET['view_mode'];
  }
}


Send email grouped on a commerce line items field I use commerce a little different than most as I schedule trips as custom line items.

A trip is scheduled by someone else and they can schedule as many trips as they want for however many users they want.

I am trying to send an email to the user that had a trip scheduled.

My problem is that a user can have multiple legs (line items) on a single order.  So when I try to loop through the line items, it sends out an email per line item (which it should) but to the user it is a duplicate.

I want to use rules to send an email out once.

Is there a way to group the line items on the user as a result and then just send one email out?

I think I found the solution to this.  I should be able to load the list of line item entities using VBO and a view grouped on the user.  I got the information needed from here:

http://nodeone.se/sv/node/777

Then I just pass the [commerce-order:order-id] as an argument.

EDIT
This worked for me.


How to set and retrieve cookies? After several days and more hours I only found issues and patches about what to do once a cookie is set, but not one is mentioning how you get a cookie set in the first place.

Our intention would be to set a (session) cookie of the landing page (for ALL user roles) and retrieve that cookie on certain pages, through views, to use in the URL of an outbound link.
This would be very simple in standard programming (even I understand) but I am starting to have considerable doubt if this is actually possible in Drupal.

Drupal already sets a session cookie when a user logs in: see the function drupal_session_regenerate().

Can you use this session Id for your purposes? If not, then you just need to create a new value in the cookie the same way that you will do in PHP, $_COOKIE['my_value'];. Place this code in the hook_init() of a custom module, adding a if() to filter the landing page.

Later, you retrieve it and use it in your view; you can use some of the hooks of Views depending on your needs. You can also use the module Views custom field, and embed your PHP code there.


Old site migration and keeping links (as aliases) I'm migrating an older site into Drupal 7 and have had a lot of success so far. One item where I'm stumped is on links to user profiles. The older system would link to teachers via

site.edu/faculty.php?PID=FirstnameLastname

Might there be a way to effectively copy that URL as the page's alias faculty.php?PID=FirstnameLastname? And yes, is there a way to escape the http encodings (?, =, and &)?

There's no real need to escape the URI string.

Here's one way to handle this:

In a custom module, implement hook_menu(), creating an item for the path 'faculty.php'
In your php function callback for the above path, look at the PID value, look up the new path (you do have a database table mapping old content to new content, right? :) ), and do a 301 redirect.

Another approach is to do this lookup on all 404 pages with something like the following code in a hook_init():

function hook_init() {
  if (!menu_get_item($_GET['q'])) {
    $pid = isset($_GET['PID']) ? $_GET['PID'] : FALSE;

    if ($pid) {
      // lookup new path and 301 to it
    }
  }
}


How to set form action to default contact form action I'm editing a Drupal site, it has a hardcodeded contact form which I would like to have the same behaviour than the default contact form (applying filters, inserting info in the database and sending email).

Maybe it is an easy question but I don't know how to do it.

Thanks!

I not sure will this help you. If you have no other solution, how about try to use webform module with form builder. I not sure what you mean filter, but its help to store in database and send email easily.

Hope this help you.


How to ask anonymous to confirm their flag by email? I need to add Flags to one of my content types. Two kinds, actually:

I'll take care of it
Solved

Second flag should be available only to node author, and only if first one was already raised. But that's simple part. First kind of flag is trivial for logged in users, too.

The point is - I need to make first kind of flag available for anonymous users, too. And I need to make sure I have their valid email addresses. Standard confirmation link in mail would be OK - so how do I do that?

I know I can develop custom module from scratch, and I will if needed, but I was sure there is already a out-of-the-box solution, and I simply can't find it now.

Just to make some things clear:

Flag module works for anonymous users if you install Session API. No problem here.
I planned to keep emails in Email Field attached to flag itself. For logged in users it defaults to their email, and if they decide to change it, so be it, I have a way to reach them anyway. For anonymous, I want it verified by link in email, and if it is not verified in time, I want to delete flag. Deletion will be easy with CRON and Rules or simple helper module, it's verification that's complicated (and I hope solved already).

I would use hook_flag_link_type_info() to provide a link type like the 'confirm' link type provided by the flag module. Copy their approach, but on the 'confirm' form you ask for the users e-mail address (if the user is anonymous). You save the value to the email field you added to your flag and the Rules module should be able to do the rest for you. It requires a bit of custom code (not too much I would guess), but the major part of the functionality (flagging, unflagging, rules integration, ...) still comes from the Flag module.

[EDIT] For the verification part: Add a boolean field to your flag ('Verified') which you change with the verification link you send by mail. The "Solved" flag can be hidden/shown with hook_flag_access().


Recording the time it takes to process a form I have created a form that has a submission button on it. Is it possible to record the time that the submit button is pressed and then, once the form has run, display how long it took to process on the page?

I use HttpWatch to monitor load times:

http://blog.httpwatch.com/2008/05/14/using-httpwatch-to-measure-page-load-times-for-new-and-existing-users/

You should be able to get the numbers you want with the free version.


Can I "drush rsync" with "chown @ destination"? I understand that drush rsync is, by design, capable of preserving uid:gid.

if I am synchronizing with drush rsync @site1 @site2, and uid:did exists on both site1, and site2, all is well.

How would I go about changing the uid:gid to a specific selection on site2, within drush's command/alias config?

For example, on site1 all files are wwwrun:www, but on site2 I want to save all files as bob:admins, neither of which exists on site1.

Is there an integrated solution?  I know I can use 'drush ssh @site2 "chown ..."' as a subsequent step. Can I instead define/chain the command in aliases.drush.rc?

Using "remote-user=xxx" certainly works, but, apparently, it is limited to users that are allowed SSH access on the remote box.

@ remote
egrep -i "allowusers" /usr/local/etc/ssh/sshd_config
    AllowUsers         root locuse testuser

@ local
whoami
    locuse
drush --remote-user=testuser rsync @siteA @siteB
    You will destroy data from locuse@siteB.loc:/srv/www/siteB/ and replace with data from /srv/www/siteA//
    Do you really want to continue? (y/n): y

@ remote
ls -al PROD/ | head -n 5
    total 248K
    drwsrws--- 10 testuser users 4.0K Mar  8 00:08 ./
    drwxrwx---  4 wwwrun   www   4.0K Mar  8 08:11 ../
    -rw-rw----  1 testuser users 6.5K Mar  6 17:31 authorize.php
    -rw-rw----  1 testuser users  64K Mar  6 17:31 CHANGELOG.txt
    -rw-rw----  1 testuser users  996 Mar  6 17:31 COPYRIGHT.txt

That doesn't address my particular issue/interest.

More clearly, what I want to do is ssh-in from local->remote as an authorized user ('locuse' or 'root'), but I have the remote files' uid:gid set to an existing pair, where the target uid does/will NOT have ssh-access (e.g., wwwrun:www).

Reading the output of "man rsync," I read:

  USING RSYNC-DAEMON FEATURES VIA A REMOTE-SHELL CONNECTION

Then @siteB

mkdir -p            /path/to/target
chown -R wwwrun:www /path/to/target

vi /etc/rsyncd.conf
    transfer logging = true
    log format       = %h %o %f %l %b
    log file         = /var/log/rsyncd.log
    pid file         = /var/run/rsyncd.pid
    lock file        = /var/run/rsync.lock
    hosts deny       = *
    use chroot       = no
    [siteB]
        path = /path/to/target
        hosts allow = *
        comment = COMMENTS
        uid = wwwrun
        gid = www
        read only = no
        list = yes

and @local

whoami
    locuse
ls -al ~/SourceDir
    total 240K
    drwxrwxrwx  2 locuse users 4.0K Mar  8 10:42 ./
    drwxr-xr-x 27 locuse users 4.0K Mar  8 10:41 ../
    -rw-r--r--  1 locuse users 5.2K Mar  8 10:43 file1.txt
    -rw-r--r--  1 locuse users 2.8K Mar  8 10:43 file2.txt

rsync -av --rsh=ssh ~/SourceDir/ root@siteB.loc::SiteB

Checking on remote:

ls -al /path/to/target
    total 240K
    drwxrwxrwx  2 root   root 4.0K Mar  8 10:42 ./
    drwxr-xr-x 27 wwwrun www  4.0K Mar  8 10:41 ../
    -rw-r--r--  1 wwwrun www  5.2K Mar  8 10:43 file1.txt
    -rw-r--r--  1 wwwrun www  2.8K Mar  8 10:43 file2.txt

It ends up with exactly the end-state I'm after.

If you do not tell rsync to preserve the uid, then it will create all transferred files under the ownership of the user that you connected as.  The key, then, is to make sure that you put 'remote-user' => 'bob' in the site alias for your destination site.

The rsync flags I use to achieve this are -rlptz.  So, in my drushrc.php, I have:

$command_specific['rsync'] = array('mode' => 'rlptz');

See also:

http://drupal.org/node/1169776#comment-4612944

http://drupal.org/node/1343892

Supporting rsync modules in Drush would be awkward. If you want to use modules, it's probably best to call rsync directly.  e.g.:

rsync -av --rsh=ssh drush dd @siteA root@siteB.loc::SiteB

You would need to configure your SiteB module to point to the Site B Drupal root anyway, so it seems like there is little value to tying this to a site alias.


Change control using CVS We're looking to manage our install of Drupal 7 with CVS (sadly Git and SVN are out). Do you have any pointer for things to think about when setting up the repositories?

Our lay of the land is as follows:

Our staff include UI developers, back-end developers , administrators, and DBAs.
For starting, we're going to install various modules (e.g. Domain, LDAP, Workflow, and Views). We'll write some custom modules down the road. We're also looking for implementing our own look and feel.
We have Dev, Test/QA, and Production instances of Drupal. The flow of code and configurations  will be from Dev to Test/QA to Production (with some looping between Dev and Test).
We'll have top level domains and several subdomains.
We're on RedHat Enterprise Linux 5.5, MySQL 5.x and Apache 2.x.

What are the ways of managing changes that have worked for you?

Regardless the used VCS, here is what I put in my code repository

A .make file used to download Drupal core, contrib modules and contrib themes and apply patches (if required)
a module folder with only the custom modules
a themes folder with only the custom themes
A build script to

run drush make on the .make file to download Drupal core and contribs to a (VCS ignored) dist folder
copy the modules folder to dist/sites/all/modules/custom
copy the themes folder to to dist/sites/all/themes/custom

This to

properly track changes to the custom code
properly track used core and contribs versions (in the .make file)
prevent core or contribs hack
allow proper patching (Drush Make requires the applied patches to be on publicly accessible)

For the build script, I use Phing but any scripting languages (ant, bash, php, ruby, etc.) could be used. With some additional work, the build script can also be used to run automated test (SimpleTest) and code validation (php -l and Coder Review).

I try to have as much configuration as possible exported into code. Mainly by using exportables through the Features module and by having a project specific profile to define and update non-exportable configurations through its hook_install and hook_update_N implementations. See The Development -> Staging -> Production Workflow Problem in Drupal and the Code driven development: using Features effectively in Drupal 6 and 7 presentation.


Exclude taxonomy term from view display except its own? I work on a news publisher site and I need help excluding a taxonomy term from view but still to keep it with its own page.

E.g. Our content is organised by theme and region. For one set of articles I've added a certain tag to it. I would like to exclude articles with this tag from all region and theme view display pages, but still maintain a page with only this tag's view display. So that these certain articles will not display on the theme and region displays (though they are organised into such categories), but still display on the tag page.

So exclude tag: xyz from all pages except www.site.com/xyz

My problem is that when I filter criteria for the tag, it removes all articles from the tag's own landing page.

It would be simpler to just not give these certain articles regions and themes, but we need these to be organised as such on the back end and for future use.

Thank you in advance!!

You seem to be on D7 and using the default Taxonomy term Views.

Out-of-box Taxonomy term Views is set up to cover all taxonomy Vocabularies you create on your site.

You can override this to "split" that functionality into more than one View, that have different settings, and control which Views is responsible for displaying which Term pages.

BTW I find it best to disable the original Taxonomy terms view, Duplicate (Clone) it and work on the Duplicate so I always have the original to reference back to.

On D7 this is usually done with the help of the Taxonomy display module although this module only provides a convenient interface for adjusting each term, but it doesn't provide the "splitting" on the Views level.

You'll have to create the second View yourself, and edit the original Taxonomy term views to exclude that special term yourself.

In the original Views you can add another Contextual filter, set it to the fixed value of the ID of your xyz term, and under More set to Exclude. This way no articles tagged with this term will appear on other term pages.

Clone the Taxonomy terms Views, name it meaningfully, and override values for the Contextual filter to only show content for the xyz term (I'm guessing ti will again be the fixed default value, but without Exclude).

You mention regions and themes a lot, but that is not how you usually control filtering in Views. So if you have more than one View listing content where you want to exclude the special xyz tagged content, you'll have to edit each view to filter out that content. There is no easy way to filter according to theme regions that I'm aware of.


No Schema type for mysql type datetime error while creating view to show webform submissions I am attempting to display webform submitted data in view. For that I have used Webform MYSQL Views and Data module. And I am referring tutorial from here: http://drupal.org/node/1658784. The problem is when I created MySQL views for given webform, it has created view with Submitted column as datetime field.

Now when I go to Structure > Data Table > Adopt Tables and selects the created view, it is giving error of "no Schema type for mysql type datetime".

I googled for it, but didn't find any solution yet, any suggestion how can I overcome this error.

-- Thanks for your time.

You likely already resolved this, but I just ran into the same issue.  Here's how I resolved it:

I applied the patches to the Schema module listed here: http://drupal.org/node/1237974.

This got rid of the error, but because i had a db_prefix on my tables, I could not adopt them.  In order to get that working, I tried the patches here (http://drupal.org/node/894074#comment-6459584).  It didn't work for my view, so I logged in via PHPMYAdmin and removed the prefix dr_ from the webform view (instead of dr_webform_myviewname, it's now webform_myviewname).  This allowed me to adopt it.

I'm not saying it was pretty, but it is working now.

KMT


phpBB 3.0.10 to drupal 7 I have a phpBB 3.0.10 site i want to migrate all the contents of the site to drupal 7.

I want all my users to import from phpBB 3.0.10 to users of drupal 7.

All the forums should be migrated to drupal forums along with their groups and access rules in the phpBB forum.

The users groups should be mentioned.

All the posts and comments should also be imported.

I have tried modules phpbb2drupal and phpbbforum but i was not able to completely migrate it to drupal.

After the migration i will be leaving phpBB 3.0.10 and only be working on drupal 7.

Is there a solution, i have been searching but couldn't find the right solutions.

Thanks for the help...

use the module migrate, be sure you studied the example and modules like TYPO3_migrate or Wordpress migration.

Migrate has a learning curve, but it is worth it.


How can I filter entity titles in an autocomplete form and use the title as context for a View page? I am trying to provide a form with a single autocomplete text field on the front page.  The user can search for a title of the product (commerce_product), and when they submit, they're redirected to a views page with the title as context.

These are baseball cards from multiple sellers, so there can be many cards and variations of a single card with the same name, e.g. multiple sellers sell a "Barry Bonds" card.

When the user enters the name of the card and submits, I need to redirect them to a views page to display all the cards for that particular title (card name).

The part I'm trying to figure out is how to use the selected title on the front page and send the user to a views page with that title so I can use it in a view. I assume that would be a Context, but I'm not having success finding how to do that.  To clarify the flow:

User hits front page and searches for a product title.
The user submits and is redirected to a views page.
On the views page, the user can browse all the cards under that title.

Here's how I solved my problem:

Added an ID field (the ID from the source I'm pulling/validating player names) to my variation.  On creation of a variation, I store the ID in the field when the user selects the player name during product creation, e.g. "Barry Bonds" is ID 35456 in my source.
I'm using a regular autocomplete route in my form instead of an entity_autocomplete.  My autocomplete handler does an entity query on cards (product variations) that are active and match the player name.
After the player is selected from the autocomplete, on form validation, I re-select the player to get the ID.
On form submit I pass the ID with the URL to my views page as a contextual filter, where it expects it as a field value in the URL, e.g. "/player-card-search/35456".

Creating the new ID field in my product variation feels redundant, but it got me to the solution.


file field properties drupal7 I'm building a library and it is possible to add books to website. I need to get uploaded file urls and display them in 'a' tag inside views page (not node). how can I do that?

unfortunately I can't use kpr() to find file properties I guess because it has lot's of outputs and it prevents the page from loading (var_dump does the same thing)

I also tested this function to print the file size but it failed

function MYT-HEME_file_link(&$variables) {
$file = $variables['file'];
print $file->getsize();
}

You can follow the below steps

Create a Relationship of the type "File Usage: File"
This will bring up additional Fields. You can add the filed called File: Path (Path) and select the above relationship.
Check "Display download path instead of file storage URI" This would give you the entire path. You can use the same any where in the view.

Once you add the relationship you would get additional fields related to the file. For example if you want to print the size of the file you can use the field "File: Size" etc.