Configuring Commerce in an existing drupal install I'm running drupal 7 and would like to add the Commerce module to my site and am having problems with basic functionality. I've created a product display with views, but I'm unable to figure out how to add an 'add to cart' button to item listings, as well as how to add a checkout page.

Just about everything that I've found suggests using kickstart from a clean installation but that isn't an option for me. The documentation seems to be missing gaps of information relating how to set up blocks which normally would be included in commerce kickstart.

What is a good place to start learning about the basic module so I can get my cart up and running?

I would recommend that you install and play with Kickstart 2 in order to study best practices and find out what contrib modules you need for the most common Drupal Commerce features.

To install Drupal Commerce on any existing Drupal site, start by first installing its dependencies, and then activating Commerce modules in the order indicated here. Also, make sure that you activate all the Commerce UI modules. This should get you to the point where you can create basic products, orders, and a checkout workflow.

You should first learn about the separation between product displays and products here.
In short, you need to create a new node type, let's say "Product display". For it to act as a product, you need to add a "product reference" field and configure it to suit your needs. Make sure that on the "Manage display" section of your Product display you have selected the "Add to cart form" format for your product reference field. Your view should display products with add to cart forms as long as you configure it to display nodes of type "Product display" with the correctly configured view mode.

After you understand the concept, I fully recommend installing Inline Entity Form. It will spare you the effort of explaining the above concept to your clients, and make their life much easier.


Installed Bluez theme as a sub-theme but can't change Appearance Settings I'm using the Bluez theme (in D7). I created a sub-theme from it. It doesn't have a starter kit or anything so I just turned it into a sub-theme by creating an .info file, etc.

Things are working fine so far, but when I try to make any changes to the settings in 'Appearance' under 'Bluez Theme Settings' ... make the changes and then click 'save configuration' > it says the 'configuration options have been saved' but ... they aren't.

Any idea what might be happening here? I'm thinking maybe there are template files I should be copying over to my sub-theme folder or something. Or maybe you can't create sub-themes out of themes that don't support sub-theming?

In one of your comments you wrote you created your my_bluez folder within the "sites/all/templates folder".

If that's really the name of the folder where you created the my_bluez subfolder (i.e. that it is not a typo in your comment here), then I wonder what result you would get if you would rename that folder to "sites/all/themes". Because that would make it comply with the Community documentation about Installing themes (bullet 3 in that list there). It would make it even  harder to realize for Drupal that my_bluez theme is actually like a clone of the Bluez theme, no?. Just to be sure, after renaming that foled I'd then also clear the Drupal cache.

If that still doesn't work, then I wond if it could be related to some (missing) file permissions of that newly created folder.

Does this help somehow?

PS: Creating a "clone" seems to me like a better term of what you're trying to achieve. Creating a sub-theme is really something related to base themes in Drupal-eze.


duplicate taxonomy array being called I am working on a music site with a couple other programmers who have left.

We are using taxonomy terms or "tags" for each node, to determine the url/subdomain the node will be shown, on effectively creating different subdomains of content.

There is only one debug statement in the code, and even if there was another hiding somewhere, it does not explain why it shows two different arrays from the same taxonomy on the homepage.

I use the following code to reveal what terms are associated with the node:

 $terms = array();

 foreach($node->taxonomy as $term) {
   $terms[$term->name] = $term->name;
 }

 print 'debug:
' . check_plain(print_r($terms , 1)) . '
';

I get the following output:

    debug:
    Array
    (
        [national] => national
        [nyc] => nyc
    )
    debug:
    Array
    (
        [national] => national
        [nyc] => nyc
    )

Why is it showing 2 groups of arrays from the same taxonomy? The posts are only tagged once with these two tags "national" and "nyc."

Also on any nodes tagged with only "national," "washington" shows up as well in the duplicate array. I think it may be coming from another content type because when I performed a redirect on the node, using

