How to code custom 404 error handling? I was planning on using a new domain name when migrating my legacy site to Drupal. I already have the php script that will translate old urls into Drupal Urls (I'm not using pathauto for that).

Now there is a chance I have to keep showing content on the old domain (mainly for SEO purposes). This site won't have any login or write-backs at all, it basically just shows the content and link to the new site.

How would I intercept the 404's that Drupal would now generate, preferably at a very low bootstrap level since there could be tons of invalid requests?

Update:

Sounds like I could use hook_boot() to intercept every page request early and then have the query string parsed and redirected to the matching node/... page on the same site.

Or, similar to Fast404 I could add an include_once to settings.php and do the redirect there:

include_once('.sites/default/modules/myredirect_module/myredirect_module.inc');

Will there be a big difference between those two options?

You could just use the Fast404 module (if I'm understanding your question correctly).

  Drupal has expensive 404 errors. On an 'average' site with an
  'average' module load, you can be looking at 60-100MB of memory being
  consumed on your server to deliver a 404. Consider a page with a bad
  .gif link and a missing .css file. That page will generate 2 404s
  along with the actual load of the page. You are most likely looking at
  180MB of memory to server that page rather than the 60MB it should
  take.

  That's where Fast 404 comes in. This module combines a very common
  method of handling missing image/file 404 errors (discussed here and
  planned for Drupal 8) with a method created by dpardo (a co-maintainer
  of this project) to deliver super fast 404 error pages for both
  missing images and bad paths. Depending on which method of
  implementation you choose (aggressive or super aggressive) you can
  deliver 404 errors using less than 1MB of memory on your server.


How can I allow users to search for other users based on profile information I have two profiles for my users. First, is "Infomation" machine name "main" and second "About Me" machine name "about_me" and I want to create a page where other users can search for users with specific attributes in their "Information" or "About Me" profile. I'm just starting out with drupal 7.10 so any help would be appreciated.

You can achieve this by using views contextual filters.

or you can use advanced search for users

http://www.yoursite.com/search/user

set the user permission accordingly to view advanced search


Add Dynamic Wrapper div to a Row I have buttons below a slideshow I have created. I want them to be centered whether there be 1, 2, etc. I'm looking to have a wrapper div surrounding them with a class name of "button-count-x" (x being number of buttons). I've tried using a 'foreach' loop and counting the number of $row's, but that is not working.

Note: I am using the "Views Slideshow" module and am using the view's respective 'views-view.tpl.php' file.

<?php $count = 0; ?>

<?php foreach ($fields as $id => $field): ?>
<?php if (!empty($field->separator)): ?>
<?php $count ++; ?>
<?php print $field->separator; ?>

<?php print $count; ?>

<?php print $field->wrapper_prefix; ?>
<?php print $field->label_html; ?>
<?php print $field->content; ?>
<?php print $field->wrapper_suffix; ?>
<?php endforeach; ?>

that's not much to go on, so I'll assume that the module generates one button per slide in the slideshow, and you want them centered underneath the image area ?

It's hard to know without the markup, but a couple of css selectors should do the trick.

for the containing div, if it has an id, or a uniquely addressable class, try something like this:

#container {
    width: 100%;
    text-align: center;
}

and if the button divs or whatever have no convenient id or class, address them something like this:

#container > div {
    display: inline-block;
}

I think you may be better off sticking to css. Post the relevant rendered html, and perhaps we can help.


Need an exposed filter field as select box with values like "Last x days" etc I'm trying to filter my nodes on the basis of last 7 days & last 30 days but the below code is not working for me when I tried this in my custom module, its working as a conversion for text-field to select but not working as a filter

function dreamzen_form_views_exposed_form_alter(&$form, &$form_state, $form_id) {
    $fromdate = &$form['created'];
    $fromdate['#type'] = 'select';
    $fromdate['#options'] = array(
      'All' => 'All',
      'Last 7 days' => '-7 days',
      'Last months' => '-30 days',
    );
    $fromdate['#default_value'] = '';
    $fromdate['#size'] = 1;
}

are you checking, value is equal to '-7 days', it must match to the value of select box.

Hope this may help full.


Twig embedding and field object I'm using Radix and trying to create a Botstrap carousel component with no luck.
This is the code so far. Kint shows me that media object is there with its multiple fields but nothing is rendered.

themes\custom\newtheme\templates\content\node--article--teaser.html.twig

{% embed '@newtheme/carousel/carousel.html.twig' with {'media': content.field_media } %}{% endembed %}

themes\custom\newtheme\src\components\carousel\carousel.html.twig

    {% for item in media.items %}

{{ item.content }}

    {% endfor %}

    Previous

    Next

The only way I achieved something similar was using:

{% for key, item in content.field_club_history if key|first != '#' %}
    {{ content.field_club_history['#items'][key].entity.field_games.value }}
{% endfor %}

The only difference is that field_club_history was EntityReference field to Paragraph of concrete type. Paragraph type then has fields like field_games. Try to use following code example and get fields from specific item that you need.

{{ content.field_club_history['#items'][key].my_field_name }}


how to remove a node with a garbled url I have this stray node showing up in places (mainly menus) on my site - I don't know how it got created, but I would like to delete it and I can't find a way to delete it from the administration interface.

The url looks like this:

www.organization.com /node/dc436a14-ff7d-4ff8-85f2-ee2b4f9e81ad

and when you click it, it goes to the 404 page.

Anyone know a way to delete this node without having to go into the database?

Thanks!

Ok, I found a way to do this.

Went into the specific menu as admin, and looked through the urls each of the menu items were pointing to (painful process when you have 60 some items). Found the menu item and deleted it from the menus interface and that worked.


PHPUnit Testing when a custom class contains drupal calls and references other classes Ok, I am brand new to TDD within the Drupal environment but we have been asked to try write tests where possible for our custom and/or utility/support modules.

I've managed to write some simple PHPUnit tests, but because the classes within my module have some methods that try to load entities (Content Types built via standard Drupal UI) and then do various thing with them, I am having trouble how to bridge this gap.

Currently when I run my tests most of the assertions pass as they are fairly simply but the one is giving me a warning:

1) Warning
The data provider specified for Drupal\Tests\lrgContentTypes\Unit\AuctionEventTest::testGetNodeFields is invalid.
\Drupal::$container is not initialised yet. \Drupal::setContainer() must be called with a real container.

This has only occurred recently because I have now fleshed out the code for the entity class that the parent is trying to pass in the provider.

I am unsure where to go from here, the Drupal 8 documentation seems to be spotty and gives no clear guidance from a basics point of view.

Is there anywhere that gives a definitive set of examples to show how to test methods that try to load a node via Node::load and where Entity Reference Revision objects are expected?

I will post my classes and test classes below in case its relevant.

1) AuctionEventTest class

https://pastebin.com/vkaiPfUD

2) AuctionLotTest class

https://pastebin.com/ptUmF8UJ

3) AuctionEvent Class (Auction Event content type utility class)

https://pastebin.com/NCDy34z2

4) AuctionLot Class (Auction Lot Entity Reference Revision util class)

https://pastebin.com/mmZ0dh1i

If you are doing Unit tests (and not functional tests), you will need to mock the objects you want to use, in the setup of the test. You can read more here: https://www.drupal.org/docs/8/phpunit/mocking-entities-and-services-with-phpunit-and-mocks

If you are using Drupal functions, you should first try to find out if there is an OOP method that can be used to do the same thing - later versions of Drupal have tried to deprecate such functions, and provide OOP alternatives instead. An example is the Time (datetime.time) service, that replaces things like REQUEST_TIME.

If there is no OOP alternative, you can do the following. Imagine you are using db_query() (which, you shouldn't). Instead of using that function direct in your code, you can create a protected function as follows:

protected function dbQuery($query, array $args = [], array $options = []) {
  return db_query($query, $array, $options);
}

Next, for your text, you will create a class that extends the original class. In this test class, you override dbQuery() above:

protected function dbQuery($query, array $args = [], array $options = []) {
  return ['row1' => ['col1' => 'val1'], 'row2' => ['col2' => 'val2']];
}

This mocks a call to db_query by returning an array of values. The last step is to use this new class in your Unit tests, so that when dbQuery() is called, it uses your extended version that returns the array, instead of calling db_query() which is not available to the Unit test.


How to create a machine name for custom table field with transliteration available I think the title is pretty explanatory.
I have a custom table in which i retrieve human readable titles in 'title'. This title could be any language, and since i'm french it could have accents for instance.
I would like to change a title like : "L'océan indien, l'Asie et la végétation" into the 'cleanurl' field : "l-ocean-indien-l-asie-et-la-vegetation".

I've seen this topic that seemed interesting, but neither machine name nor safeword seems to be usable with transliterate (or i don't see how).

I've tried some "custom" function but does not work completely as expected (and is not a serious replacement for transliterate i guess :

function clean_name($string)
{
  $string = html_entity_decode($string);
  $string = str_replace('&#039;', '\'', trim(strtolower($string)));
  $search  = 'àáâãäåçèéêëìíîïðòóôõöùúûüýÿ';
  $replace = 'aaaaaaceeeeiiiioooooouuuuyy';
  $string = strtr($string, $search, $replace);
  $string = preg_replace('/[^a-z0-9-]/', '-', $string);
  $string = trim($string, '-');
  $string = preg_replace('/-{2,}/', '-', $string);
  return $string;
}

What can you suggest to achieve this goal ? I would obviously prefer to use core functions if possible.

EDIT --
@Clive
I tried to use the pathauto/transliteration modules and i've manage to get what i want, but i'm not sure this is the right way.

module_load_include('inc', 'pathauto', 'pathauto');
module_load_include('module', 'transliteration', 'transliteration');
$cleantitle = pathauto_cleanstring(transliteration_get($string));

This might not be the optimal way since as you emphasised : Process the string through the transliteration module, but i'm not at ease enough with Drupal code.
From the code in pathauto_cleanstring(), transliteration_get should be processed automatically if

variable_get('pathauto_transliterate', FALSE) && module_exists('transliteration')

Both are enabled in my Drupal, but if i do
pathauto_cleanstring($string); the transliteration is not aplied.

But again, if nobody tells me why, this works with pathauto_cleanstring(transliteration_get($string));

I don't think core has any such function, but the Pathauto module does.

pathauto_cleanstring():

  Clean up a string segment to be used in an URL alias.

  Performs the following possible alterations:

  Remove all HTML tags.
  Process the string through the transliteration module.
  Replace or remove punctuation with the separator character.
  Remove back-slashes.
  Replace non-ascii and non-numeric characters with the separator.
  Remove common words.
  Replace whitespace with the separator character.
  Trim duplicate, leading, and trailing separators.
  Convert to lower-case.
  Shorten to a desired length and logical position based on word boundaries.

Emphasis mine.


Search api solr result reordering on field value I'm using search_api_solr and search_api_location. I have a view with exposed filters to perform geolocation searches.

I'm trying to reorder search result from a solr query based a referenced node's field. My question is witch hook to use, where i can access node fields and reorder the results.

I already tried:

hook_views_pre_render()
hook_views_post_execute()
hook_views_post_render()
hook_views_pre_view()

but reordering is effectless or i don't have access to node fields.
I'm doing something like this:

$results = &$view->result;
$to_search_top = array();
foreach ( $results as $i => $capacity){
  if ((int) $capacity->{_entity_properties}['field_free_capacity_company_ref:field_last_review'] > 1) {
    unset($results[$i]);
    $to_search_top[] = $capacity;
  }
}

foreach ($to_search_top as $capa) {
  array_unshift($results, $capa);
}

Thank

Finaly i was only able to solve this with hook_preprocess_views_view_table().

$to_search_top = array();
foreach ($vars['rows'] as $index => $row) {
  if ((int) $row['field_company_review_number_1'] > 0) {
    $to_search_top[] = $row;
    unset($vars['rows'][$index]);
  }
}

// Sort reviewed by distance.
usort($to_search_top, function ($item1, $item2) {
    if ($item1['field_free_capacity_coordinates_latlon'] == $item2['field_free_capacity_coordinates_latlon']) {
            return 0;
    }
    return $item1['field_free_capacity_coordinates_latlon'] > $item2['field_free_capacity_coordinates_latlon'] ? -1 : 1;
 });

// Move to results top.
foreach ($to_search_top as $row) {
  array_unshift($vars['rows'], $row);
}


Import nodes with images Im trying to create nodes from CSV also with image in one image field. I'm using Migrate modul in Drupal 8 and Migrate from CSV. Data to node works fine, image download and copy works fine but in node i dont have that image, the image has also record in database but isn't connected with the node. There is my code, does anyone knows where can be the problem? Thanks a lot for advices.
The image field is called - field_uvodni_obrazek
and im using last Drupal 8.4.2

product_data.YML - node import

 dependencies:
      module:
        - migrate_source_csv
    id: product_data
    migration_group: product_migration
    migration_tags:
      - product
      - node
    label: Profile
    source:
      plugin: csv
      # Full path to the file.
      path: 'C:\Users\Hans\Documents\import.csv'
      # Column delimiter. Comma (,) by default.
      delimiter: '|'
      # Field enclosure. Double quotation marks (") by default.
      enclosure: '"'
      # The number of rows at the beginning which are not data.
      header_row_count: 1
      keys:
        - id
      column_names:
        0:
          id: 'id'
        1:
          kod: 'Kod zbozi'
        2:
          title: 'Nazev produktu'
        3:
          refstruct: 'Referenční struktura'
        4:
          kategorie: 'Kategorie produktu'
        5:
          objednani: 'Objednaci název'
        6:
          obrazek: 'Obrazek'
        7:
          popis: 'Krátky popis'
        8:
          rozsireny_popis: 'Rozsireny popis produktu'
    process:
      title: title
      field_produktove_cislo: kod
      field_objednaci_nazev: objednani
      field_refstruct: refstruct
      body/value: rozsireny_popis
      body/summary: popis
      field_kategorie_produktu:
        -
          plugin: explode
          delimiter: '/'
          source: kategorie
      field_uvodni_obrazek/target_id:
            plugin: migration_lookup
            migration: product_image
            source: obrazek
            no_stub: true
      field_uvodni_obrazek/alt:
         plugin: default_value
         default_value: title
      field_uvodni_obrazek/title:
        plugin: default_value
        default_value: title
      uid:
          plugin: default_value
          default_value: 1
      langcode:
               plugin: default_value
               default_value: 'cs'
      type:
        plugin: default_value
        default_value: produkt

    destination:
      plugin: 'entity:node'
      default_bundle: produkt
    migration_dependencies:
      optional:
        - product_image

product_image.YML - image import

id: product_image
label: Import all product images.
migration_group: product_migration
migration_tags:
  - product
  - file
  - image
source:
  plugin: csv
  path: 'C:\Users\Hans\Documents\import.csv'
  delimiter: '|'
  enclosure: '"'
  header_row_count: 1
  keys:
    - id
  column_names:
    0:
      id: 'id'
    6:
      filename: 'obrazek'
  constants:
    file_source_uri: public://import
    file_dest_uri: 'public://produkty/uvodni'
process:
  file_source:
    -
      plugin: concat
      delimiter: /
      source:
        - constants/file_source_uri
        - filename
    -
      plugin: urlencode
  file_dest:
    -
      plugin: concat
      delimiter: /
      source:
        - constants/file_dest_uri
        - filename
    -
      plugin: urlencode
  uid:
        plugin: default_value
        default_value: 1
  uri:
    plugin: file_copy
    source:
      - '@file_source'
      - '@file_dest'
  filename: filename
destination:
  plugin: 'entity:file'

You need to create a connection between image and node, a reference. You should set the fid. Have a look at this example. Also, in my case it was really helpful this post


Building an online print shop I am trying to build an online print shop where user will upload their own images and select the size and quantity of the print they want and pay for the service.I want to use Drupal commerce for the backend.

I don't know how to store the images. Should I store the images as single nodes, or files entities, or products, or something else so that I can easily added them to a product or to the shopping cart?

I have tried googling a solution or something similar, but I haven't get anything.

  The issue with the images is that the same image can be re-order
  multiple times without been uploaded multiple times and also the users
  can upload and delete any of their own images at any time.

I would either add an image field directly to the line item type and expose it to the Add to Cart form (along with any other pertinent fields) or figure out some sort of entity reference scenario with an Inline Entity Form on the line item to show the entity add form in the Add to Cart form. Might be a bit general, but googling any of those topics will turn up more info.


need popup display of term definition in page contents I have glossary terms in site as glossary type content. Client now wants to have each instance of each term linked to the term explanation, to popup when user hovers over term.

Suggestions? Modules? Magic?

Check out the Popups API (Ajax Dialogs) module.


How to insert the node comments form into quicktabs? Im trying to insert node comments inside the quicktab, I can use views to list the comments and make the tab with it, but how to add the "Add comment" form to it ?

Here is a recipe for adding comments to a quicktab: http://www.katbailey.net/blog/go-forth-and-tabbify-quicktabs-30-drupal-7


Why do I have two menu bars in my drupal instance? I noticed while I was building my theme, that I have 2 menu bars at the top of my screen, like so:

I don't see anywhere that would indicate there would be two.

How would I go about fixing that?

You may have 2 toolbars enabled. One is the Drupal 7 default toolbar which in my experience most disable in favor of the the admin_menu.

drush dis toolbar -y

or

drush dis admin_menu -y

Or under the modules config page.


Accessing custom taxonomy term fields in a rules loop I am building a rule that on node save will loop through taxonomy terms added to an entity reference (taxonomy term) field, build up a list of users from an entity reference (user) field in those taxonomy terms, and e-mail those users.

The problem I'm having is that my data selector won't give me the tokens for the user reference field in the taxonomy term loop.  This rules issue tells me that I need to have the "entity has field condition" condition applied or the "content is of type" condition.  Unfortunately all my conditions are referencing the node that is being saved.

I'm guessing that the answer would be to build the loop into some type of component so I can do a second condition check, but I'm not sure what the right approach for that would be.  How can I let rules know what kind of entity I'm looping through, so it will give me access to the custom fields on that entity?

Have a look at the question about "How to access commerce_product field of line-items using Rules to flag the Commerce Product?". The accepted answer to it (disclosure: it's mine ...) explains how that question can be solved (also) by creating a Rules Component, and which looks like so:

{ "rules_perform_an_action_on_a_selected_line_item" : {
    "LABEL" : "Perform an action on a selected line item",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : { "selected_line_item" : { "label" : "Selected Line Item", "type" : "commerce_line_item" } },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "selected-line-item" ], "field" : "commerce_product" } }
    ],
    "DO" : [
      { "entity_fetch" : {
          "USING" : {
            "type" : "commerce_product",
            "id" : [ "selected-line-item:commerce-product:product-id" ]
          },
          "PROVIDE" : { "entity_fetched" : { "product_fetched" : "Fetched Product" } }
        }
      },
      { "drupal_message" : { "message" : "Some details about this product: Product ID = [product-fetched:product-id], Product SKU = [product-fetched:sku], Product Title = [product-fetched:title], Product Creator = [product-fetched:creator]" } }
    ]
  }
}

Note the parameters used in this Rules Component, i.e. selected_line_item ( = the line item being processed). And also note the type of that parameter (a Commerce line item).

The main rule just executes this Rules Component, as part of a Rules Loop in it, whereas in each iteration of that loop the actual line item being processed is passed as the value for that parameter. So with this example in mind, it seems that this might be a solution to your questions:

  How can I let rules know what kind of entity I'm looping through

The type of the parameter you pass to the Rules Component.

  ... so it will give me access to the custom fields on that entity

I think your Rules Component would not need any extra Rules Conditions, though if needed (as shown in my Rules Component example with the Rules Condition related to "Commerce Product"), you could add relevant other Rules Conditions if needed.

For the sake of completeness, some more details about that Rules Component:

By adding the Rules Condition, I got access to the value of the id (key) of the Commerce Product that the line item was about.
Since I had made the value of that id (key) of the Commerce Product avaiable, I could use the Rules Action to fetch an entity by id (entity being the Commerce Product). And by doing that, from then on I had ALL the data (fields) of the Commerce Product available.


How do I access a user image? How can I access a user image in Drupal 8? I am trying to use this code, but I am getting an error.