unset($terms['national']);
      $value = array_shift($terms) ;
      if($region != $value) {
        $link = 'http://' . $value . '.thedelimagazine.com/' . drupal_get_path_alias("node/$node->nid", $path_language = '');
        drupal_goto($link, $query = NULL, $fragment = NULL, $http_response_code = 301);

it redirected to a different content type "CD of The Month." using term "washington" it should choose the other term in the first array; in the case above "nyc."  and go to the same node type in this case "blog,"  I performed this redirect using drupal_get_path_alias for other logic cases and it worked fine.

debug:
Array
(
    [national] => national
)
debug:
Array
(
    [national] => national
    [washington] => washington
)

The debug is called inside this function

function region_filter_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {
  /*global $user, $base_url;*/
  switch ($op) {

    case 'view':

      if( (arg(1) == 0)){ }

      else {

The site is http://www.thedelimagazine.com.

Is this in a hook function? It's possible your hook function is being called more times than you expect which gives you your extra debug statement.


Folder permission errors on public:// after upgrade to 8.8.5 I'm new to this community, and asking for help because I'm stuck on this problem, and cannot go past. I've also tried asking on StackOverflow, but with no luck so far.

My current setup:

Drupal 8.8.5
CentOS Linux release 7.5.1804
PHP 7.2.19 and HTTPD - Apache/2.4.6
Run user/group: apache:apache

The /admin/reports/status#warning admin page reports that "the sites/default/files directory is not writable. You may need to set the correct folder in the configurations of the File system page or change the permissions of the current folder so that it is writable."

Obviously, this leads to a number of errors:

Drupal\Core\File\Exception\FileException: Failed to unlink file 'public://css/css_Y3zRgmC0P7yIXk_w_H9qyrPs3aMkKRv44SMfupbSCMc.css.gz'. in Drupal\Core\File\FileSystem->delete() (line 340 of/var/www/html/project/core/lib/Drupal/Core/File/FileSystem.php).

Warning: unlink(/var/www/html/project/sites/default/files/css/css_Y3zRgmC0P7yIXk_w_H9qyrPs3aMkKRv44SMfupbSCMc.css.gz): Permission denied in Drupal\Core\File\FileSystem->unlink() (line 124 of /var/www/html/synergie/core/lib/Drupal/Core/File/FileSystem.php)

The specified file 'temporary://fileuJjxaE' could not be moved to 'public://js/js_FKKJ_OhNvc7muQ1i_fQS6OJmZLsZnRvVhbbPaVlNwb8.js'.

Permissions for the file cannot be set for sites/default/files/translations

Now, I'm not a full expert on Drupal, but I've already tried doing all the possible basic things that these situations require on a linux system:

Setting all 777 to /var/www/html/project/sites/default and subdirectories
Changing owner of the directory aforementioned
Manually debugging lines 124 and 340 of lib/Drupal/Core/File/FileSystem.php
Sudoing on "apache" user with sudo -s /bin/bash apache and try to create/delete files from the command line (and it works)
Writing custom scripts that run under apache:apache, outside Drupal, to see if they can manipulate public://. (they work)

I think the problem is not in the filesystem itself, because whatever combination of permissions doesn't work, I believe this problem is connected to Drupal itself.

Fact is, if I write a custom script to write/read/move files from/to the /var/www/html/project/sites/default/files, it just works. It doesn't work "from within" Drupal.

As said before, I'm not a expert of all the "under the hoods" of Drupal like file settings, admin settings, drush, so I'm asking to you to try and issue this problem, because it's driving me crazy. Spent the last 10+ hours watching the command line and not understanding what's happening.

Kind regards,

Maurizio

Update:

Find current mode of SELinux and temporarily shut it down. "#" is for comment and can be removed.

Getenforce # see current mode.

getsebool -a # find al boolean values

Sudo setenforce 0 # shut it down, but will be back at reboot.

Try your thing.
If that’s cause, just add rule to allow locations like /var/www/your Docroot.

SElinux will come back with reboot so to add a permanent rules for /var/www/drupal-document-root.

I do the following.
Line 2 will work but won't survive rename & restorecon
(line 3 will survive such things).

 ls -dZ /var/www/html  # See SELinux context of
 sudo chcon -R -t httpd_sys_content_t /var/www/html/drupal-document-root
 sudo semanage fcontext -a -t httpd_sys_content_t "/var/www/html(/.*)?"

I have also done the following in the past to give apache write permission.

# Selinux allow httpd read & write to /var/www/html/my-project
sudo chcon -R -t httpd_sys_script_rw_t /var/www/html/my-project/
sudo chcon -R -t httpd_sys_script_rw_t /var/www/my-Symfony-project/var/log/

SELinux references:
https://access.redhat.com/documentation/en-us/red_hat_enterprise_linux/7/html/selinux_users_and_administrators_guide/sect-managing_confined_services-the_apache_http_server-types

Beside that, the following is what I do when I setup new site and run into this kind of thing.

1) cat /etc/http/http.conf | grep user , to see user Apache is running as
2) from the vhost file, check the document root
Then follow it and make sure Apache can write to it
3) Check your docroot or Symlinks
Post and show the following
1&2& then l would love to see
Ls -al /document root that Apache is pointing to
And output showing Apache user is in right group

Don't forget to reset your drupal permissions to the best practices after resolving the issue. look at 2nd answer of the following.

What are the recommended directory permissions?

Ps: assuming your not setting up multisite as few more things will be needed.


How to show a block on specific content type and combine it with path restrictions How do I show a block on all nodes of content type A, without restricting it to other "pages"? I already have some restrictions based on the path. The problem is that by using the settings under Visibilty > Content Type, the block disappears from other places where the block is defined. I want to combine it with showing this block on all nodes of Content Type A.

With D8 you can make multiple instances of the same block, just use Place Block to place another copy of it. Then you can have one display on the specific content types, and the other display on the pages you need.


A field that is a multiple of a float field. How? Let's say i have a product content type. It has a title, body and price field.

In a view (or in the node page) in addition to these fields I would like to have a multiple of the price field ?

Example :

Title : Red tshirt
Body : Tshirt description
Price : $9,95
Extra field : $99,5 ( Price x 10 )

The easiest way would be to use the Computed Field module. Use something like:

if ( isset($entity->field_price)){
  $entity_field[0]['value'] = ($entity->field_price[0]['value'] * 10);
}

in the Computed Code (PHP) box.


Display google map based on coordinates I've a node with field that store coordinates (in a field with type Geofield).

Now I want to display google map block on page based on coordinates in that field. How should I do it? IS there any module that provide such functionality.

I decided to use gmap module as it provides widget to change Display format for my geofield.


URL with "en" for english language does not work I did implement the multilingual. I have successfully translated the content and interface in multiple languages. But when I try to use "/en" in URL for the English language which is the default. It does not work and shows me "404 Page" for default language only.

Can anyone please help me to fix it?

Thanks

I found the solution. Default language "English" requires the code to be enabled like the way when we add/change the code for new languages.

Go to configuration click languages.
Click "edit" for default language "English".
Now put code language code "en" in "path prefix language code" text field."
Save changes and access Url with/without "en" code. It will work in both cases for default language.

Thanks.


Having a views result in raw output I already found Get "Raw" views data (with no or little markup), but it wasn't, what I was looking for. I really do need the raw fields for having them differently styled in a module. Because the view itself should just be styled like it is, when navigating to it as page. But my module should be able to read the fields in raw-style. Or do I have to clone a view in order to be able to read the raw format?

Your module can load and execute the view itself. You can get the results from the view without changing the display.

// Load the view
$myview = views_get_view('my_view');
// Set arguments if you need to
$myview->set_arguments(array($code));
// Execute the query
$myview->execute();
// Loop over the results
foreach ($myview->result as $row) {
  // The fields are properties of the row
  $x = $row->my_field;
}


Display a block only if another specified block isn't visible? The issue is that I have a Menu Block with parent items that don't yet have child menu items, but eventually might.  I want to display another block in place of the menu block if the menu block is not on a particular page.  I have tried rules, rules bonus blocks, context, even conditions in my page templates but I am a PHP novice and so far it doesn't seem possible to create a condition based on a block's visibility.  I hope that makes sense!  Any help much appreciated!  I am using D7.

I was able to do this with panels, view blocks and a custom PHP visibility condition.  I think Panels is trivia.  You could do this with Drupal's built-in block administration.

I had a news block that would show up on the city page.  It would display all the news of the city.  If there was no news for that city, it would display [another] news block for that state.  If there was no news for that state, it would display [another] news block for the country.

Each of these block was a view.   In the PHP visibilty I would check for views results using the views_get_view_result($name, $dispay_id = NULL [, $args])

So the county block would check if the state and city block view returned any results,  if FALSE (no results) then it would get displayed.  State would check if city block view return any results, if FALSE (no results) then it would get display.

If you blocks are not views, then I don't know how to solve the problem easily (unless the last block is the only one that is not).


Why doesn't the authentication work? I am using Rest web service . I CREATED a view called ART and specified its path (/viewpath) and I set the  http baisc authentication within that view's structure such that the results will be accessible only for a user whose role is RESTADMIN . Everything works fine when I curl using the path of that view and the username and password of the user (of role restadmin) :
curl http://username:password@example.com/viewpath

However , when I try to get a simple article using its nid :
curl http://example.com/node/2?_format=hal_json

I get no results and "The used authentication method is not allowed on this route" . Even when I put the username and password as before I still get this error. I do realize that the authentication I have set is just for the view ART. But I can't find the solution to let the other link work any idea why?

Since the latter uses hal_json, you need to do it like this
curl --request GET --user myusername:mypassword --header 'Accept: application/hal+json' \
http://example.com/node/2?_format=hal_json

For more info, see Using other authentication protocols.


Checkbox near multifield value I want to make a new content type called Event, I have other fields in Event, but the field I am having trouble is Keynote Speakers.

Speakers are different content types and have their own fields like Name, Address.

In Event content type I have a field entity reference for this speakers content type, where Multiple Speakers could be added. I want to have a Checkbox near every speaker which would say Key Speaker as Title and could be checked to make the speakers as Key Speaker.

I tried this with Field Collection Module, where I made a collection type of Speakers and inserted the Entity Reference for Speaker as a field value. I created a new Boolean field with checkbox, but that went on to be

My quest is to make that Keynote Speaker as a separate title and have a checkboxes near every Speaker, if checked they'll be added as Keynote Speaker. Like:

How do I achieve this ?

I would suggest using two entity reference fields rather than one. One for storing the speakers and another one for storing the keynote speaker.

The you could place these two fields side by side and then hide the label of the keynote speaker through css.

You could also achieve this in a module using the form alter function to alter the style of the form.


HybridAuth has stopped working with FaceBook Before the weekend, I successfully set up the HybridAuth module. Upon returning to this project this week (July 1), Facebook logins no longer seem to respond.

Watchdog logs contained numerous of the following lines

Exception: Authentication failed! Facebook returned an invalid user id. in Hybrid_Auth::initialize() (line 147 of xxxxxxxx/public_html/sites/all/libraries/hybridauth/hybridauth/Hybrid/Auth.php).

Now I have checked the FB AppID and AppSecret. They are correct.

Permission is set as follows....

Sand box is off

I'm using the latest library from HybridAuth. I've clone it using git

Please check the issue already submitted in drupal.org https://drupal.org/node/1860618 . Especially check this comment. You have to use latest 7.x-2.x-dev release.


Validation Users Issues I have my fresh web site up and running. My first test is to try the functionality of creating a new user.  I tested added myself (no, not my admin account -- a different one with a different email address).  The new user's (mine) email got an alert saying that the account would be approved by the admin and further instructions and password would be sent to me.

I got the alert email also at the admin email address and I logged on and assigned the account a password and approved the account.

But the new user's email never got the notification.  I also tried to find the user's email address by using the admin's privileges on the site in case I needed to deliver the message to the user by hand.  But I could not find out how to do that.

I solved this issue.  The problem was that one has to look in the "spam" folder to see email that is sent by automated means.


I can't insert images to articles I installed Drupal 8 today, the release candidate 3. I had not done any modifications to it. When I edit my first article, I can't insert images. I clicked on the image button, but it keeps loading forever. I saw other people clicking the image button and a pop-up appearing.

Do I have to install a module?

My solution was simple: After updating Drupal8, ensure you run any pending scripts! Otherwise you will not be able to do certain things with your Drupal8 site.
Yesterday I updated my Drupal from some ancient version to the latest stable Drupal8. I noticed I can't add images [the forever loading problem], and I'm just a home user not behind a fancy firewall. After updating 13 pending scripts, everything was fine.
I'm not a very technical person, but I wanted to share my solution because no one else had shared this.
My website is ontu.org and thus the settings page for me was here:
http://ontu.org/admin/reports/status

Change that URL to your site and you'll quickly go to your settings page. There may be multiple issues reported on that page, so notice everything on there.


How do web search engines handle view pages? When search engines are examining the content of a Drupal site how do they identify content assembled by a view?  A single view can have unlimited pages associated with it. In fact the entire content of a site can be provided that way.

Any resources on how these engines do their job in general (and for Drupal specifically) would be appreciated.

In the SEO world, this is known as Duplicate Content, and it's something you want to avoid as much as possible. [1]

This is dangerous territory for duplicate pages which can get you sandboxed by the search engines! [2]

in drupal you can reach same page with lots of links: node/123, node/123/, content/some title and ...

one solution is Global Redirect module


How can I rename a menu machine name in drupal 8 I ve migrated my D6 site to D8. And now I'd like to rename my menu machine names(not the system menus my custom menus) to a different ones. I'd want to do this either on database or from code.

Any ideas??

I also faced the problem when I needed to rename the machine name of my custom menus. In my case, I needed to remove hyphens in the machine name (this is a known issue https://www.drupal.org/project/drupal/issues/1353064), because some modules don't support hyphens. How I fixed it:

First of all you need to update already existing menu items (bundle, name, parent and etc.) I did it directly in a database through hook_update in your_custom_module:

function your_custom_module_update_8008() {
  $database = \Drupal::database();

  $menus = [
    'example-menu-machine-name-1' => 'examplemenumachinename1',
    'example-menu-machine-name-2' => 'examplemenumachinename2',
  ];

  foreach ($menus as $old_machine_name => $new_machine_name) {
    $database->update('menu_link_content')
      ->expression('bundle', "REPLACE(bundle, :old_value, :new_value)", [
        ':old_value' => $old_machine_name,
        ':new_value' => $new_machine_name,
      ])
      ->execute();
    $database->update('menu_link_content_data')
      ->expression('menu_name', "REPLACE(menu_name, :old_value, :new_value)", [
        ':old_value' => $old_machine_name,
        ':new_value' => $new_machine_name,
      ])
      ->expression('bundle', "REPLACE(bundle, :old_value, :new_value)", [
        ':old_value' => $old_machine_name,
        ':new_value' => $new_machine_name,
      ])
      ->execute();

    $database->update('menu_tree')
      ->expression('menu_name', 'REPLACE(menu_name, :old_value, :new_value)', [
        ':old_value' => $old_machine_name,
        ':new_value' => $new_machine_name,
      ])
      ->expression('id', 'REPLACE(id, :old_value, :new_value)', [
        ':old_value' => $old_machine_name,
        ':new_value' => $new_machine_name,
      ])
      ->expression('parent', 'REPLACE(parent, :old_value, :new_value)', [
        ':old_value' => $old_machine_name,
        ':new_value' => $new_machine_name,
      ])
      ->execute();
  }
}

Rename these names in configs. Your IDE should help with this. Don't forget also about renaming files for configs. For example:
system.menu.example-menu-machine-name-1.yml to system.menu.examplemenumachinename1.yml

If you have custom templates for menus also rename them:
menu--example-menu-machine-name-1.html.twig to menu--examplemenumachinename1.html.twig

Adjust classes in CSS|SCSS files, because they will be changed after renaming. Use IDE for this, it will save time :)

Run your build process locally and check results.

Take the dump of the database from the production and run a build with this database locally. Please compare menus between the local version and the production on the frontend.


Only getting varnish misses Would having the display errors setting turned on in the following admin page admin/config/development/logging cause Varnish to generate cache misses?

Messages are stored in the session (errors, warnings and info messages). If anything is in the session, a session cookie is set in the browser. If the session cookie is set in the browser, Varnish is normally bypassed.

Note, the name of the Drupal session cookie is SESS followed by a long hexadecimal string.


Redirect to Different URl on validation errors in form builder I am using drupal 8 fapi and i have user case as below

I have a form  on https://example.com/landing-page and I submit the  form and there are validation errors .the page should reload as https://example.com/landing-page#lead-form.

Is there any hack we can implement?

I came with logic

if validation has error set form redirect page to example.com/landing-page#lead-form

if($form_state->getErrors() ) {
  $response = new TrustedRedirectResponse('example.com/landing-page#lead-form');
  $form_state->setResponse($response);
}

some how its not working.

Is there any way we can change the url to example.com/landing-page#lead-form and show the validation error at same time .

You can use like

For Internal:

global $base_url;
$response = new TrustedRedirectResponse($base_url.'/landing-page#lead-form');
// You can use any one of these below to show error message.
$form_state->setError($element, $message);
$form_state->setErrorByName($element, $message);
$form_state->setResponse($response);

For External:
Use full link

$response = new TrustedRedirectResponse('https://facebook.com');
// You can use any one of these below to show error message.
$form_state->setError($element, $message);
$form_state->setErrorByName($element, $message);
$form_state->setResponse($response);


How can I rebuild node / view cache based on the contents of an entityqueue I have

Content types:

front_banner
news

Entity Queues:

front_banner -> only ever contains one front_banner node
news -> contains multiple news nodes

Views:

front_banner -> displays rendered nodes (default)
news -> displays rendered nodes (teaser)

The front banner content type has a field in it that determines whether the text colour should be light or dark when display (sets a class in the twig template, works fine).  The news content type also makes use of the front_banner's overlay style field like so:

function mymodule_preprocess_node(array &$vars) {
  if ($vars['node']->bundle() == 'news'){

    // Set the overlay class (dark/light).
    $entity_subqueue = \Drupal::entityManager()->getStorage('entity_subqueue')->load('front_banner');
    $items = $entity_subqueue->get('items')->getValue();
    $front_node = node_load($items[0]['target_id']);
    $vars['overlay_class'] = $front_node->get('field_overlay_style')->getString();
  }
}

All of this works perfectly well, my problem occurs when I alter the front_banner node or entityqueue: the cache is obviously not set to refresh for news items when that occurs.

1. Which render cache do I need to rebuild?

Is it the view cache? or the node's render cache? or both?

2. How can I do it?

I have tried creating my own cache tag and flushing it like so:

function mymodule_entity_presave(EntityInterface $entity) {
  $tags = ['entity_type:' . $entity->getEntityTypeId() . '.' . $entity->bundle()];
  Cache::invalidateTags($tags);
}

function mymodule_node_view_alter(array &$build, Drupal\Core\Entity\EntityInterface $entity, \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display) {
  if ($build['#node']->bundle() == 'news'){
    //dpm($build);
    $tags=['entity_type:node.front_page_banner', 'entity_subqueue:front_banner'];
    $build['#node']->addCacheTags($tags);
  }
}

(entity_subqueue:front_banner tag is provided by the entityqueue module)

I cannot get the news node page itself to change the overlay style, nor can I get the view that displays news nodes to change the overlay style when the front_banner node is saved.

[Edit 1:] I looked into Views Custom Cache Tags - this does allow me to state which tags I want to affect the views cache - I tried putting the two relevant tags in my view to no effect.  Perhaps this means it's the node cache that is giving me grief?

Every view that lists nodes is tagged with node_list and will be invalidated when a node is added, changed or deleted, so you don't need to worry about adding your nodes to the view.

But you do need to add the entity_subqueue tag to your view's cache tags, and you need to add the entity_subqueue tag and banner content type to your news content type's build array.  I haven't tested the way you're adding it, but I know you can add cache tags to a node in hook_entity_view:

  function mymodule_entity_view(array &$build, EntityInterface $entity, EntityViewDisplayInterface $display, $view_mode) {

      if ($entity->bundle() == 'news') {

        $tags = ['entity_type:node.front_page_banner', 'entity_subqueue:front_banner'];
        $build['#cache']['tags'] = array_merge($build['#cache']['tags'], $tags);

      }
    }

I know this is similar to what you were doing, but need to add it to the build array, not the node object.

Then you need to add the entity queue to the build array of your view

function mymodule_views_pre_view(ViewExecutable $view, $display_id, array &$args) {

  if ($view->id() == 'news' || $view->id() == 'front_banner') {
    $view->element['#cache']['tags'][] = 'entity_subqueue:front_banner';
  }
}


Can I access node ID of the parent node of a field collection field in field-collection-item--FIELD_NAME.tpl.php I am just hoping to get the node ID of the parent node in a field-collection-item--name.tpl.php template file.

So if my parent node name is mypage in which I have child fields of field-collection-item--name.tpl.php, I just want to access the Node ID of the parent page (mypage) in field-collection-item--name.tpl.php.

Is it possible?

Apparently somewhat yes. If I do this, I get details on the parent node. The only problem is that that data is protected. The output of this line is pasted below. All I want is [vid] value (i.e. 120)

  $var = $content["field_image_title"]["#object"];
  print_r ($var);

Output of above line

FieldCollectionItemEntity Object
(
    [fieldInfo:protected] =>
    [hostEntity:protected] => stdClass Object
        (
            [vid] => 120
            [uid] => 1
            [title] => My Parent Page Name
            [log] =>
            [status] => 1
            [comment] => 1
            [promote] => 0
            [sticky] => 0
            [vuuid] => f3c2f63d-5d86-4d94-98f3-8a1ba76ce1f9
            [nid] => 120
            [type] => subpage
            [language] => und
            [created] => 1408623334
            [changed] => 1408640101
            [tnid] => 0
            [translate] => 0
            [uuid] => 486dead0-4f72-45a3-988c-64512e6b91de
            [revision_timestamp] => 1408640101
            [revision_uid] => 1

Any help on how I can get this vid value in this protected array?

Thanks.

Load the field collection using entity_load by passing the entity id. It gives you object where you can get the Host entity of the loaded entity. example profile2 will have user entity as host entity, or commerce line item will have commerce order as host entity.

$entity = entity_load('field_collection_item', $your_file_collection_id);
$host_entity = $entity->hostEntity();
echo $host_entity->nid;


How to get Fixed Navigation when scrolling to the top I am using this module Single Page Site to get a single page and it works well.  However I want to get the navbar fixed when scrolling up the page but I cannot figure out how and where to put this jquery code in my site.

$(document).ready(function () {

  var navbar = $('.navbar');
  var origOffsetY = navbar.offset().top;

  function scroll() {
     if ($(window).scrollTop() >= origOffsetY) {
         $('.navbar').addClass('.navbar-fixed-top');
         $('.main-container').addClass('menu-padding');
     }
     else {
        $('.navbar').removeClass('.navbar-fixed-top');
        $('.main-container').removeClass('menu-padding');
     }

  }

  document.onscroll = scroll;
  });

Actually what I am trying to achieve is something similar to this website http://www.orisnv.be which itself using the modules Single Page Site.

I appreciate any help or hint.

Thanks.

It turns out the answer is simple.  I just declare the javascript inside .info file.  And by using Drupal.behaiors I implement the jquery that target the navbar to fix upon scrolling.


How to know when a field is a paragraph I'd like to know when a field from a node it's a paragraph, I only get the type, that it's entity_reference_revisions, I use this method to get the information:

\Drupal\field\Entity\FieldStorageConfig::loadByName()

But I'm not able to get this information

 [settings:protected] => Array
    (
        [target_type] => paragraph
    )

The only way I get it's to check directly to the database to see it the name of the field it's in the table paragraphs_item_field_data.

Thanks

Oskar

You're probably looking for the EntityFieldManager service. It is available from the container as entity_field.manager. Its EntityFieldManager::getFieldDefinitions() method returns the field definitions for all fields that belong to a certain entity type and bundle (content type), keyed by their field names:

$definitions = \Drupal::service('entity_field.manager')->getFieldDefinitions('node', 'page');
if (
  isset($definitions['field_to_check'])
  && $definition = $definitions['field_to_check']
  && $definition->getSetting('target_type')
  && $definition->getSetting('target_type') == 'paragraph'
) {
  // Is a field of a 'node' entity, belongs to the bundle
  // 'page', has the 'target_type' property, and finally
  // references paragraphs.
}

If you load the field storage definition using FieldStorageConfig::loadByName() only, you need to be careful: Field definitions can be different for the various bundle (content) types. So you'd need to additionally check, whether your bundle (content type) matches the bundle of the node you are investigating the reference field for.


How to create basic Organic Groups functionality with flags and references? I've used Organic Groups for the past 6 months and found it to complex for my simple use case. Creating even basic views to show users of a group or content of a group turns quickly into "rocket since".

The module comes with a ton of extra functionality that I didn't need, like access control.

Plus I couldn't migrate my group content and group membership and when I manually inserted into the tables it wouldn't work reliably.

Below is my solution to create basic OG features with flag and reference modules. My requirements were:

users can create groups
users can join groups (and leave them) without approvals or permissions
users can add other nodes to show up as group content
use views to display group content and group membership

Please post your comments or alternative solutions.

Btw, Clive encouraged me on meta to post this how-to. Thanks, Clive!

1. Users can create groups:

To create groups you just create a new content type "groups" and with permissions for users to create new content. I also added an image field to allow uploading a group logo.

2. Users can join groups (and leave them) without approvals or permissions

The Flag module turned out to be an excellent way to allow users to join (and leave) groups. Create a new flag called "groups" and make sure the "global flag" is unchecked and then select your "groups" as "flaggable content". You can also customize the flag links to say "join this group", etc.
Btw, just changing the default link text is hard in OG.

3. Users can add other nodes to show up as group content

To assign other nodes to the "groups" content type I used node references from the references module. I also looked at (and used before) entity references and DA members seem to prefer entity references.

Node references however has more installs and comes with a nifty "References" feature that allowed me to filter the "available groups" on a node add/edit page to only the groups that have been flagged by the user.

To allow my photo nodes to be assigned to the groups type I add a "group_content" field to the photo type and select "node reference" as the field type. You can specify the widget type (autocomplete, checkbox, select list), I picked checkbox and 5 as the "number of values".
For "content that can be referenced" you simply select your "groups" content type.

With this setting you can create a new photo node and assign it to ANY of the groups that have been created so far. To limit it to a user's groups you create a view for "content of type = group" and then add relationship "Flags: Node flag" with the setting "include only flagged content" checked. Select your "group flag" and select "current user".

Now your view only shows groups flagged by the current user. Click "Add" below "Displays" and select "References", then save.

Now edit your photo content type again and edit the "group_content" field. At the bottom you there is an option for "The list of nodes that can be referenced can be provided by a view" and you should see your new view as an option. Select that and save.

You can create similar references from other nodes by using "add existing field" in "manage fields" of the content type.

4. Use views to display group content and group membership

Now all that is left is creating some views. For example, I want to show a list of users and a list of group content on a group page.

In OG these views are complex, see an example of group content view and users of a group.

With Flags and Node References they are very simple:

List of groups with number of users in each group":

content type = group
add relationship "flags: node counter" with "groups" selected and "include flagged content" not selected
add field "Flags: Flag counter", that shows the number of users
display in a table and enable default sort by title or number of users. Done

List of members that belong to a group:

create a view of users
add relationship "Flags: User's flagged content" with "include only users who have flagged content" checked and "group" as "flagged"
add contextual filter for "Flags: content id" and provide a default value of "content ID from URL"
create a block view to show the first 5 users with a more link to show all users on a page. Select that block to show up for your "group" content type

Show list of nodes that are assigned to a group:

create a view with content type = photo for example
add contextual filter "Content: Groups (field_group_content) - that's the node reference field we created above. Select "content from URL" as the default value and now you'll only see photos assigned to the current group.
create a block to show the most recent 5 with a "more" link to a page showing all. Then enable the block to show for type "group".

That's it. As an additional benefit I could import my legacy group membership and group content with a couple of basic SQL INSERT statements.


valueCallback in custom form element is not invoking itself? I am creating a custom form element in my custom module. Everything is working fine except the valueCallback function is not invoking itself. I have done it in following way :

Name space

namespace Drupal\custom_element\Element;

getInfo and valueCallback Method:

public function getInfo() {
    $class = get_class($this);
    return [
      '#input' => TRUE,
      '#tree' => TRUE,
      '#process' => [
        [$class, 'processCheckboxes'],
      ],
      '#theme' => 'custom_theme',
      '#value_callback' => ['valueCallback'], // Try with and without #value_callback key
    ];
  }

  /**
   * {@inheritdoc}
   */
  public static function valueCallback(&$element, $input, FormStateInterface $form_state) {
    dsm('in valuecallback');
  }

I am not sure what I am missing.

Related Link : https://www.drupal.org/node/2320115

It doesn't invoke itself when #value is already set to element. I didn't notice that I set it in theme function. After removing #value key from $element array it is working fine.


File migration create ghost files I tested a migration from Drupal 6 to Drupal 8 on a local installation (2 differents multisites). Sometimes I get "ghost files" after running upgrade_d6_file.

  Processed 1444 items (1441 created, 0 updated, 3 failed, 0 ignored) - done with 'upgrade_d6_file'
  upgrade_d6_file Migration - 3 failed.

Then in admin/content/files, I get files like swadouotoclabruswuspitomiswulusliwokedaspamaslouawrotrephichophasichocutribuhostestus or wruhahachicregiwaspidristocospopowrucrekefrocojegephehoshapracocrewafrispugedrachupuclushipreclochoshusiclastewracrislumufraswiheracribra.

How can I fix this issue?

EDIT1:
In my use case, with a custom node content migration.Not sure about using the Skip on empty option. However file exist, ghost files are created.

id: upgrade_d6_node_diapo_hp
label: Nodes
audit: true
migration_tags:
  - Drupal 6
  - Content
  - Migration_CE
migration_group: migrate_drupal_6_ce
source:
  plugin: d6_node
  node_type: diapo_hp
process:
  # In D6, nodes always have a tnid, but it's zero for untranslated nodes.
  # We normalize it to equal the nid in that case.
  # @see \Drupal\node\Plugin\migrate\source\d6\Node::prepareRow().
  # If you are using this file to build a custom migration consider removing
  # the nid and vid fields to allow incremental migrations.
  nid: tnid
  vid: vid
  langcode:
    plugin: default_value
    source: language
    default_value: "und"
  title: title
  uid: node_uid
  status: status
  created: created
  changed: changed
  promote: promote
  sticky: sticky
  body/format:
    plugin: migration_lookup
    migration: d6_filter_format
    source: format
  body/value: body
  body/summary: teaser
  revision_uid: revision_uid
  revision_log: log
  revision_timestamp: timestamp

  #OK
  field_diapo_home:
    plugin: d6_field_file
    source: field_diapo_home
    process:
      target_id:
        plugin: migration_lookup
        migration: upgrade_d6_file
        source: fid
        -
        plugin: skip_on_empty
        method: process

#  unmapped d6 fields.
#  tnid
#  translate
#  moderate
#  comment

destination:
  plugin: entity:node
migration_dependencies:
  required:
    - upgrade_d6_user
    - upgrade_d6_node_type
    - upgrade_d6_node_settings
    - upgrade_d6_filter_format
  optional:
    - fields_instance_widget
    - fields_formatter_settings

Try it like this:

  field_diapo_home:
  -
    plugin: d6_field_file
    source: field_diapo_home
    migration: upgrade_d6_file
  -
    plugin: skip_on_empty
    method: process


How to keep theming of a view after changing type of view? I am using a Drupal distro(Recruiter).
The distro has a view of type "Rendered entity".
However I am interested to change the type of the view to "Fields".
However when I make the change,the default theming of the view dissapears.So I am interested to keep the default theming of the view.
How can I do that?What shall I inspect?I am not a theming/css guy so any help would be appreciated.
thanks!

Use the Theme:Information link in the edit view page

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


Add module-generated pages to Drupal 7's search index I have a custom module that provides pages via hook_menu(). The page callback returns HTML-formatted output that is then displayed. The information is fetched from an external database, so it is not a  node/custom content type.

Since the displayed information is somehow the heart of this Drupal site, I want to add the information to Drupal's search index.

How can I facilitate this?

Implement hook_search_info() to describe your new search type.
Implement hook_update_index(), build up the content you wanted to be indexed, and throw it over to search_index() (see the example in hook_update_index()).
Profit.

Be sure to follow all the advice in the comments in the linked functions, and check out the core node and user modules' implementations of these hooks for examples of exactly what you need to do. The comments for hook_search_execute() should also prove pretty helpful.


display description and price field from a term reference this is my setup: a vocabulary(pulp_toppings) containing 3 terms(honing, noten, brie). Each term also has a price field, I cannot find a way to display the prices of the terms :/ please help.

I have a line item with a term reference but it only references or displays the term titles.

So I could have toppings above my add to cart button but the prices of the toppings won't show.

I followed this tutorial(the screencast from Josh Miller about customizable items) to get the line item and taxonomy part: https://www.youtube.com/watch?v=j9KsyvQZaAY

What I need is either a solution for the above(changing the way my line item references the terms so also the price of the terms are shown) or a better way to handle toppings(not pricing attributes since it stopped working for me).

setup shown below:

If you have token you could 'rewrite output' on the Configure field: screen. I think yours is called 'form' (your 2nd last pic).

On that edit screen scroll down a little and you will see the rewrite output header. In there you can add tokens for fields that are already called earlier in your display. You can call the value and 'exclude from display' just to load them and have them available.

Unfortunately I can't make out the machine names you have assigned to the terms, but there is a button to show you all the available tokens.

Sooo, you could write the output and have
 <label ...>[..field:?topping_ref:name][..field:?topping_ref:name]</label>


Theming stuff in Drupal 8? How do you theme stuff in Drupal 8? In 7, for example, if you had some data items you could call item_list, via the theme function, pass in a render array and get your markup back.

This is a great resource for those interested: Render API, but no examples that I can see.

How do I do this in Drupal 8? For example, how do I theme an image? Sure,
I can probably construct my render array, but does it then have to go off to a twig template or something. Are there any examples yet?

Thanks.

It seems to be similar to D7. Just use a render array:

$list = array('apples', 'peaches', 'pears');
$render_array = array(
  '#theme' => 'item_list',
  '#items' => $list,
  '#title' => t('Argument Information'),
);
return $render_array;

I searched '#theme' in core\modules to find examples. Not sure if this is the 'correct' way though?


How to programmatically publish/unpublished node using flag link and without using Rules? I have implemented the functionality on flag link click the content are unpublished and click on unflagging the content are published.
By using the Rules module.

But this time I want to implement same functionality without using rules module and instead using custom coding.

Any suggestions?

Any module may react to a piece of content being flagged by implementing hook_flag(). Here is the relevant do so:

mymodule_flag($action, $flag, $content_id, $account) {
  if ($action == 'flag') { // Or $action == 'unflag'.
    // Do something in response to the flagging.
  }

  if ($flag->name == 'yourflagname') {
    //Your custom code to unpublish/publish the content goes here.
  }

}

Source: "Responding to a flagging", located within the Flag's community documentation.


migrating from localhost to server - What to do with the folder sites/localhost.mysitename? I am trying to migrate my site from acquia dev desktop (local host server) to bluehost.
In my site on my computer I have inside the "sites" folder, 3 folders:

all
default
localhost.mysitename

Inside localhost.mysitename I have the "files" folder, and inside that I have the following folders: adaptive theme, banner, color, ctools, custom_search, custom_search, feeds, pictures, styles, styles. in addition I have the ".htaccess" file and many pictures and logos of the site.

Should I change the folder name of "localhost.mysitename" to only "mysitename"?
Should I change it at all or to other name?

I don't know the acquia product you are using. And I don't know bluehost - but it seems to be a "usual webhoster". I assume at bluehost is an ordinary LAMP stack running without any drupal-specific modifications.

update 2 after comments of EB84:

It turns out you are not using multi-sites. Seems to me as you made your setup more difficult than it needs to be:

Just replace the default folder with your localhost.mysitename folder. By doing so you revert your folder-structure back to a simple single-site setup.

Keep in mind, that you need to adopt your settings.php to the preferences of your bluehost webspace (database parameters, etc.). Your settings.php will look different on the server than on your local machine - all other files and directories may be the same.

update 1 after comment of EB84:

Since you are using a multi-site setup the configuration in sites/sites.php will control which site will be used for what domain names in HTTP requests.

Please read following documents:

https://api.drupal.org/api/drupal/sites!example.sites.php/7
https://drupal.org/documentation/install/multi-site

You will read that the directory names are arbitrary - as long as you map the domain name of the HTTP requests to it (via the configuration in sites.php).

Anyhow it might be good to remove the term "localhost" from your directory name - not for the whole thing to run technically, but to not confuse yourself some when in future.


How to fix millions of Alt Text are missing on body content? This question is very similar to my other question. I have a website missing millions of Alt Text in body content(not image field). My solution is to set the default Alt Text as the file name without extension. Is it even possible, if so, how?

-- -- added additional info on Oct 2nd 12:40pm for tenken : below is a screenshot of setting

PS: there is no replace setting on Setting section

Here is the screenshot on setting section

Try using the Search and Replace Scanner module to search through the text of your body field. You could use a regular expression to search for image tags without alt attributes.

Some excerpts from the module page:

  Features

  Can search and replace text in CCK text fields, in addition to standard node title and body fields
  Plain text search and replace regular expression search and replace
  Case sensitive search option

This module is designed to work on MySQL and dedicated servers, be sure to review the module page and accompanying documentation.


How to configure htaccess to redirect ALL traffic through https? I'm looking for a way to redirect users to https://domain.com whether they type the www or not

I'm using a shared host for a drupal website so i don't have access to virtual host config files.
A let's encrypt certificate if included with the hosting package
Right now the website can be accessed both with http and https depending on what you type in the browser.
In looking for a solution to force redirection to https i found this section in the in the .htaccess file that redirects users who type the www. to https://domain.com

# To redirect all users to access the site WITHOUT the 'www.' prefix,
  # (http://www.example.com/... will be redirected to http://example.com/...)
  # uncomment the following:
   RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
   RewriteRule ^ https%{ENV:protossl}://%1%{REQUEST_URI} [L,R=301]

Now i'm looking for a way to redirect when typing http://domain.com without the www.

Do i need to put another rule somewhere in addition to the line i uncommented or is there some other way to do this ?

You could use something like this:

 RewriteCond %{HTTPS} !=on
 RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [R=301,L,NE]


How to create a layout with different size grid theming with Views? I recently saw this Wordpress website.

I am curious on how to create such a layout with different columns for each row in views.

Can someone help me out with this what to do?

This you can do using combination of Views and Panels. Views will provide whatever data you want. This will be the easiest and straight.

Views is for -> Fetching the data
Panels/DS is for -> To arrange Display layout

Panels,

  The Panels module allows a site administrator to create customized
  layouts for multiple uses. At its core it is a drag and drop content
  manager that lets you visually design a layout and place content
  within that layout.

Or instead of Panels, Display suite also,

Display suit,

  Display Suite allows you to take full control over how your content is
  displayed using a drag and drop interface. Arrange your nodes, views,
  comments, user data etc. the way you want without having to work your
  way through dozens of template files.


Can I create a custom interface to power views search? My content is well structured from an internal point of view, but I want to provide a more customer-focussed front-end to an advanced search form.

e.g. I want to offer a list of check boxes like

Show:
[ ] All
[X] Articles
[X] Yellow things
[ ] Super cheap things

I would then intercept this data and mangle it, so for example Article might become a parameter to node_type but Yellow things might be changed into node_type = things AND field_colour = 'yellow' while Super cheap things might be a different thing again.

i.e. I'd like to have a parameterised view set up but use my own customer-focussed forms, rather than use Views' own data-focussed exposed forms.

Is this straight forward?

(More info: I'm on Drupal 7.x. I'm very comfortable with PHP and SQL but I'm keen to do things the Drupal Way unless it's ridiculously inefficient)

Write a custom views_handler_filter. See Views' API for a step by step introduction to implementing handler classes for Views.


Change Entityqueue autocomplete to an entity widget I have an Entityqueue and whenever a user wants to add an item to queue, he/she should write part of title in Autocomplete to add it to queue.

I want to change this autocomplete with a widget that list entities with pagination and when user clicks on an Entity title to add it to queue.

Finally i solved it using Entity API & Entity reference view widget.

Entityqueue is prefect but it suffers from lake of good UX.


User registration form: Give username "username n+1" value, if and when n is already used I'm using the first & last name in the user registration form to generate the username for the new user:

$firstname = $form_state['values']['field_firstname'][LANGUAGE_NONE][0]['value'];
$lastname = $form_state['values']['field_lastname'][LANGUAGE_NONE][0]['value'];
$username = $firstname.''.$lastname;
$result = db_query("SELECT COUNT(*) FROM {users} WHERE name = :name", array(':name' => $username));
$results_number = $result->rowCount();
if ($results_number == 0) {
    $form_state['values']['name'] = $username;
}
else {
    $i = 1;
    $username = $firstname.''.$lastname.''.$i;
    while ($results_number > 0) {
        $result = db_query("SELECT COUNT(*) FROM {users} WHERE name = :name", array(':name' => $username));
        $results_number = $result->rowCount();
        $i++;
        $username = $firstname.''.$lastname.''.$i;
        $form_state['values']['name'] = $username;
    }
}

But I get an infinite loop. There is a problem with that while loop, any suggestions on the best way to fix that?

So here is what I used to increment the username's suffix by 1 if the initial value is not found:

function increment_string($str, $separator, $first = 1) {
    preg_match('/(.+)'.$separator.'([0-9]+)$/', $str, $match);
    return isset($match[2]) ? $match[1].$separator.($match[2] + 1) : $str.$separator.$first;
}

$username = $firstname . ' ' . $lastname;
$result = db_query("SELECT uid FROM {users} WHERE name = :name", array(':name' => $username));
$results_number = $result->rowCount();
    if ($results_number == 0) {
        $form_state['values']['name'] = $username;
    }
    else {
    while ($results_number >= 1) {
        $username = increment_string($username_to_store, ' ');
        $result = db_query('SELECT uid FROM {users} WHERE name LIKE :name_pattern', array(':name_pattern' => db_like($username)));
        $results_number = $result->rowCount();
    }
    $form_state['values']['name'] = $username;
    }


Save user fields in commerce profile I add some fields to default user fields,like  phone,address,city,... , I want If user edit or filled up his user information in user/uid/edit when submit ,if there is not any commerce shipping profile, create a profile to him/her, and if there is , update default shipping profile ,
how can I achieve this job?
I know I can create  profile with something like below code

 $new_profile = commerce_customer_profile_new($type);
  $wrapper = entity_metadata_wrapper('commerce_customer_profile', $new_profile);
  $wrapper->uid = $account;
  $wrapper->commerce_customer_address->country = $country;
  $wrapper->commerce_customer_address->name_line = $name_line;
  $wrapper->commerce_customer_address->first_name = $first_name;
  $wrapper->commerce_customer_address->last_name = $last_name;
  $wrapper->commerce_customer_address->organisation_name = $organisation;
  $wrapper->commerce_customer_address->administrative_area = $administrative_area;
  $wrapper->commerce_customer_address->sub_administrative_area = $sub_administrative_area;
  $wrapper->commerce_customer_address->locality = $locality;
  $wrapper->commerce_customer_address->dependent_locality = $dependent_locality;
  $wrapper->commerce_customer_address->postal_code = $postal_code;
  $wrapper->commerce_customer_address->thoroughfare = $thoroughfare;
  $wrapper->commerce_customer_address->premise = $premise;
  $wrapper->field_bcg_customer_phone = $phone;
  commerce_customer_profile_save($new_profile);

but my question is , how can set it as default, after user edited (updated) if there is default profile , update it also

appreciate any help

As you mention you're looking for setting the profile as default, I'm assuming you're using Commerce Addressbook or in any case looking for a very similar feature of what that module provides.

  Commerce Addressbook is a module that allows authenticated customers to reuse
  previously entered addresses during checkout.
  They can manage all entered addresses in their user panel (user/%user/addressbook).

You can use commerce_addressbook_set_default_profile function to set the default (one per type). Example:

$billing_profile = commerce_customer_profile_new('billing', $user->uid);
  $billing_profile->commerce_customer_address[LANGUAGE_NONE][0]['name_line'] = 'Sample Customer';
  $billing_profile->commerce_customer_address[LANGUAGE_NONE][0]['country'] = 'US';
  $billing_profile->commerce_customer_address[LANGUAGE_NONE][0]['thoroughfare'] = '16 Hampton Ct';
  $billing_profile->commerce_customer_address[LANGUAGE_NONE][0]['locality'] = 'Visalia';
  $billing_profile->commerce_customer_address[LANGUAGE_NONE][0]['administrative_area'] = 'CA';
  $billing_profile->commerce_customer_address[LANGUAGE_NONE][0]['postal_code'] = '93277-8329';
  commerce_customer_profile_save($billing_profile);
  commerce_addressbook_set_default_profile($billing_profile);

I'd recommend another way to create the profile, for example:

    // Create the new profile now.
    $profile = commerce_customer_profile_new('billing', $order->uid);

    // Add the address value.
    $profile_wrapper = entity_metadata_wrapper('commerce_customer_profile', $profile);

    $profile_wrapper->commerce_customer_address = array_merge(addressfield_default_values(), array(
      'country' => $country,
      'name_line' => $name . ' ' . $last_name,
      'first_name' => $first_name,
      'last_name' => $last_name,
    ));

    // Save the profile.
    $profile_wrapper->save();


Membership contribution with profile required 'on behalf of' prefilled I'm helping a nonprofit with a Drupal/CiviCRM site. They track memberships in CiviCRM which are associated with an organization as the primary member, and individuals linked to the organization by relationships to share this membership.

Using the "CiviMember Roles Sync" module, these individuals are granted access to a member role in Drupal.

I've created a contribution page in CiviCRM for membership signup or renewal, and since the primary member is actually the organization, I've checked "Allow individuals to contribute and/or signup for membership on behalf of an organization". Since it is a requirement, I've also made this required instead of optional. (Screenshot below).

The help text here indicates that "logged in users will be given a choice of selecting from a list of organizations that they have a permissioned relationship with OR entering a new organization" -- however, I am not able to produce the select/list despite assigning "view and update information" permissions in both directions on the relationship between the individual and the organization. The contribution page just allows typing in a text field for the org name, which will produce a lot of duplicates and extra work.

Am I missing a step to get the select list which will prefill the org's information?

The behaviour that you are expecting to see will work - at least it does for me - when the relationship between the individual and the organisation is "Employee of". Other relationship types appear not to work. Perhaps you are using a different relationship type?


How do I programmatically add an image while programmatically creating nodes? I'm writing a script to add nodes programmatically, and I don't know the proper way to add/attach image. Actually I'm not that familiar with Drupal.

Here are the (sample) image objects I found while print_ring the existing $node I'm using:

field_image: Array ( [und] => Array ( [0] => Array ( [fxid] => 3089 [alt] => [title] => [width] => 95 [height] => 126 [uid] => 249 [filename] => helloworld.jpg [uri] => public://helloworld.jpg [filemime] => image/jpeg [filesize] => 3694 [status] => 1 [timestamp] => 1346748001 [type] => image [media_title] => Array ( ) [media_description] => Array ( ) [field_tags] => Array ( ) [field_license] => Array ( [und] => Array ( [0] => Array ( [value] => nothing ) ) ) [metatags] => Array ( ) [rdf_mapping] => Array ( ) ) ) )

The next one I found is the following.

field_temp_image: Array ( [und] => Array ( [0] => Array ( [value] => http://www.example.com/sample-path/helloworld.jpg [format] => [safe_value] => http://www.example.com/sample-path/helloworld.jpg ) ) ) `

How should I add an image to that node in that way?

Let suppose your image fields in field_body_images ,

first load your node by node_load
and record your image in file tables and add it to your node image field
I hope this sample help you to achieve :

$n=  node_load($nid);
$file = new stdClass();
$file->filename =$file_name;
$file->filemime =file_get_mimetype($localimagepath.$file_name);
$file->filesize = @filesize(file_create_path($localimagepath.$file_name));
$file->uid = $user->uid;
$file->status = 1;
$file->timestamp = time();
$file->list=1;
$file->data=array('alt'=>'','title'=>$n->title);
drupal_write_record('files', $file);
$record->fid=$file->fid;
$n->field_body_images[]=(array)$file;
node_save($n);


translating static text I have just built a view for one of my modules.
In there, I have this line; %of Applicants Admitted`

I already installed modules like "Locale", "Content Translation" and "Internationalization" is already enabled.
But I dont understand how these modules will translate this text to other languages.
When I put it in t('') how will I know that it will translate it correctly. Can I manually enter the translation?

Thanks

Translations have to be entered manually... always.  There is no "automatic machine translation" function provided by Drupal core or the Internationalization suite of modules.

Putting a string inside t() simply makes it available to Drupal's translation subsystem for translation; the string will still be displayed "as is" until it is translated manually.

To translate strings manually from the UI, if you have the Locale module enabled, you can go to the Translate interface page.  (On Drupal 7: /admin/config/regional/translate/translate)


Hook to import entity data in custom module installation in Drupal 7 What would be 'the best' hook function to use in the custom module installation to import entity data? This is supposed to be a one-time activity during the module installation only, after entity schema is built in the database and entities are initialized (to be able to use Entity API in the data import).

For one time import of data, when installing a module, use hook_install.  This can be used to populate the database just after tables are created, provided your module also implements hook_schema.

You do not want to use
hook_enable.  If you used this, the database would be re-populated every time the module was re-enabled after being temporary disabled.


Contextual filters taxonomy name I'm adding a contextual filter to a view for a custom content type that has a taxonomy field. The contextual filter allows me to filter by the taxonomy tag id but not by the taxonomy tag name. Meaning with the given tags in the taxonomy:

1  | test1
2  | another tag
3  | taggy
......
99 | coolness

I can generate a contextual filter that will parse a URL like http://mydrupal/myview/3 to display all content that has been tagged with taggy BUT, the URL needs to pass the argument to lookup by tag name instead of tag id, e.g., http://mydrupal/myview/taggy to view all content tagged with taggy How can this be accomplished?

I assume you've added the Content: Has taxonomy term ID contextual filter. You can use taxonomy term names with this filter by adjusting Specify validation criteria settings. here's a screenshot:

Make sure Specify validation criteria is checked and you should be presented with more options. Under Validator choose Taxonomy term. You can optionally select with vocabularies to allow. Under Filter value type choose Term name converted to Term ID and check the Transform dashes in URL to spaces in term name filter values checkbox.


Blank screen with no error messages on new server I have a working Drupal 7 site, built with git, running on 2 different servers, one test server and one server used for staging and production sites. So I know that the site is working.

So after deciding to move the production and staging sites to a new Apache server I cloned my git repo with the whole codebase, to the webroot and created the database and imported a copy of the mysql database.

I then edited the settings.php file to match the new database name, user and password. Using SSH and Cygwin I can login and run mysql commands, like 'show databases' etc. So I know that the mysql connection works too.

But when I try to test the site from a browser I just get a white screen, that times out after a couple of minutes.

I have read this artcile How to see the error messages when I get the white screen of death?, and I have added the suggested lines in order to show error messages in both index.php and settings.php with no change whatsoever. Just a white screen and the busy icon turning.

So maybe there is something in .htaccess that needs to be changed? I tried to uncomment the rewritebase line and adding the site name, with no luck.

  RewriteBase /

The phpinfo.php file in the webroot opens without problems. So I guess it must be somehting odd with the site all the same.

The file structure on the web server does not include any public_html folder. This is how it looks and I have cloned my site directly into this folder:

/home/httpd/example/www.example.com

Is that the problem here? That Drupal 7 needs a another folder structure?

This is what the server error log looks like, after the timeout:

PHP Fatal error:  Allowed memory size of 134217728 bytes exhausted (tried to allocate 130968 bytes) in /home/httpd/example/www.example.se/includes/bootstrap.inc on line 966

After increasing the memory_limit from 128 MB to 512 MB, the apache server's error message stops complaining about the memory and instead shows this message:

Script timed out before returning headers: index.php

I now tried to do a fresh install of a Drupal 7 site with a new database, which actually worked. I then changed the database settings in settings.php to call my original site database. And that worked to.

So now my code is on speaking terms with the right database. But I have no git branches and all my images an so forth in the default/files folder is missing. But why did this work? Is there a step when deploying a Drupal site to a brand new server with git, that I missed? The git repo contains everything that is needed, but still it didn't work. Please help, if anyone recognizes this behavior.

In case anyone else is struggling with the same problem, here is how I could partially solve it and open the site without the white screen.

In the settings.php file I commented out this line:

// $conf['memcache_servers'] = array('localhost:11211' => 'default');

So if you are using Memcache and are moving to a new environment, try the above if you encounter a white screen problem.


Show views display based on exposed filter value I've a views with 2 different displays which are Picture View and List View, both sharing the same exposed filter(the query string).

I have an exposed filter block, one of the exposed filter(Radio Button) is View by: 1) Picture view 2) List View

How to show the respective views result based on user selection (View By filter)?

Updates:
My intention is to let the user to choose which Display she wants to see before clicking the Apply/Search button of the exposed filter block. There is only ONE display at a time, no tabbed/links for multiple display option. Solution similar to Views Mode module is not i looking for.

I find out two methods here.

Method 1: Use set_display function

function mymodule_views_pre_view(&$view, &$display_id, &$args)
{
 //To get the query string to find out the field value
$query = drupal_get_query_parameters($_GET, array('q', 'page'));

if( $query['viewby'] == 'photo')
 {
  $view->set_display('view_photo');
 }
}

Method 2: drupal_goto (if the two displays are not sharing the same exposed filter)

function mymodule_views_pre_view(&$view, &$display_id, &$args)
{
 //To get the query string to find out the field value
$query = drupal_get_query_parameters($_GET, array('q', 'page'));

if( $query['viewby'] == 'photo')
 {
  //build up the the query string here
 $query['filter_a'] == 'xxx';
 drupal_goto('viewphoto_path',array('query' => $query));
 }
}

To my case, i used Method 2.

I am really new to drupal, and not sure are these methods will cause any problem or not.
Let me know if they are ok.


Twig conditions for node/page/view in page-title.html I am trying to set different classes in the page-title.html.twig based on what drupal is actually showing. The first condition works in a node template, but not in the page-title.html. This is a pseudo-code of what I am trying to achieve:

{%
  set classes = [
    'title--h1',
    node.type.entity.label == 'Blogpost' ? 'ico ico--time',
    page.machine_name == 'about_me' ? 'ico ico--world',
    view.machine_name == 'blogpost_list' ? 'ico ico--target'
  ]
%}

Try adding this to your MYTHEME.theme. This will provide the machine name value to your page.html.twig template files.

MYTHEME.theme:

/**
 * Implements hook_preprocess_HOOK().
 */
function MYTHEME_preprocess_page($variables) {
  $variables['machine_name'] = $variables['page']['#type'];
}

Then in page.html.twig:

{%
  set classes = [
    'title--h1',
    machine_name == 'about_me' ? 'ico ico--world',
  ]
%}

{{ machine_name }}

For node.html.twig templates, use bundle to get the machine name:

{%
  set classes = [
    node.bundle == 'content__type' ? 'one-class' : 'another-class'
  ]
%}

You cannot access the bundle type in MYTHEME_preprocess_page_title() directly.


Drupal 8 what is the ajax event for auto complete dropdown? Drupal 8, what is the ajax event for auto complete dropdown? i have created form alter, there i am altering my form field that is auto complete field, so now what is the ajax event for this auto complete drop down.

change,
select,
keyup all are not working for this.

use autocompleteclose event.

#ajax' = array(
  'callback' =>'get_user_details',
  'event' => 'autocompleteclose',
);


How to have users set a value for a flag field upon flagging? I added a field (Text list of options) to my flag.  But, when a user flags the content, they don't get a chance to set the value for the field (the flagging form does not show the field to edit).  Instead, the user has to flag the node, then go to the flag edit page, then set the value, and then re-save the node. Instead, I want the user to set the value of the field upon flag creation.
In other words, I want to use flags like I use nodes. With nodes, when you add a field to a node, that field is shown on the node creation form, and users with permission to add the node can also set the value for the fields on the node.
How do I do this in Flag?

You need to read the flag admin options more carefully.
On /admin/structure/flags/manage/MYFLAG, under Display options, choose "Field Entry Form".  This will give users the options to enter flag fields before the flag is saved.


How to make changes in HTML code and make them show up on site I am working on a Drupal 7 site that is being manged via Github.

I am trying to change the HTML code on one page. The HTML that I am changing is in the [appname]/sites/all/themes/[app] folder. The HTML in this file is identical to what is on the page if I were to go to the [siteurl]/user/login then navigate to the page and press edit. However when I change the HTML on my local branch and push it up to github and then deploy it using heroku it doesn't actually change the page.

My question is how can I change to way this page is displayed in code instead of changing the page on the drupal website itself.

Look into using the Features module. This way, you can convert any configurations that are stored in the database to code, push them up to the repository, and then pull and revert all the features on your test and production site. You can add template work as a custom feature as well. You should stray away from editing code in Drupal and lean toward creating custom themes, modules and features. I would be no where without this module.


Is it feasible to migrate by only migrating content? I am preparing to do a Drupal 7 to Drupal 8 migration. This is not a pure like for like migration. Whilst many of the content types are similar there will be some differences between the Drupal 7 and Drupal 8 content types and paragraphs (i.e. site architecture improvements).
I would have thought that the easiest way to do the migration would be to completely rebuild the site in Drupal 8 and configure and customise it the way I want and then just migrate the content (e.g. users, taxonomy, nodes, etc.); however, according to the Drupal documentation one should not configure the site. From the Drupal "Preparing a site for upgrade to Drupal 8" page

Do not configure the Drupal 8 site
Keep in mind that the upgrade process will overwrite configuration on the Drupal 8 site, so do not do any configuration of the Drupal 8 site until after the upgrade process is complete. This means you do not have to create all the content types and fields manually before running this upgrade. The Migrate module will create them as a part of the migration process. In fact, it is a common best practice to install Drupal 8 using the Minimal install profile, because the Standard profile introduces its own configuration that you might not want to use.

Couldn't I just build and configure the Drupal 8 site just the way I like it and then just migrate the content being sure to customise the migration in order to adjust for any architectural changes? This idea of migrating all content and configuration and then making content changes afterwards doesn't make sense to me.

TL;DR: use Migrate and associated modules to do the heavy lifting, adding in your own code as needed.
Yes, you absolutely can build your configuration first and then migrate content. I'd suggest the following outline approach (you'll still need to read the documentation for Migrate and these modules carefully):

Install the Migrate Tools and Migrate Upgrade modules.
Use migrate upgrade to generate prototype migration configuration, eg. drush migrate-upgrade --legacy-db-url=mysql://user:pass@12.34.56.78/d6db --legacy-root=http://myd6site.com --configure-only
Export the configuration and weed out any migrations that you don't need, such as content type and field definitions. Remove references to these from other migrations.
Edit the remaining configurations to your needs. This can be laborious and for some cases it may be easier to use custom hooks to manipulate data rather than configuring process plugins. However, the process plugins provided by core, supplemented by those from Migrate Plus, are very powerful once you understand them.

These modules will do much of the hard work for you so you can concentrate on the tougher problems you may face, such as dealing with embedded media tags that may require modules that are not ported to D8.
(If you are thinking of moving field collections to paragraphs, the D8 Paragraphs module has everything you need already in place).


Delayed error messages for webform blocks in template I am printing a webform block in my node.tpl.php:

  <?php
      $block = module_invoke('webform', 'block_view', 'client-block-72');
      print render($block['content']);
  ?>

And when I submit the webform with nothing, no error messages are shown. They are shown on the next reload.

If insert the block in admin -> structure -> block, it works fine.

Is there any way to make it work with inserted block in template file?

I've created a new region and inserted the webform block there.


How to obtain raw field value from db table in a view? In Views 2 I am rewriting a field to generate a link that has arguments appended.

One of those fields is referenced as [field_name_value] but outputs 'public' (and translated) value of the field.  In the database the value is stored as 0 or 1 but it outputs No or Yes respectively.  The No/Yes must be coming from the content type template which provides a pair of radio buttons, where 'No' is 0 and 'Yes' is 1.

Is there any way to obtain the raw database (0 or 1) value? Thanks.

One of the last things Views does when it renders a view is to process all the fields raw data and format them according to settings, then theme according to the default or your own custom views templates.

So, if the 'Output format' options in field's settings on the view don't provide what you need, you can get the raw values - before formatting & theming - like so:

Install Views PHP so you can run code from within views fields, arguments etc.
Check the "Exclude from display" option on the fields you want 'raw' to stop them appearing in the output, but still ensure they're in the view data.
Add one "Global: PHP" field for each field for each hidden field.
In the "Output code" at the bottom of the field settings on the new Views PHP field, add something along the lines of print $row->field_you_want_raw.

Since you've got full PHP in these new fields you can format, tweak and merge any raw field data you need.


how to get weight or delta of current field collection item that is being computed Is it possible to get weight(order index) of multi field "field collection".This weight is needed inside computed field which is inside field collection.I tried the following but it returns empty

$wrapper = entity_metadata_wrapper('field_collection_item', $entity);
$instance = field_read_instance('field_collection_item',$wrapper, 'bundle_name');
dpm($instance['widget']['weight']);

Here is the structure

main_content-contains field collection (multi value)
------field collection(s)-contains 1 text field and 1 computed field
------|----item 0
------|-------|-------computed_field <---here how to get weight of field collection item ie 0
------|----item 1
------|-------|-------computed_field <---here how to get weight of field collection item ie 1
------|----item 2
------|-------|-------computed_field
------|----item n
------|-------|-------computed_field

I was searching in wrong path :( this is found at

http://drupalcontrib.org/api/drupal/contributions!field_collection!field_collection.module/class/FieldCollectionItemEntity/7

code for getting delta is

$wrapper = entity_metadata_wrapper('field_collection_item', $entity);
$cur_delta=$wrapper->delta();


How to have two domains for same site, but site working in directory in second domain? Example:

www.domain1.com -> Drupal site in root dir (Managed by Apache)

www.domain2.com/usa -> Drupal site of domain1.com (Managed by Nginx)

The idea is that www.domain2.com/<countrycode> points to the real domain but in a transparent way (User must not see the existence of the real domain).

What I did:

1) Configured nginx as reverse proxy:

## HTTP server.
server {
    listen 80; # IPv4

    server_name emed.com, www.emed.com;

    access_log /var/log/nginx/drupal.log;
    error_log /var/log/nginx/drupal.log;

    keepalive_timeout 75 75;

    root /opt/www/web/drupal;
    index index.php;

    include apps/drupal/drupal.conf;

    location /fr/ {
        proxy_set_header Host $host;
        proxy_pass http://localhost:8080/fr/;
        proxy_redirect http://localhost:8080/fr/ http://www.emed.com/fr/;
    }

}

2) Configured Apache

<VirtualHost *:8080>
        # The ServerName directive sets the request scheme, hostname and port that
        # the server uses to identify itself. This is used when creating
        # redirection URLs. In the context of virtual hosts, the ServerName
        # specifies what hostname must appear in the request's Host: header to
        # match this virtual host. For the default virtual host (this file) this
        # value is not decisive as it is used as a last resort host regardless.
        # However, you must set it for any further virtual host explicitly.
        #ServerName www.example.com

        ServerAdmin webmaster@localhost
        DocumentRoot /var/www/html

        # Available loglevels: trace8, ..., trace1, debug, info, notice, warn,
        # error, crit, alert, emerg.
        # It is also possible to configure the loglevel for particular
        # modules, e.g.
        #LogLevel info ssl:warn

        ErrorLog ${APACHE_LOG_DIR}/error.log
        CustomLog ${APACHE_LOG_DIR}/access.log combined

        # For most configuration files from conf-available/, which are
        # enabled or disabled at a global level, it is possible to
        # include a line for only one particular virtual host. For example the
        # following line enables the CGI configuration for this host only
        # after it has been globally disabled with "a2disconf".
        #Include conf-available/serve-cgi-bin.conf
        Alias "/fr" "/var/www/html/drupal7"
</VirtualHost>

The problem is that Apache must have the Alias fr directive, otherwise Drupal generates incorrect URLs:

www.domain2.com/usa tries to load assets from www.domain2.com/sites/... instead of www.domain2.com/usa/sites/...

Is this even possible withouth using Alias? Because the first domain serves on / (root)

I think you have to check this module  https://www.drupal.org/project/domain
it has the solution for this


How can I within Drupal 7 make updates to an external MS SQL Server database? I have an external MS SQL Server database that I can display some of its contents within the Drupal 7 views module via the Views Database Connector module.

How can I within Drupal 7 make updates to an external MS SQL Server database?

Use the Drupal database API to manipulate the data in the other database. You can use db_set_active() to switch to the other database.


How to save values on each form submit without overriding saved datas? i am having a form with 2 values to save on submit:

 public function submitForm(array &$form, FormStateInterface $form_state) {
    if ($_POST['op'] == 'Import Accounts') {
      $filter = $form_state->getValue('ldap_filter');
      \Drupal::configFactory()->getEditable('amu_import_ldap.settings')
        ->set('ldap_filter', $filter)
        ->save();

      $roles = $form_state->getValue('roles_list');
      \Drupal::configFactory()->getEditable('amu_import_ldap.settings')
        ->set('roles', $roles)
        ->save();
      }

It is working but each save override the previous one.

How can i structure the yml to save a list of datas iterately

/config/install/my_module.settings.yml

ldap_filter: ""
roles: null

i have been trying a schema file although i am not sure it if it is considered at all

/config/schema/my_module.schema.yml

amu_import_ldap.settings:
  type: config_object
  label: 'couple filtreLDAP / roles'
  mapping:
    ldap_filter:
      type: text
      label: 'Filtre LDAP'
    role:
      type: array
      label: 'Rôles'

i have seen things like

  node.type.*:

?

Config items can be arrays, so something like this should work. (Note that I haven't actually set it up to try it).

      $new_filter = $form_state->getValue('ldap_filter');
      $filters = \Drupal::configFactory()->getEditable('amu_import_ldap.settings')
        ->get('ldap_filter');
      $filters[] = $new_filter;
      \Drupal::configFactory()->getEditable('amu_import_ldap.settings')
        ->set('ldap_filter', $filters)
        ->save();

Of course that's a very naive example, you may wish to check you are only adding unique items to the array, and so on.


How do I alter the output of a field using a views handler Currently I'm uning Views PHP to reformat some fields in a view. in the documentation of views it says

  While this module allows you to directly use PHP inside views which may be useful for quick and easy solutions, it is highly advisable to use regular handlers and plugins when available (or even to create one yourself).

In my particular use case, I'm trying to re-format the output of a field that is being loaded by relationship. How would I create a views handler, or a views plugin that does this?

You add your custom views handler using hook_views_data() like so:

function mymodule_views_data() {
  $data = array(
    ['my_table_name'] => array(
      'my_field_alias' => array(
        'real field' => 'my_field_id',
        'group' => t('Testing'),
        'title' => t('Testing'),
        'help' => t('Testing a thing.'),
        'field' => array(
          'handler' => 'my_custom_views_handler_test',
          'click sortable' => TRUE,
        ),
        'sort' => array(
          'handler' => 'views_handler_sort',
        ),
        'filter' => array(
          'handler' => 'views_handler_filter_string',
        ),
        'argument' => array(
          'handler' => 'views_handler_argument_string',
        ),
      ),
    ),
  );

return $data;
}

And then you declare your custom views handler:

class my_custom_views_handler_test extends views_handler_field {
  /**
   * Render some stuff.
   *
   * Data should be made XSS safe prior to calling this function.
   */
  function render($values) {
    $value = $this->get_value($values);
    return $this->sanitize_value($value);
  }
}

Almost all changes you'll be wanting to make should be made in an override of the render function.


How to install Drush 8 on Windows 10? I am currently running Drush 7 and its working fine for D7.

But I want to run it for D8 site. I have also seen many post where it is mentioned that Drush 7 support D8 but its not true.

So i am trying to install Drush 8.

Try to run below command

composer global require drush/drush:8.*

Or

composer require drush/drush:dev-master

./composer.json has been created
Loading composer repositories with package information
Updating dependencies (including require-dev)
Your requirements could not be resolved to an installable set of packages.

  Problem 1
      - Installation request for drush/drush dev-master -> satisfiable by drush/drush[dev-master].
      - drush/drush dev-master requires consolidation/robo dev-master -> satisfiable by consolidation/robo[dev-master] but these conflict with
  your requirements o r minimum-stability. Installation failed, deleting
  ./composer.json.

But unable to get success. Any suggestion how achieve this?

Finally...

using this command

 composer global require drush/drush:8.*

But i need to refer few steps before running this command.

  composer.json  # Removed the line containing drush like below

  {
          "require": {
              "drush/drush": "7.*"
          }
      }

composer global update
composer global require drush/drush:8.*

source https://github.com/drush-ops/drush/issues/2006


Multiple Landing Pages Under Same Url I need some suggestions, I am not sure which direction to go to do this, but I need to do 4 different landing pages, with 4 different urls, example http://site.com/landingpage?blue=1, http://site.com/landingpage?blue=2.

Now everything is almost the same on the landing pages except for a banner thats going to be on the front and on 2 of the landing pages the layout will be different. I am using panels for the pages. Should I make 4 different panels for them or can panels allow me to change different elements on certain urls? How would I do that using panels? Or would you suggest a different module?

Any suggestions is appreciated,
Thanks

a way to do something like you are talking about is creating one panel page with panels variants and showing each one depending on selection rules.

Regards.


UI can't be accessed I noticed 3 issues with my site and I feel they are all related:

The context link is absent from admin/structures. When i type www.example.com/admin/structure/context, it redirects back to www.example.com/admin/structure.
Also Views is missing from the structure menu

Both the Context and Views U.I modules are enabled.

When I go to the /admin/reports/dblog page, the message and operations column are blank as in the image below.

The UI issues started after i re-enabled the modules. I previously disabled them on my site but now need to make some edits.

I have tried clearing cache a couple of times. I have also manually emptied the cache menu table in the Database.

I am logged in as User 1.

I would be grateful if anyone could point me in the right direction.

Thank you.

As per your "after I re-enabled the modules": try to (temporary) increase your PHP memory limit (eg with 25%) to see if you get different results ... Doing so might get to work it as normal again.

That's one of the typial things I (temporary) do if such kind of issues come up (typically after enable of 1 or more extra modules due to which the current memory limit is not sufficient anymore).


Some files are deleted from the files table after CRON execution I am using hook_form_alter() to add a file upload field to the taxonomy term form.
The form itself and the submit are working well. From the submit callback i save the uploaded file using file_save_upload(). This also works well, the is saved in sites/default/files and in the files database. I have noticed that when Drupal CRON is executed the files i saved are deleted, but the other files (from CCK for example) remains in the table. Files are also deleted from the sites/default/files directory.

Here is my code :

/**
 * Implementation of hook_form_alter()
 */
function community_form_alter($form, $form_state, $form_id) {
  switch($form_id) {
    case 'taxonomy_form_term':
      // get the current image if any
      $image = variable_get('community_term_image_'.$form['tid']['#value'], '');
      // load file
      if($image) $image = field_file_load($image);
      $form['identification']['image_preview'] = array(
        '#type' => 'markup',
        '#value' => $image ? theme_imagecache('community-section-title', $image['filepath']) : '',
      );
      $form['identification']['image'] = array(
        '#title' => t('Category image'),
        '#type' => 'file',
      );
      $form['#attributes'] = array('enctype' => "multipart/form-data");
      $form['#submit'][] = 'community_term_form_image_submit';
    break;
  }
}

function community_term_form_image_submit($form, &$form_state) {
  $dir = variable_get('file_directory_path', 'files');
  $save = file_save_upload('image', array(), $dir);
  if($save->fid) {
    // If the term currently contains a picture, we remove it prior to saving
    // the new one
    $current_image = variable_get('community_term_image_'.$form_state['values']['tid'], '');
    if($current_image) {
      $current_image = field_file_load($current_image);
      db_query('DELETE FROM {files} WHERE fid = %d', $current_image['fid']);
      file_delete($current_image['filepath']);
    }
    variable_set('community_term_image_'.$form_state['values']['tid'], $save->fid);
  }
}

file_save_upload():

  The source file is validated as a proper upload and handled as such.
  The file will be added to the files table as a temporary file.
  Temporary files are periodically cleaned. To make the file permanent
  file call file_set_status() to change its status.

You need to use file_set_status() to change the status of the file.

  $save = file_save_upload('image', array(), $dir);
  if($save->fid) {
    file_set_status($save,FILE_STATUS_PERMANENT);
    ...


Defined variables losing value after using drupal_bootstrap We're trying to use drupal_bootstrap to be able to delete a drupal user when a user is inactivated in our internal (non-Drupal) system. It appears that all defined variables set prior to the bootstrap call are losing value as soon as the call is made. Here's the weird part: it only happens on our live server - everything runs perfectly on dev.

Here's the code; I've stuck a whole bunch of error_log statements in so I can see exactly where the variables are disappearing.

//email address is empty; delete institute record - but not if it's user 0 or 1
if($institute_uid > 1) {
  error_log("institute uid right before bootstrapping drupal: $institute_uid");
  //previous line prints and the $institute_uid is correct

  //set the working directory to your Drupal root - necessary for delete user function
  chdir('/home/www/institute');

  //require the bootstrap include
  require_once './includes/bootstrap.inc';

  //Load Drupal
  drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
  //(loads everything, but doesn't render anything)

  error_log("institute uid immediately after bootstrap = $institute_uid");
  //previous line prints but the $institute_uid value is blank

  $test = "123";
  error_log("test = $test");
  //previous line prints and $test value is correct

  user_delete(array(), $institute_uid); //$vuid = institute_uid from new_people
  $body .= '<br />Institute account deleted';

}

Any ideas? We're new to the bootstrap stuff; maybe there's a server setting, or line in a .ini file somewhere in Drupal that needs to change on our live server?

When "register_globals" is enabled, Drupal unsets all global variables before boostrap.

Disable the "register_globals" option in your live server.


Create 2 or more exposed filters for the same view I would like to ask how can I create 2 or more exposed filter for the same view,which can be placed in different places of a site.
E.g. one exposed filter will have 3 fields,the second one will have 7 fields.
thanks

One way is that you can expose the fitler block by configuring (EXPOSED FORM option in views) the "Exposed form in block" to "Yes" for  as I have done below:

This way you will have the exposed filter available as a block at "/admin/structure/block".

Now as you want to create expose filter with 3 fields and 7 fields for the same view so than you do the following for that:

Create view of block type and add the required fields (if you want it to be of fields type).
Add the fields in "FILTER CRITERIA" section and this will be your expose filter fields. (Right now add the 3 fields).
Add another block for the same view, and now the view be same and you have all the fields available you have added in the previous block.
In the new block, add only new expose filter fields (just make sure you select "This page (Override)" while adding the fields for second block.

Hope this will work as you want.


Advanced form block - fields not showing in block configuration I have installed Advanced Form Block (AFB) in a Drupal 7 site.

At first the AFB settings didn't show. But after applying the patch from issue 1863852 that got resolved. I can now create blocks, but in my block configuration form no fields are showing up. I am not getting options like in this image:

Basically I have a content type add content form that I was hoping to be able to split up into different blocks. I created an add type of block but when I go to that blocks configuration page I don't get any options beyond the normal options (no field selection options are presented to me).

Any idea why?

Infact the block isn't displaying at all, and I tried using different content types. When I go to the block configuration and save it I also get these notices:

I have been and am continuing to use Form Block.

Thinking about it those notices appearing would seem to be part of the problem as they would hint that the fields aren't being found and therefore cannot be displayed.

It seems formblock and afb (advanced form block) conflict with each other. On my development site i disabled and uninstalled formblock and then all aspects of advanced form block worked as it should.
I do not want to do this to my production site because I am unsure of whether I will switch due to the work invovled


Taxonomy term missing as type of data to store in new field for content type I have Drupal 6.2. I added a taxonomy term and I am trying to to add it as a new field to a content type. However, I don't see "taxonomy term" as a "type of data to store" when I try to select a field type.

Use the Content taxonomy module. It provides a CCK field type for referencing taxonomy terms.