$account = \Drupal\user\Entity\User::load($q->uid);
$name = $account->getUsername();
$picture = $account->getUser_picture();

Use the following snippet to get the user image.

$user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());
$picture = $user->get('user_picture')->entity->url();

If you want to get the default image when the user account doesn't have an image associated, use the following code.

$field = \Drupal\field\Entity\FieldConfig::loadByName('user', 'user', 'user_picture');
$default_image = $field->getSetting('default_image');
$file = \Drupal::entityManager()->loadEntityByUuid('file', $default_image['uuid']);
$picture = file_create_url($file->getFileUri());


Rules: How to access field values by language I have content in two languages (entity translation). If I want to use it's field values in PHP, I can access them by code like this:

$node->field_name['en'][0]['value']

or

field_get_items('node', $node, 'field_name', 'en')

But Rules load only currently active language. How to access field value in particular language in Rules data selectors?

Use foreach loop for field_name['und']['value']


How to import nodes in drupal 8? There are many posts available for migrating the content to D8. But i am not able to understand. I am stopped at some points.

What I have cleared yet?

  Till now there is no UI available node import.
  Feed module not supporting node import.

What I wants to know?

Is it mandatory to create a custom module to achieve this?
Drush is required?

Try this module to import node data from CSV file. Content Import


taxonomy for downloading files in my e-learning website i sell my tutorials. my files are there in private folder and after paying for each set of files, users have access to download that specific set of files...
to implement that; so far i used this module: "Private files download permission" = Allows by-user and by-role downloads from private file system directories.
so for each set of files i have to created a separate role!
my problem: now i have so many roles and it is getting more difficult to organize them!

now i am thinking of other solutions such as using taxonomy!
i can create a form to upload a file to private folder and assign a taxonomy to it!
1- any user who pay for it, can get that taxonomy and can download it but i don't have a clear idea how to assign this taxonomy to a user after paying?
2- how can i let him download from private folder if that user has the taxonomy?
i can do it all by PHP coding and hooks but is there any module which can do half of the job at least? or if there is no module to help me...can i use Rules to check if a user has a certain taxonomy or not?

One easy way of doing this, is to use hook_preprocess_node(), and in that function, check for that specific term. And depending on that term, you can actually unset() that file download field in the node, and insert "Please sign up", or something, message in it's place.


How to programmatically display a select list label instead of the value? I created a select list box in the following format

Gender
1|Male
2|Female

I want to display the follwing information in a table but I am getting "1" for male and "2" for female.

Here is my code:

function display_results_submissions(){
$results = db_query("SELECT * FROM {users}");
$header = array( t('Name'), t('Mail'), t('Gender'),);

foreach($results as $result){
        $rows[] = array(

            $result->name,
            $result->mail,
            $result->gender,

            );
    }

    return theme('table', array('header' => $header, 'rows'=>$rows));
}

I want to display Male or Female instead of "1" and "2". How can I do so?

I think you should use entity_metadata_wrapper because when the select label changes you don't have to change your code.

Following lines will do what you want:

$wrapper = entity_metadata_wrapper('user', $result->uid);
$gender = $wrapper->field_user_gender->label();

So your code would look like:

function display_results_submissions(){
  $results = db_query("SELECT * FROM {users}");
  $header = array(t('Name'), t('Mail'), t('Gender'));
  foreach($results as $result){
    $wrapper = entity_metadata_wrapper('user', $result->uid);
    $gender = $wrapper->field_user_gender->label();
    $rows[] = array(
      $result->name,
      $result->mail,
      $gender,
    );
  }

  return theme('table', array('header' => $header, 'rows' => $rows));
}

There is a good blog post at http://www.mediacurrent.com/blog/entity-metadata-wrapper


Image styles not working, uploads to to files directory Image styles are not being applied. I have the /files/ directory set to CHMOD 777, GD Library is installed. When you upload an image, it just goes to the /files/ directory, none of the styles are generated into their styles folder. Reports -> status report is clean. Image uploads, but it stays in files directory, no thumbnails are generated, all paths are broken to the image even to the thumbnail in the Media page.

Hosted on AWS EC2 Linux/Apache

.htaccess in /files dir:

# Turn off all options we don't need.
Options None
Options +FollowSymLinks

# Set the catch-all handler to prevent scripts from being executed.
SetHandler Drupal_Security_Do_Not_Remove_See_SA_2006_006
<Files *>
  # Override the handler again if we're run later in the evaluation list.
  SetHandler Drupal_Security_Do_Not_Remove_See_SA_2013_003
</Files>

# If we know how to do it safely, disable the PHP engine entirely.
<IfModule mod_php5.c>
  php_flag engine off
</IfModule>

It's because you do not have the correct folder owner/group.

You need to cd into your /sites folder. Once there:

If you're using Ubuntu do:

sudo chown www-data:www-data -R default

For CentOS it's:

sudo chown apache:apache -R default and disable SELinux

PS: Never give your files folders permission of 777, set it to 775


what variable can i use to identify a specific pages i need to load a diff stylesheet depending upon which page the user is on.

when using:
     themename_preprocess_page(){kpr(&$variables;)}

i thought i'd see a pageId or pageTitle in which i could use for a conditional statement but i'm not seeing those variables. am i overlooking something? what can i use to uniquely identify a page so i can the use drupal_add_css()?

i guess i could do at the node level? but the stylesheet i need to load is really a page level thing.

can someone advise on the best way to do? big thanks in advance

You may have trouble adding CSS with drupal_add_css in hook_preprocess_page because the $styles variable has already been built.

Better to add CSS in hook_preprocess_html or hook_page_build

Note, you should be able to target specific pages in CSS by using body classes.

e.g:

body.page-node-type-article #content{
  background-color:pink;
}

But yes, to check the path, you can use

$arg = arg($index); // system path component
$path = current_path(); // full base system path ($_GET['q']);
$alias = $_SERVER['REQUEST_URI']; // full alias only


Disable creation of a page for a content type and just use teasers? So on my website I have Content Type: Level 3 - Article Page. This page has two node reference fields where you can set Call to Actions, these display teaser versions of other articles, downloads etc and are shown below the body text of the page. See this screenshot:

I now want to also allow users to set Call To Actions on the Level 3 pages for specific Giving/Donations.

So I've created a new Content Type: Giving CTAs. Here a user can add text, a thumbnail, title, default donation amount etc.

The issue is that I only ever want to use these Giving CTAs as teasers rendered as in the screenshot. They will forward to a giving checkout page carrying the donation amount value.  I don't really want full pages to be rendered for each one. So is there a way to cancel the rendering of pages or disable it for this content type? Maybe it's actually disabling the creation of a URL and default node/id URL? I'm not sure :S

As far as I'm aware, every Drupal node created has a "page" created for it, no matter what. You can disable the creation of a user-friendly URL, but all nodes have a node ID, and since the node/id URL path is in reality just a simple query, all nodes can have "pages" generated for them by querying against their node IDs in this way.

I would say as long as you just refrain from placing these content types into a menu, you won't need to worry about it. It's highly unlikely that a user would manipulate a URL on their own in order to find the content's page.


Understand message before updating a module If I go to admin/reports/updates I see modules that need to be updates.

I just need to know what is the difference between the message "Recommended version:..." and the other message with red background. I mean what are the risk of not updating them?

The message on red background are critical or security fixes means the module is insecure or has known vulnerabilities. It's important to you to update flagged (red highlighted) modules as soon possible so you can prevents hacks.

A recommended module means your modules are many version(s) behind the current release, the module is known to be secure, and simply not up to date with features the current module offers.


How do I translate menu link URIs? Is there a way to translate a menu link URI?

When I change it in one language (e.g. http://www.example.com), it is also changed in the other language, where I want a different domain (e.g. http://www.example.de).

Link title and description is working as expected.

It is not possible to translate the menu uri itself. If you want different menu links per language you need to create a unique menu per language, and use block visibility settings to limit each menu block to its respective language.

See this Drupal 8 multilingual hack for a step by step guide: build unique menus per languages


user ability to hide one column only on view What is the best way to give the user the ability to see or hide one column (only one) on a drupal 7 view?  I want to give them a toggle box to be able to hide and unhide the column

Found the answer here http://siripong-computer-tips.blogspot.com/2011/12/hide-table-column-drupal-view-w-jquery.html

View 3 on drupal 7 produces html like this

    Example
    howto
    dynamically
    show/hide

      table column
      Drupal
      Views
      jquery

go to view edit page
Displays -> Page Details -> Page Settings -> Footer
add the following code

Show columns
<form>
<input onclick="toggleVis(this, '.views-field-title')" type="checkbox"> Title
<input onclick="toggleVis(this, '.views-field-body')" type="checkbox"> Body
</form>

using Jquery to toggle hide the column


Using drupal login system for another platform I want to create another site that uses the drupal user login / registration system so that it is integrated with my drupal site. This would allow current users to use this other service without having to register again.
Can someone let me know if this is possible? Sharing login cookie / registration / user validation...etc.

I am using drupal 7.

The Services module provides an HTTP REST API for authentication (amongst other things). So it should be easily usable to let a remote/separated site re-use your Drupal web site user authentication. The following code comes from its documentation and illustrate how to use it for user authentication. The returned user object will contain the session name and id to use in future REST request if more data from the Drupal are needed (for instance to retrieve user profile or content).

// REST Server URL
$request_url = 'http://your-drupal/rest_server_endpoint/user/login';

// User data
$user_data = array(
  'username' => 'user_name',
  'password' => 'user_password',
);
$user_data = http_build_query($user_data);

// cURL
$curl = curl_init($request_url);
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Accept: application/json')); // Accept JSON response
curl_setopt($curl, CURLOPT_POST, 1); // Do a regular HTTP POST
curl_setopt($curl, CURLOPT_POSTFIELDS, $user_data); // Set POST data
curl_setopt($curl, CURLOPT_HEADER, FALSE);  // Ask to not return Header
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($curl, CURLOPT_FAILONERROR, TRUE);

$response = curl_exec($curl);
$http_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);

// Check if login was successful
if ($http_code == 200) {
  // Convert json response as array
  $logged_user = json_decode($response);
}
else {
  // Get error msg
  $http_message = curl_error($curl);
  die($http_message);
}


How to display the blocks to display in certain page in Drupal? Consider a module deserts:

page1:- deserts/*
page2:- deserts/*/*
page3:- deserts/*/*/*

A dynamic content ...

I have three blocks, namely a,b and c:

Block a should be displayed only in page1
Block b should be displayed only in page2
Block a should be displayed only in page3

How should do that restriction?

Use the context module. Though I'm not generally a fan of this module, this is one of the cases where it comes in handy.

Add a condition for a path. So if I want a block on page 1, but not page 2 or 3, I would write the paths like so, one for each block:

Case 1 - Block A

deserts/*
~deserts/*/*
~deserts/*/*/*

Case 2 - Block B

~deserts/*
deserts/*/*
~deserts/*/*/*

Case 3- Block C

~deserts/*
~deserts/*/*
deserts/*/*/*

The ~ means to exclude in this case. After that, add the block to the region you would like for it to show up. You can also add back in specific paths that might otherwise be excluded, and vice versa.


How to detect same user when they submit two webforms? User A submit a newsletter form and come to thank you page. At the thank you page there is another general comment form.

Here is my question: How to detect both of them are belong to User A?

Reason: So that I can extract both information together from database.

Another less obvious solution if using the rules module already is https://www.drupal.org/project/rules_session_vars

Set the variable when the first form is submitted and check for it when the second is submitted. The use rules to do whatever is needed.

Your own prepopulate solution is perfectly fine however. This one just stops someone from hacking the url.


Git making code changes in local branch 'develop' and push to Acquia Cloud Dev I cloned Drupal 8 core and modules from my Acquia Cloud distro into my local repo.

In my local repo I have 2 branches * developand master. Currently I am in develop branch. I made some small changes to the .gitignore file and in sites/default/settings/php

(in the develop branch i want to make all my changes to code, themes and add contributed modules).

Currently i am in develop branch. When i try from Dev desktop: Push code to Cloud Dev I get this message:

  NOTE: Your locally deployed branch 'develop' doesn't match 'master'
  deployed in the Cloud environment 'dev'. You will have to deploy
  'develop' in the Cloud to see your code changes.

I know I get this message because I am currently in develop branch. But what do I have to do exactly before Push code to Cloud Dev to avoid this error message? What is the recommended procedure exactly to make changes to my code locally (on another branch) and Push code to Cloud Dev? And is it advisable to make those changes to code on another branch e.g. develop?

Update:

I select develop in Acquia Cloud dev environment after git push
origin develop. Till when? When do i have to choose master again?
In my local repo i have added branch develop to add all my
contributed modules and to develop the frontend etc. When do i have
to merge it to master exactly? Or do i have to stay on develop
all the time?

This simply means you need your develop branch to be pushed to the remote Acquia Cloud repository.

$ git push origin develop

Once you do so, just select develop in your Acquia Cloud dev environment. You'll now by in synch between your local and remote branch and will be able to push code as you expect.

UPDATE:

Using the develop branch can be permanent or not, it's up to you.
You can, say, have develop always checked out in dev, master in
stage, and a git tag in prod. develop would then be your
cutting-edge branch while master would be safer and primarily for
QA. Sometimes, you'd have to delete develop and create it again
from master to clean things up. It's part of a normal workflow.
Don't be mistaken between a feature branch and a regular branch. develop isn't a feature branch, it's an integration branch. This means that you could have a feature branch locally called, say, twig-fixes that you would merge with develop when you're happy with the changes. You would then test your feature one last time in the develop branch locally and/or on Acquia Cloud, and then would take it from there.

NOTE: always create feature branches from master as it's your stable branch.

Example workflow:

$ git checkout master
$ git pull
$ git checkout -b twig-fixes

Do your work and commit changes to the feature branch, and, when you're ready to test your changes on the Acquia dev environment, merge your branch into the develop branch and push it to origin:

$ git checkout develop
$ git pull origin develop
$ git merge twig-fixes
$ git push origin develop

If all looks good, merge the feature branch into master using the squash option, to compact all commits into one commit only.

$ git checkout master
$ git merge --squash twig-fixes
$ git commit -m "Squashing twig-fixes"
$ git push origin master

If all looks good again in master, then you're free to delete your feature branch.


Reusing view field formatting? I have several views that display data from the same content type, Customer.

I had to decide whether the view should display the teaser and format the teaser in a custom node--customer.tpl.php or to use Views ability to specify exact fields and format those. I decided to use Views to format the fields (under Format->Show->Fields) based on the preference to configure rather than code.

However, I don't want to duplicate this field formatting for each view that needs to display customers.  Is there a way to reuse the field formatting configuration from one view in a another? (besides cloning the entire view) And is there a way to keep them in sync?

The best way to do this is by using a display mode for the content you are trying to display. The whole purpose of display modes is to provide a way to render content in a consistent way across the site.

The field format for views is meant to provide granular control over the content displayed for that specific view. The best way to clone field formatting is to just clone the whole view and modify it from there; however, the first method is definitely the right way to do this.

[Edit] You can use the Entity View Modes module to create custom displays. Once the display is created, you can manage it from the "Manage Display" tab on the content type. If you need further customization to your display, Entity View Modes allows you to provide a custom template for each view mode.


Hook for Node Add Field? For my use case, this question revolves around the entities node and paragraph.

Fields in my projects are created under the following structure:

content_h2
paragraph_h2
content_p
paragraph_p
...

etc...

For example, I'd like to create field_name on a node, check if it exists in paragraph entity storage and if not create it. And the other way around.

I've had some success but it seems like more coding than needed.

Does a hook exist for node add field?

Example form class: field-ui-field-storage-add-form.

By the way, all the hooks are listed here there doesn't appear one that fits the task tho.

You can always add a custom validation to the field add form.

/*
 * Implements hook_form_FORM_ID_alter()
 */
function mymodule_form_field_ui_field_storage_add_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state) {
  $form['#validate'][] = 'mymodule_custom_add_field_validation';
}

/*
 * Custom Validate Callback
 */
function mymodule_custom_add_field_validation(&$form, \Drupal\Core\Form\FormStateInterface $form_state) {
  // the code that performs the check
  // if (......) {
  //   $form_state->setErrorByName('label',
  //     t('This field already exists in another entity'));
  // }
}


How to create a view of nodes that are referenced by a node that references the current node? I have three content types: patient, patient medication, and physician.

Using the Node Reference module, patient medication references the patient content type and the physician content type. How can I create a view with a contextual filter that does the following: When I view a physician node, I want to view all patients that the physician has interacted with. Using the two Node Reference fields in the patient medication content type, how can I display a block of unique patients that the physician has prescribed a medication to?

I basically have it set up like a relational table:
Patient <-- Patient Medication --> Physician  (The arrows represent the node reference)

Create a view of content type Physician and set relationship between
Patient --- Patient Medication & Patient Medication --- Physician keep both relationship required.
Now add all field related with Patient nodes.
Here only a block display with patient and  Patient Medication.


View items content type as css class in view template I have a view which outputs node titles from various content types, what I need is to theme the view template so one of the css classes for each row in my view is the item's content type. How would I do that?

EDIT: I tried to add the code below in the view template file but it doesn't seem to output any code:

<ul class="<?php print $fields['type']->content ?>">

In fact I even tried outputting it as a regular field but it simply seems to be ignored:

<?php print $fields['type']->content ?>

You need to adjust the template (tpl) file that's being used to generate the markup for the Views output. I think everything you'll need as well as a bunch of related and equally important info can be found here: Mustardseed -> Views Theming


Why does the selected payment method comparison always fail? I'm trying with following simplified rule but nothing happens if using maro_credits as payment method!?

{ "rules_pay_with_maro_credits" : {
"LABEL" : "pay with maro credits",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"REQUIRES" : [ "rules_conditional", "rules", "commerce_payment", "commerce_pos" ],
"ON" : { "commerce_pos_transaction_completed" : [] },
"DO" : [
{ "CONDITIONAL" : [
{
"IF" : { "commerce_payment_selected_payment_method" : { "commerce_order" : [ "order" ], "method_id" : "maro_credits" } },
"DO" : [ { "drupal_message" : { "message" : "aklfjaipwoejfipasjfijasdfas" } } ]
}
]
},
{ "LOOP" : {
"USING" : { "list" : [ "order:commerce-line-items" ] },
"ITEM" : { "list_item" : "Current list item" },
"DO" : []
}
},
{ "drupal_message" : { "message" : "test pos event" } }
]
}
}

However the orders in admin - store - orders show up with the payment method, as shown in this screenprint:

http://imgur.com/a/XZeHy

Anyhelp?

Edit:
I used the mentioned selected_payment_method comparison method that pierre referenced below from start on.

cant add more than 2 links, so i have to add multiple pictures like this i guess:
first you see the selected_payment_method input for the version in the actions with conditional and the rule in the view also with what happens

i after changed the rule to use the conditions directly to show that also there it does not work

http://imgur.com/a/5Ekiu

is this more clear now? or you need more specification?

edit2: in the end i added some screens showing the fields that could be found (nothing with payment method)

Edit3:
Ok I added some descriptions in the pictures on imgur to clarify a bit.
In the end I want to be able to subtract user points form users that pay with "maro credits" (that part already works)

As you see in the screenshots I changed the rule having only the event pos transaction completed (that works!)

then condition selected payment method as shown

and action post a message

as you see in following screenshot that does not work (in the orders list you see there is the order with the payment method maro credits

I hope its clear now?

Ah forgot: in the last screenshots you see all the fields I would be able to chose from and there is none with payment method (and i think that is the problem...?)

Part 1 - Getting your rule to work

Try to add a Rules Condition Entity has field to make the appropriate field available for further processing in your Rules. That's also what is mentioned in the Rules UI when you're adding a "data comparison" condition: somewhere it says:

  The data selector helps you drill down into the data available to Rules. To make entity fields appear in the data selector, you may have to use the condition 'entity has field' (or 'content is of type').

Don't believe me (yet) about my recommendation here ... first add an extra Rules Action as your very first Rules Action, to simply display the actual value of that field you try to use within the "If" of your Conditional Rules construct ... Without such "entity has field" Rules Condition, I bet the value of that field will be shown as empty (or blank). Which would then also explain why your "If" always results in a FALSE ...

For a video tutorial that illustrates the importance of this Entity has field condition, refer to Data types and data selection, especially what is shown between about 13:30 and 17:30 in that video.

Note: it's hard to tell from the current content of your question what the exact field (for which to add such Rules Condition) should be in your case. But my best guess is some field about the payment method (possibly method_id?)

Part 2 - Simplify your rule

From the current content of your rule, it seems that you want to perform a Rules Loop as a Rules Action, but only if some condition (the "If" you added using "Conditional Rules" module) is true. And then as the very last Rules Action the rule shows that test pos event message.

If this very last message is just for debugging (i.e if it is not really needed after you get it to work anymore), then it seems to me that you could replace that "If" (added using Conditional Rules) by a regular Rules Condition. And by doing so your rule would not require the Conditional Rules module anymore.

Plan B

As per the comment posted below this answer, you may want to try a completely different approach ... which is based on this commit, and related to issue # 1278156:

Use the Rules Condition Selected payment method comparison, located within the Commerce Payment group.
Check if its value is equal to your 'maro_credits'.


Show Distance in table from openlayers So I followed the instructions from this thread; Need a simple Google Maps solution; lost in the labyrinth of modules. I've gotten everything to work how I need it on my test server a few months ago. The SS below shows how it looks with the distance/proximity working.

Just before I got it working. I had a problem that the distance would not show based off the address or zip searched for. After some tinkering with views (atleast I think it was views), I finally got the distance working.

Now, my boss wants me to push it live and I can't remember how I got the distance to calculate based off an address or zipcode when I expose the proximity in views. It looks like the following;

I've opened both my test server and live side by side and checked over tons of the settings MANY MANY times over and still haven't been able to figure out what I missed. I've tried the following;

Refreshing the Proximity calculations via the openlayers/proximity tab
Tinkering with many different views settings.
Creating new test nodes
Rebuilding the process from the beginning

If you guys can maybe point me in the right direction or just mention SOMETHING that maybe I haven't thought about it would be great help. Thanks in advanced.

Have you got this sorted yet?

Ensure that you're using the "Geofield - proximity" field for output and not the Proximity - distance field. I've tried using the latter and not had it working (yet).


How to display the same field with various nodes in the same row using Views? How do I do something similar in Views with the below SQL query?

select nid,
title AS title1,
type AS node_type,
(select title from node,
field_data_field_node_reference_id
where
node.nid = field_data_field_node_reference_id.field_node_reference_id_target_id
AND
field_data_field_node_reference_id.entity_id = 1)
AS title2,
(select nid from node,
field_data_field_node_reference_id
where
node.nid = field_data_field_node_reference_id.field_node_reference_id_target_id
AND
field_data_field_node_reference_id.entity_id = 1)
AS nid2
from node
where nid=1;

The output in MySQL would be:

nid | title1     | node_type |   title2        | nid2
1   | Some Title | MyNode    |   Another Title | 69

As you can see, they share a relationship by a field called 'field_node_reference_id_target_id'.  Both values, 'title1' and 'title2', are from the same table called 'node'.  I would like to avoid writing my own SQL queries, so is there a way to get views to display a similar output (e.g. node titles in the same row that share a relationship)?

Yes, simply

Add the field relationship your View
Add the required fields to the view
On the relevant field configuration form, select the relationship to use.

For example:

"Title" ( no relationship ) to select from base table and
"Title" ( with relationship ) to select from related data.


The machine name of custom view I created my own view thanks to Views module. How can I check the machine name of that view?

Go to the edit screen for your view. At the top right, just under Displays you will see a button labelled Edit view/name/description (right under the Save and Cancel buttons). This is a drop down. Click on it and choose export view.

The second item in the export is the machinr name of the view:

$view = new view();
$view->name = 'your_view_name';
$view->description = ...


Translatable strings and Drupal primary language I use a lot of modules and templates, in which I have to print a lot of display markups.

My website has primary language FR, but whatever I do, each time I use a translatable string, it's always EN that is set for that t('whatever').

I'd like to be able to write all my custome code in French, and then translate strings into english in the interface.

Is it any way to achieve that?

No unfortunately, strings passed to t() should always be in English.


Selling art with Drupal Commerce - how to approach? I have a fair amount of experience with Drupal 7 but I'm confronted with some requirements that I simply don't know how to think about in terms of Drupal modules, etc. I'm not looking for a step-by-step tutorial; I'd just like to know how I can implement this roughly so I know which direction to head in.

I'm making a personal site for a friend who is an artist. We defined a custom content type, work of art, that allows her to add each piece she has created.

She wants to sell some works of art and simply list others (never sell).
Of the works of art for sale, for some the originals will be for sale, while for others only reproductions will be for sale.
For reproductions, users need to be able to choose from among different sizes.
Even after a work of art is sold, she would like to keep the node published so visitors can see it, though it should no longer be available for sale.

I've already built a gallery of the works of art in Views.  Ideally, I would be able to add the option to purchase each work directly on its node page rather than building a separate store.

Is this going to be relatively straightforward to do in Drupal Commerce?  What is the general approach I should take to this, given the requirements above?

Products you sell are not nodes in Drupal commerce, but are their own entity where you can define product related stuff, like SKU, price etc.

You probably will need two product types, one for originals and one for reproductions.

You will need to create a product reference field on a node or something else in order to display the add to cart form along with product details, this can be done on your work of art content type.

In order to select size, the easiest solution will be to create on product per size, then reference all of them and commerce will do the rest.


PDOException: SQLSTATE[42S02]: Base table or view not found I am getting a PDO error which seems related to the Mass Contact module. I installed, played with and then disabled the Mass Contact module. Now when I run cron I get the error:

  PDOException: SQLSTATE[42S02]: Base table or view not found: 1146
  Table 'drupal.field_data_field_mass_contact_category' doesn't exist:
  SELECT field_data_field_mass_contact_category0.entity_type AS
  entity_type, field_data_field_mass_contact_category0.entity_id AS
  entity_id, field_data_field_mass_contact_category0.revision_id AS
  revision_id, field_data_field_mass_contact_category0.bundle AS bundle
  FROM {field_data_field_mass_contact_category}
  field_data_field_mass_contact_category0 WHERE
  (field_data_field_mass_contact_category0.deleted =
  :db_condition_placeholder_0) AND
  (field_data_field_mass_contact_category0.bundle =
  :db_condition_placeholder_1) LIMIT 10 OFFSET 0; Array (
  [:db_condition_placeholder_0] => 1 [:db_condition_placeholder_1] =>
  mass_contact ) in field_sql_storage_field_storage_query() (line 585 of
  /var/www/modules/field/modules/field_sql_storage/field_sql_storage.module)

If I try to uninstall Mass Contact I get the error:

  PDOException: SQLSTATE[42S02]: Base table or view not found: 1146
  Table 'drupal.field_data_field_mass_contact_category' doesn't exist:
  UPDATE {field_data_field_mass_contact_category} SET
  deleted=:db_update_placeholder_0; Array ( [:db_update_placeholder_0]
  => 1 ) in field_sql_storage_field_storage_delete_field() (line 312 of /var/www/modules/field/modules/field_sql_storage/field_sql_storage.module).

The table 'field_data_field_mass_contact_category' does not exist. It is not even created if I enable the Mass Contact module and create a category.

I have tried clearing all cache tables (using phpmyadmin) both with the Mass Contact module enabled and disabled.

I am using Drupal 7.32 on ubuntu localhost.

I have no idea how to proceed. I have found no relevent solution searching the questions here with "PDOException: SQLSTATE[42S02]: Base table or view not found". Any help/advice about how to proceed to track this problem down appreciated.

I just had the same similar situation happen just today.  I'm not sure if you resolved your issue, but in case you or others have the problem again, there's a simple solution that worked for me.

I'll post it here, but please go to this link (https://www.drupal.org/node/2417855) as a reference to my situation... thanks!

  This is the error message I was getting PDOException: SQLSTATE[42S02]:
  Base table or view not found: 1146 Table 'dbxxx.xxxfile_metadata'
  doesn't exist: SELECT * FROM {file_metadata} WHERE fid IN (:fids_0);
  Array ( [:fids_0] => 38 ) in file_entity_file_load() (line 201 of
  /sites/all/modules/file_entity/file_entity.file.inc)

Here's what I did:

  UPDATE

  I did my own recon work ... somehow, I was able to get out of the
  situation and the error message disappeared. I am either very
  resourceful or EXTREMELY lucky!! lol

  Here's what I did before the error message ... I Installed and enabled
  the following modules:

  Media and File_Entity ... then the error showed up and froze me I then
  tried to disable, but it wouldn't let me. Here's what I did AFTER the
  error message to fix the problem:

  I went directly to the database and disabled the two modules within
  then I ran the "update.php" from my site It then processed the
  "file_entity" module All is good now I'm guessing the module did not
  upload properly ... I don't know, but I'm back online again... whew =)

I hope this helps =)


Can't add a new field of type entity reference! Other field types can be added, but only a field of type "Entity Reference" can't be added.

I am getting a status message "Die Einstellungen wurden gespeichert."(Configuration has been saved), but it should redirect me to the manage field of the content type in which I am adding the content type.

Can someone please help me with this?

It was my browser's cache.

On clearing my browser cache I was able to see the Entity Reference field as well.


Render a field in node_preprocess I need to order my field in a node_preprocess to display it in a ul.

I have this field:
body,
field_cover[image],
field_gallery[2 imgs with title..],
field_video [a link list.. rendered with videojs module],
field_video_desc [a text field..]

I need to render they in 2 lists:

function mytheme_preprocess_node(&$variables){

  $rendered_field = mytheme_field_HTML($variables);

  $element = array (
     $rendered_field['field_cover'],
     $rendered_field['field_gallery_0'],
     $rendered_field['field_gallery_1'],
     $rendered_field['video'] );

  $text = array (
     $rendered_field['body'],
     $rendered_field['field_gallery_0_title'],
     $rendered_field['field_gallery_1_title'],
     $rendered_field['video_desc'] );

  $variables['elements'] = theme_item_list(array('items' => $element, 'type' => 'ul'));
  $variables['texts'] = theme_item_list(array('items' => $text , 'type' => 'ul'));
}

but I need to write mytheme_field_HTML() function and I don't understand how, using Field API, I can retrive the HTML according the default field display used in the current node.

How can I achieve this?

What about leaving the rendering of fields by Drupal and putting your list directly in the template?

Depending the condition about your node rendering, can be based on 1 particular node, or by content type, ... you can use a separate tpl file. For example, if its for a content type gallery, you can create a node--gallery.tpl.php in the templates folder of your activated theme.

Inside the tpl, you can create an HTML structure like this:

<div class="content"<?php print $content_attributes; ?>>

<?php print render($content['field_cover']); ?>

<?php print render($content['field_gallery_0']); ?>

<?php print render($content['field_gallery_1']); ?>

<?php print render($content['video']); ?>

    </

<?php print render($content['body']); ?>

<?php print render($content['field_gallery_0_title']); ?>

<?php print render($content['field_gallery_1_title']); ?>

<?php print render($content['video_desc']); ?>

    </

    <?php print render($content); ?>


Error on hook_theme_suggestions_HOOK_alter() I am trying to set a custom theme suggestion for the item-list template. It does work but I am getting an error message:

User error: "attributes" is an invalid render array key in Drupal\Core\Render\Element::children() (line 97 of core/lib/Drupal/Core/Render/Element.php).

Function:

function MYTHEME_theme_suggestions_item_list_alter(array &$suggestions, array $variables) {
  $moduleclass = str_replace('-', '_', $variables['attributes']['class']);
  $suggestions[] = 'item_list__' . $moduleclass;
}

Not sure what the probleme is here?

Every time it calls the hook, the variables may or may not have the array key 'attributes' - so the error happens on certain hook call, but not others. It's easy to fix, just check if it exists

function MYTHEME_theme_suggestions_item_list_alter(array &$suggestions, array $variables) {
  if (!empty($variables['attributes'])) {
    $moduleclass = str_replace('-', '_', $variables['attributes']['class']);
    $suggestions[] = 'item_list__' . $moduleclass;
  }
}


How to transfer a block from one site to another? I've built a block on my local site and now want to transfer it to a remote site.

I thought this was done via Features, so downloaded the feature files and placed them on my remote server. On the remote site I accessed Features, checked the box of the updated Feature I placed up there and hit save.

I've cleared the cache and theme registry but the new block does not appear on the remote site.

Would anyone know what I've done wrong here?

Have a look at the Bean module. Here is a quote about its project page:

  Think of a Bean as a method to provide new types (compared to node this would be a content type) which then provides an add content interface to create as many blocks as you require (see screenshot below). The bean content can then be placed around the site just like any other block.

This module also works great in combination with the UUID and UUID Features Integration modules. And after you become familiar with the Bean module, you might find other cases in your site where you also want to use this module (which somehow compensates the fact that you need to add another module).

The video tutorial Drupal Bean module tutorial - using Bean Admin UI provides a great introduction to really understand the power of this module, and the kind of things you can do with it (by only using site building techniques, no custom coding involved). It also shows how the Bean module transforms Drupal blocks into fieldable entities.

This module only started as of D7 (because of the "entities" of course that were only introduced in D7), and already has over 22K reported installs. Those who don't use it yet should definitely start looking at it in preparation of some day upgrading to D8. Because this is what is currently shown on its project page (I added the bold markup here):

  This module has been included with Drupal 8 core. Refer to this issue for more information.


Error when creating a custom Twig filter I'm trying to create a custom Twig filter in Drupal 8. The goal is to use my custom filter in a template like so:

{{ a_variable|myfilter }}

I have created a custom module with 3 files:

MODULE.info.yml
MODULE.services.yml
src/TwigExtension/MyExtension.php

The MODULE.info.yml file contains the usual values.

The MODULE.services.yml file contains:

services:
  MODULE.twig_extension:
#   arguments: ['@renderer']  #  <-- Initial code (USELESS)
    class: Drupal\MODULE\TwigExtension\MyExtension
    tags:
      - { name: twig.extension }

The src/TwigExtension/MyExtension.php file contains:

namespace Drupal\MODULE\TwigExtension;

// use Drupal\Core\Template\TwigExtension;  // <-- Initial code (WRONG)

class MyExtension extends \Twig_Extension {
// class MyExtension extends TwigExtension {  // <-- Initial code (WRONG)

  /**
   * Generates a list of all Twig filters that this extension defines.
   */
  public function getFilters() {
    return [
      new \Twig_SimpleFilter('myfilter', array($this, 'myFilter')),
    ];
  }

  /**
   * Gets a unique identifier for this Twig extension.
   */
  public function getName() {
    return 'MODULE.twig_extension';
  }

  /**
   * Replaces all instances of "animal" in a string with "plant".
   */
  public static function myFilter($string) {
    return str_replace(array('animal'), array('plant'), $string);
  }

}

My initial code got following error: "Call to a member function generateFromRoute() on a non-object in /core/lib/Drupal/Core/Template/TwigExtension.php on line 224".

But I have now corrected the code following lauriii's answer and it works perfectly!

The problem in the code above is that your Twig extension class is extending the internal Drupal Twig extension class. That breaks the Twig extensions added by Drupal core and that's why you are getting the error.

To fix this, you should make your Twig extensions extend Twigs internal Twig extension class. Your class should be defined like this:

class MyExtension extends \Twig_Extension {

After making that change, you can also remove arguments set for that class from the MODULE.services.yml


custom module js loaded before the module which it depends, Drupal.behaviors The "Drupal.behaviors" doesn't behave as "document.ready", if I use a document.ready I will have the correct map but if I do a Drupal.behaviors, there will be an error related to the openlayers library function which is not found :(

After check, the OpenLayers.js is loaded after my module js.
Is it possible to make it load after another one ?
I though adding a dependency on another module would make him load before the other one.

If I use a setTimeout it's working but it's not the best solution !

Do you have any idea how I can do that ?

Thank you guys

(function ($) {
Drupal.OL_lat_long = Drupal.OL_lat_long || {};
    Drupal.behaviors.OL_lat_long = {
         attach: function (context, settings) {
                setTimeout(function(){
                    var map = $('#openlayers-map').data('openlayers').openlayers;
                    var pointLayer= map.layers[1];
                    console.log(pointLayer);
                    proj4326 = new OpenLayers.Projection("EPSG:4326");
                    proj900913 = new OpenLayers.Projection("EPSG:900913");
                    Drupal.OL_lat_long.dragPoint();
                    Drupal.OL_lat_long.actualizeLatLong();
                    Drupal.OL_lat_long.clickMap();
                    $('#redrawPoint').click(function(){
                        Drupal.OL_lat_long.redrawPointOnMap();
                        Drupal.OL_lat_long.actualizeLatLong();

                    });
            },200);
        //  });
        }
    }
}(jQuery));

Maybe you could try altering the weight of the script you add in your module?

drupal_add_js(drupal_get_path('module', 'MYMODULE') .'/myscript.js', array(
    'weight' => '999',
  )
);


Best way to build bio content specific to the user I'm creating a website where users can report on news in their area. Needless to say, I'm hoping to have thousands of users eventually.

I'm wondering what's the best way to give them a place to add/manage a biography about themselves. What should I do between the following options?

Add a field in the user profile database and call the database on my template override
Create a new content type named bio, treat it as a page and use entity/views to display the correct bio page based on the search

Originally I was going to go with the user database path, but something inside me is nagging me to treat bio's as pages for easier theming/searching. I think it's because I want the bio to be searchable like the articles are, and display as a whole page when selected without having to write a lot of backend code or more template overrides.

If the bio pages can be created for people without an account on the site, then I would create a new content type to use for the bio data; if the bio data needs to be strictly linked to the user profile, I would add new fields to the user accounts.

I would also create a new content type if I want the bio information to be completely searchable. When searching for users, the User module looks just for the username or the user email (in the case the user who is searching as the permission of administering users).

  $find = array();
  // Replace wildcards with MySQL/PostgreSQL wildcards.
  $keys = preg_replace('!\*+!', '%', $keys);
  $query = db_select('users')->extend('PagerDefault');
  $query->fields('users', array('uid'));
  if (user_access('administer users')) {
    // Administrators can also search in the otherwise private email field,
    // and they don't need to be restricted to only active users.
    $query->fields('users', array('mail'));
    $query->condition(db_or()->condition('name', '%' . db_like($keys) . '%', 'LIKE')->condition('mail', '%' . db_like($keys) . '%', 'LIKE'));
  }
  else {
    // Regular users can only search via usernames, and we do not show them
    // blocked accounts.
    $query->condition('name', '%' . db_like($keys) . '%', 'LIKE')->condition('status', 1);
  }

To search users basing on the content of any field attached to user accounts, you should use a module that implements user search differently from the User module, or create yourself one.

As for changing the template used for user accounts, that is not different from changing it for a node; the only difference is the template file used by default: user-profile.tpl.php for a user account, and node.tpl.php for a node.

You could also use the Profile 2 module; in this case, the profiles would be an entity different from nodes, and they would be fully searchable with the Views module or the Search API module.


Set value for start/end date field labels in hook_form_alter how can I replace the labels of start/end date for a date field via form_alter? the code below only works for the fieldset. The "to" needs to be removed.

$form['field_my_dates']['und']['0']['#title'] = t('My new title');

Code below not working neither, please help me to figure out how to do it! I forgot to mention that I'm using the popup widget for the date field.

function mywebform_date_combo_process_alter(&$element, &$form_state, &$context) {
    if ($element['#field_name'] == 'field_my_dates') {
        $element['value']['#date_title'] = 'From';
        $element['value2']['#date_title'] = 'To';
        $element['value2']['#title'] = t('');
    }
}

function mywebform_date_part_label_date($vars) {
    if ('field_my_dates' == $vars['element']['#field']['field_name']) {
        return t($vars['element']['#date_title']);
    } else {return t('Date');}
}

Something similar to below might help,change combo field title from 'to:' to none:

function mymodulename_date_combo_process_alter(&$element, &$form_state, &$context) {
    $element['value2']['#title'] = t('');
}

To change From and To date field labels,implement

function mymodule_date_part_label_date(&$vars) {
    if ($vars['element']['#field']['field_name'] == 'yourfield_machine_name') {
      if ($vars['element']['#date_title'] == 'Date Start date') {
        return t('Date (From:)');
      } elseif ($vars['element']['#date_title'] == 'Date End date') {
          return t('Date (To:)');
        }
    } else {
        return t($vars['element']['#date_title']);
    }
}


Give permissions to users to edit Drupal Views content How to give permission to users to edit the content that are in Views.
In Views the FORMAT is:

Format: Unformatted list | Settings
Show: Content | Full content

Thank you in advance.

You can control view page access using "Page settings" section on views settings page,

You can grant permission for views edit to any Role you like form permissions page.

admin -> people -> permission


How to allow user registration based on roles? I have two roles on my site:

Visitor, the normal user who can register on our site without any admin approval procedure
Business role, the business user who can register and add their business to our site, with admin approval.

Can anyone suggest how I can allow registration based on role, so that one requires approval, and the other doesn't?

Also there are two different registration links for users whether they want to register as normal or business user; based on which link the user click, the registration process will take place.

I would recommend that you have all users register on the same page, and have "business" users register for the right to add businesses using either the Apply for Role module or Organic Groups.  Note that Organic Groups will allow you to put a checkbox on the registration page, so business users could check the appropriate request checkbox as they sign up.  An admin would have to approve their request to join the "business" group.


Newbie-question: how to use hooks Ok, this is a newbie-question i'm afraid to ask for some time .. how to use Drupal Hooks?
Yes, i know where to look for the code, but then? Put it in the template-folder, a block, a custom module?

When i google for a tutorial, the most results are for Drupal 6 / before 2010.

Drupal Hooks are a call back mechanism, you name your function modulename_Hook like mymodule_form_alter(). Based on the name of the function, it is called in the proper phase of the Drupal execution. This is an entry point from Drupal into your module.

Using Drupal Hooks doesn't change that much from version to version, the hooks that are available do change from version to version. The old tutorials are still good. The best way to learn how to use hooks is to examine existing contributed modules, or that's what worked for me. Hooks you really need to learn, or that you should start with are the FORM API hooks hook_form_alter, hook_form, hook_form_validate (https://api.drupal.org/api/drupal/includes!form.inc/function/drupal_form_submit/7), ..., hook_menu is generally needed if you're adding a page to the website.

If you can get a copy of "Pro Drupal Development" or "Pro Drupal 7 Development" (http://www.drupalbook.com/ or http://www.amazon.com/Drupal-Development-Experts-Voice-Source/dp/1430228385) it might help as well. Go with the pdf downloads. There are also 2 or 3 day classes you can take, or you can get training at your local Drupal Camp or Drupal convention.


How to NOT change the path/uri after applying a style? I'm working on a module. It uses an API to serve images. One of it's features is calling for a custom resolution image by GET request. So for example

myapi.com/img4324342?w=22&h=55.

I'm currently abusing the style function from the Image module.

I call hook_preprocess_image() and if it detects my effect (my custom style that has my custom effect) it has to return a modified path. But the path get's malformed when I apply a style. I just want to have the original URI so I can use the information inside to construct a REST call. How to prevent that the URI changes after style a.k.a. how to return the original URI as Path?

Background:

It's a brand portal and I'm an intern making the drupal plugin. The company I work for doesn't want the images to be served from the Drupal hosting, only provided by the API. But they ALSO want that adding a different banner for example to every article is still done the same way you normally do: by adding a image style and adding it as a field to the content type

The $vars variabele from hook_preprocess_image() in json looks like this:

{
 "path":"?itok=D1zdawxe",
 "alt":null,
 "style_name":"thumbnail",
 "width":null,
 "height":null,
 "title":null,
 "attributes":[],
 "theme_hook_original":"image",
 "theme_hook_suggestions":[]
}

after applying any effect.

This means that when I don't apply any effect my Path (my Uri) is myscheme://img23423423432 and when I do apply ANY effect it get's malformed to random gibberish like ?itok=D1zdawxe

I've found a kinda nasty solution:

hook_preprocess_image_style(&$variables) {
    $variables['uri'] = $variables['path'];
}

hook_preprocess_image(&$vars) {
    if(array_key_exists('uri', $vars)) {
        $vars['path'] = $vars['uri'];
    }

    if(!isset($vars['style_name'])){
        return FALSE;
    }

    $image_styles = image_styles();

    foreach ($image_styles as $image_style_key => $image_style) {
        if ($vars['style_name'] == $image_style_key) {
            foreach ($image_style['effects'] as $effect_key => $effect) {
                if ($effect['name'] == 'myEffect') {
                    $vars['path'] = generateAPIURL($vars['path'], $effect['data']); //get baseURL from path and URL parameters from data
                    break;
                 }
            }
        }
    }
    return FALSE;
}


subscribe to nodes with entity reference I'm building a music site and have an 'artist' content type that are referenced in product displays, articles etc. I want to enable users to subscribe to these artists and get notified whenever there's a product display, article, event etc. that references the artist.

I've been looking into the Message Stack module to achieve this (http://www.jacksonriver.com/news/message-stack), but haven't been able to make it work with entity reference.

Is this something anyone feels like helping me out with? Could be a very powerful feature IMO.

Try flags + Rules + Views

I use something similar on a jobs site to allow users to subscribe to 'industries' (taxonomy) and be notified when a new job tagged with the industry is created.

In short:
install the Flag module, and create a flag for taxonomy terms.
This flag, when clicked, would fire a rule saying "Subscribe the user to this term" and this would happen with a nice Ajax link that does not reload the page.

Create another rule, saying something like "When new content is posted in X term, email all users who have flagged (subscribed to) that term."

Then build a couple of views:
A page of all the terms (if you need this!), showing the Flag links (these can be text, or you can style them as nice images using CSS).
The second view: A block, emulating a Subscriptions block - basically this block would appear on your 'Artists' pages, and it would show the terms together with their flag/subscribe links.

You could build a third block, to be shown on the user's profile page, listing the terms they're subscribed to.
You might want to use the Context module to control the logic of where the blocks appear.


Display Suite layouts not working for field collections Edit\Add forms Even though I have the Display Suite Forms module enabled and applied a layout to this specific field collection, it does nothing for the edit/add forms. If I apply a layout using manage display it works when viewing the appropiate view mode (for example the full view mode).

Does anybody have any idea or hints where I could start looking?

Just had a similar problem with ds and heartbeat module. Maybe my solutions also works for this problem. Just enable the needed submodules in ds - that fixed the problem.


Creating node in installation profile but body field stays empty I am trying to generate nodes in my installation profile. The weird thing is that everything works except the body. First here is the code I use:

$date = new DateTime();
$node = new stdClass();
$node->type = 'article';
$node->status = 1;
$node->uid = 1;
$node->title = 'Test title';
$node->promote = 1;
$node->created = $date->getTimestamp();
$node->timestamp = $date->getTimestamp();
$node->sticky = 0;
$node->format = 3;
$node->language = LANGUAGE_NONE;
$node->teaser = '';
$node->revision = 0;
node_object_prepare($node);
$node->intro[$node->language][0]['value'] = 'introtext index';
$node->body[$node->language][0] = array(
    'value' => 'Body text test',
    'summary' => '',
    'format' => 'filtered_html',
    'safe_value' => 'Body text test'
);
node_save($node);

The weird thing is.. This code works perfect when I add it in the index.php. But when I add this exact same code in the installation profile everything works except the body(it stays empty).

I tried the next two possibilities see below:

$node->body = 'Body text test'

$node->body[$node->language][0]['value'] = 'Body text test'

I also replaced $node->language for 'und' on all possibilities.

Still I find it weird that my code works in the index.php but not in the installation profile. Does anybody have a clue what I am doing wrong or what needs to change?

I know this old, but I just came across it.  It's really difficult to know what's going on without being able to look at all of the code, but my guess would be you are trying to use 'format' => 'filtered_html' before you've define it in the .install.  In the distributions I help to maintain, we always call filter_format_save as one of the first items of business...

http://cgit.drupalcode.org/cm_starterkit_easy/tree/cm_starterkit_easy.install#n14


How do I add an SQL query with  hook_views_query_alter()? I have the following SQL query:

db_query("SELECT content_id, COUNT(*) as count FROM {votingapi_vote}
          WHERE value_type = '%s'  AND value = 1
          GROUP BY content_id;", "option");

If I want to override the view, which code should I put in mymodule_views_query_alter()?

The content of $query is the following:

    views_query Object(
      [table_queue] => Array(
        [node] => Array(
          [alias] => node
          [table] => node
          [relationship] => node
          [join] =>
        )
      )
      [tables] => Array(
        [node] => Array(
          [node] => Array(
            [count] => 1
            [alias] => node
          )
        )
      )
      [relationships] => Array(
        [node] => Array(
          [link] =>
          [table] => node
          [alias] => node
          [base] => node
        )
      )
      [where] => Array(
        [0] => Array(
          [clauses] => Array(
            [0] => node.status  0
            [1] => node.type in ('%s')
          )
          [args] => Array(
            [0] => provider
          )
          [type] => AND
        )
      )
      [having] => Array()
      [group_operator] => AND
      [orderby] => Array(
        [0] => node_created DESC
      )
      [groupby] => Array()
      [header] => Array()
      [distinct] =>
      [base_table] => node
      [base_field] => nid
      [fields] => Array(
        [nid] => Array(
          [table] => node
          [field] => nid
          [alias] => nid
        )
        [node_title] => Array(
          [field] => title
          [table] => node
          [alias] => node_title
        )
        [node_created] => Array(
          [field] => created
          [table] => node
          [alias] => node_created
        )
        [content_id_] => Array(
          [field] =>
          [table] => content_id
          [alias] => content_id_
        )
      )
      [count_field] => Array(
        [table] => node
        [field] => nid
        [alias] => nid
        [count] => 1
      )
    )

Using hook_query_views_alter is something you should do with care as it can very easily come back and bite you when you least expect it. Trust me, I have tried this on some occasions.

hook_query_views_alter is powerful as you can create any query you want, but it should be used like the name suggests, as an alteration. It's not meant to be used by creating a view with an arbitrary query and then completely create the actual query from scratch in the alter hook. This will lead to many confusing moments, like why does the view display something different than what I set up, and why doesn't it change when I change it.

The query from the View looks something like this:

SELECT nid, title, created FROM {node}
WHERE type IN ('provider') AND status = 0

Compared to

 SELECT content_id, COUNT(*) as count FROM {votingapi_vote}
 WHERE value_type = '%s'  AND value = 1
 GROUP BY content_id;

There are two ways to solve your problem, without having to sort to nasty hacks in the hook_views_query_alter function that will be hard to maintain, and probably will give you or the next developer problems down the road.

Use the node table and create a JOIN

The voting api has Views integration but doesn't support that you query the table with views, using it as the base table. It does however support that you create a join (relationship). Most likely you are voting on nodes. If that is the case you can create a base view from nodes and add in the votes as a relationship. See below SS of how to add the relationship and the fields needed.

SS http://tardis1.tinygrab.com/grabs/99f4a5fef7b5f963fa6a64f0be8ad451af21915caf.jpg
Add info to views about voting tables

With hook_views_data_alter, you can add the needed info about the voting tables to be able to query them directly. Views documentation has great examples of how this is done. Then you could create a view that queries the votes and via the Views interface create a query similar to what you posted.


How to override the menu_tree without affecting the admin menus I've worked out how to override theme_menu_tree() using this code in template.php.

function myTheme_menu_tree($variables) {
  return '<nav class="menu">' . $variables['tree'] . '</nav>';
}

However, I've noticed that this is affecting other menus as well.

How do I target only non-admin menus?

You should use theme_menu_tree__MENU_NAME().


Headless Drupal for managing multilanguage resources for Web/Android/IOS apps? A company has content in 10 languages and 3 channels (web, ios, android). It creates a lot of overhead related to translation (external translation company has to be managed, translations sent etc.). Currently there's a dedicated tool to manage translation resources (basically a spreadsheet of strings with key name and values in up to 10 translations) and sometimes global variables (eg. user name) interpolated within. Potentially hundreds of them.

I'm considering using Drupal 8 as a single place to manage both rich content (articles) and low level UI strings. Additionally it would exposed a REST API for these clients. I'm not too concerned with the typical articles, but I want to make sure that working with these low level internationalised strings will be convenient in Drupal.

Some specific requirements are listed below:

1) structure strings hierarchically to allow easy identification of relevant app section by translators:

channel1 (eg ios)
 |--section 1 (eg. screen or step)
       |---key 1 (eg. en:confirm fr: confirmer de: ... )
       |---key 2

2) allow mass exporting of keys via API within whole section or full channel using single request for performance (in some cases such a bundle would be converted to static resources specific for given platform).
Graphql would be great here, any ideas on how to do it generically with REST API (to be able to fetch data hierarchically, either on leaf nodes or more aggregated on higher nodes).

3) Allow editors to search by key or by value in any language.

4) integrate with translation agencies APIs

5) Allow storing multiple versions / workflow states at the same time (published / new keys just added to specific app and waiting for translation / translation awaiting approval). Ideally tag specific versions to mirror various parallel development branches and allow fetching the individual key/ the whole set via API for specific branch for preview purposes.

6) Efficiently edit multiple keys at once in a single screen grid-like manner, rather than having to click x times to switch from one to another. Switching between language values should be really convenient.

I'd really love to know your opinions around how would you model this kind of content, eg/. each key separate entity? or section = entity and key = field? use taxonomy for categorisation? What if I want to store additional data about section, eg. Screenshot - with taxonomy it wouldn't be versioned. Wouldn't using CMS that stores content items in a tree out of the box make more sense?

Also it would be fantastic to get some ideas around whether any additional modules would be useful here (I'm thinking about Drupal 8) and what kind of Admin UI would you expose to manage it (built-in? custom?).

Also there's a key question lurking behind - do you think using Drupal for this is a good idea at all?

Thanks for any suggestions!

Use .po files that drupal uses for translations and sets it under sites/default/files/translations.

Build a custom module that manage the .po files status as yo need above and move it to sites/default/files/translations folder if approved, assume you have created another folders to hold not approved files.

Fetching any content from drupal will be automatically translated to the language you set by changing the path prefix for example (/en, /fr, /de if you used that method for detection).

Editing the translation strings in single click yo have to read the file and display it in a form for each record as a text field and rewrite the file after submit.

Hope that helps


Organic group request membership email issue Can anyone recommend how I can get an emailing system working for when users request to join an organic group on my system?

Right now, my users click the "request membership" links and then provides a message and click a join button. But then nothing else happens.

Neighter the user nor the admin get any email confirmation.

Please help.

For OG 7.x-1.x, I discovered that simply by enabling the Rules module, email notification Rules from OG are made active. That did the trick for me.

(Not sure about OG 7.x-2.x, which makes mention of the Message_Notify module on the OG project page...)


How to show image in teaser of any content I have created a view which displays the recent blog entries made by users...i have placed this block in sidebar...right now the view is displaying only the recent content with the teaser..however i need the view to display the recent content along with the user picture who posted it and display any image in the teaser if the user has also posted an image in the blog...i.e., if there is an image in the blog then it should be displayed in the view and if not then the teaser should be displayed

thanks

Your sentence is not very clear but :

To display user's picture, add "author of the node" relationship to the view and "user picture" field, with the relationship.
To display post's picture, presuming it's in a distinct image field and not in the body, go to your display settings of your content type, in the teaser section, set the image as you want it to be displayed, it will then appear in your view.


I can't install views module. Error Memory or infinite loop Possible Duplicate:
  How do I avoid the error “out of memory”?

In my site, I can't install Views module. When I check it on admin/modules and then I press on save configuration I've got these error:

  Fatal error: Allowed memory size of 268435456 bytes exhausted (tried to allocate 32 bytes) in (...)/public_html/includes/menu.inc on
  line 3714.

This is the code of menu.inc file:

3709  $item += array(
3711    'access arguments' => array(),
3712    'access callback' => '',
3713    'page arguments' => array(),
3714    'page callback' => '',
3715    'delivery callback' => '',
3716    'title arguments' => array(),
3717    'title callback' => 't',
3718    'theme arguments' => array(),
3719    'theme callback' => '',
3720    'description' => '',
3721    'position' => '',
3722    'context' => 0,
3723    'tab_parent' => '',
3724    'tab_root' => $path,
3725    'path' => $path,
3726    'file' => '',
3727    'file path' => '',
3728    'include file' => '',
3729  );

Problem with 'page callback' => '', ??

It's like a infinite loop that crash, because 256 M for Drupal 7 it would be sufficient.

Actually the value of variable memory_limit of php.ini is 256M . I can't increase it because is a shared hosting, and 256M is the limit. I don't have access via SSH

I try to modificated this value in settings.php, but it's locked on 256 by hosting provider

php_info show this:

Directive        Local Value    Master Value
memory_limit     256M           256M

The list of installed non-core modules are:

Administration menu
Boost
Chaos tools
Libraries
Pathauto
Pathologic
Redirect
Smiley
Sub-pathauto
Tagadelic
TagCanvas
Token
Transliteration
XML sitemap

Thank for you reading. Grettings

There should not be any problem if there is 256M ram allocated. What i would suggest is clear your cache and install one module at a time. Like rather then installing the whole views list of module just install one by one. Another good option is to use drush to install modules but unfortunately you do not have ssh access.


How to add custom fields to a page Am newbie here. I just have a problem with fields adding them to a page.
I want fields specificly textboxes and a button to be in a page. This page will be used by my authenticated users. These textboxes will be filled in by the said users then have the system save the info to the DB after click of the button.

How do I do this? I created a content type of this but i can't seem to add them in the page. No article i can find here either that answers my problem. Please help. Am new here and am not a coder.
Thanks y'all.

Drupal allows content to go onto your site, such as a Page or Book through a content type. If you want to show a Page or Book and embed a field or form on that page that is backed by a database -- typically you have to use another module for that which allows you to embed Forms onto existing Page (Node) content.

To do this usually you can use 1 of the following modules:

Webform

  Webform is the module for making forms and surveys in Drupal. After a
  submission, users may be sent an e-mail "receipt" as well as sending a
  notification to administrators. Results can be exported into Excel or
  other spreadsheet applications. Webform also provides some basic
  statistical review and has an extensive API for expanding its
  features.

  Some good examples could be contests, personalized contact forms, or
  petitions. Each of these could have a customized form for end-users to
  fill out. If you need to build a lot of customized, one-off forms,
  Webform is a more suitable solution than creating content types and
  using CCK or Field module.

or

EntityForms

  The Entityform module enables you to create front-end forms (fieldable
  entities), which contain fields that you define! These forms use the
  standard Drupal fields. This means that out of the box, you can use
  any standard Drupal node field!

These modules allow you to embed any form you define through their admin interface into existing page content.

A key difference is in these forms is that Webforms stores its own data in a custom backend difficult to make into drupal (page) content on your website. While EntityForm since it uses Drupal Fields -- it's submitted content may easily be turned into Drupal site content (but need not be).


Enable Node menu automatically I have a need to automatically create an Article node type each time a Basic-Page node type is created - I am using Rules successfully to achieve that effect.

My problem is a Menu link also needs to be created for each Article node created. This means the Provide a menu link checkbox needs to be automatically enabled in the process of creating each Article node - but it isn't.

The image above shows the checkbox I'm trying to automatically enable.

When creating an Article node directly, i:e not using Rules to create the new Article node, the box is checked and things work as normal.

I really need to find a solution which will enable the checkbox as I auto create my node types.

I don't think that it's possible through the UI. But here is how I would do programmatically:

function mymodule_node_presave($node) {
  if ($node->type == 'article') {
    $node->menu['enabled'] = 1;
  }
}

It would make your "Provide a menu link" checkbox as checked automatically.

You can also set all these values if you need to:

EDIT: I'm so sorry I forgot the node_save line in the code. Here is the correction:

function mymodule_node_presave($node) {
  if ($node->type == 'article') {
    $node->menu['enabled'] = 1;
    node_save($node);
  }
}