Finding all Basic Pages not referenced by a main-menu entry I am trying to produce a list of all published English or no-language Basic Pages on my Drupal 7 website that are not in the main menu hierarchy.

Initially, I tried the technique in Finding all nodes not referenced by a menu entry or another node only to find that the suggested SQL command does not match the current Drupal 7 database structure for menus.

After downloading the Data Dictionary and some trial and error, I came up with the following drush command (with the environment replaced by [redacted]):

drush @[redacted] sqlq "SELECT nid, title FROM node WHERE node.type = 'page' AND node.status = 1 AND (node.language = 'und' OR node.language = 'en') AND CONCAT_WS('node/', CAST(node.nid AS CHAR(6))) NOT IN (SELECT link_path FROM menu_links WHERE menu_links.menu_name = 'main-menu') ORDER BY nid"

Unfortunately, this command is returning all published English or no-language Basic Pages on my Drupal 7 website, not just those which are not in the main menu.

After testing some variations, I suspect that "CONCAT_WS('node/', CAST(node.nid AS CHAR(6)))" is the problem but have no idea how to fix it. Replacing CONCAT_WS with CONCAT does not help.

All Basic Pages on this website have 5 or 6 digits in their node ID. It is okay if I have to use a different statement to get all 5-digit node IDs and all 6-digit node IDs.

I had to wrap the cast in a TRIM function:

drush @[redacted] sqlq "SELECT nid, title FROM node WHERE node.type = 'page' AND node.status = 1 AND (node.language = 'und' OR node.language = 'en') AND CONCAT('node/', TRIM(CAST(node.nid AS CHAR(7)))) NOT IN (SELECT link_path FROM menu_links WHERE menu_links.menu_name = 'main-menu') ORDER BY nid"


tableselect showing empty message instead of options I'm trying to populate a tableselect on a form of a custom module. The tableselect is actually visible, but it's displaying the #empty message. I've simplified it to this code:

$form['my_module_overview'] = array(
    '#type' => 'tableselect',
    '#header' => array('parent' => t('Parent'), 'child' => t('Child')),
    '#options' => array(
        1 => array('parent' => 'test1', 'child' => 'test2'),
        2 => array('parent' => 'test3', 'child' => 'test4')),
    '#empty' => t('There are no relationships defined yet.'),
    '#multiple' => TRUE,
);

So I'm seeing the table with the correct headers, but with the message "There are no ...".

I think I'm donig it correct, as the options array contains key-value-pairs with the values being arrays again. And those arrays have the header keys as keys ('parent' and 'child').

So how can I get the data to become visible in my tableselect?

Apparently, something is/was cached because clearing the cache solved it. So there weren't any problems with the code.


How can I get all comments for a node? I have have a content type (Stuff) with an entity reference field (comments) for comments (their type is Stuff comments) with a single field (comment_body).

Inside a controller, I loaded a node by its ID.

How do I get the list of all the comments for that node?

To answer my own question I guess(better alternatives are more than welcome).

use Drupal\Core\Entity\EntityTypeManagerInterface;

class SomeRepository {

  /**
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entity_type_manager;

  /**
   * ProductRepository constructor.
   *
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   */
  public function __construct(EntityTypeManagerInterface $entity_type_manager) {
    $this->entity_type_manager = $entity_type_manager;
  }

  /**
   * @param $node_id
   *
   * @return array|null
   * @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
   * @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
   */
  public function getNodeComments($node_id) {
    try{
      $node = $this->entity_type_manager
        ->getStorage('node')
        ->load($node_id);
    }catch(\Exception $exception) {
      // log here
      // rethrow error or return, whatever works for you
      return NULL;
    }

    try{
      $comment_ids = $this->entity_type_manager
        ->getStorage('comment')
        ->getQuery('AND')
        ->condition('entity_id', $node->id())
        ->condition('entity_type', 'node')
        ->sort('cid', 'DESC')
        ->execute();
    }catch(\Exception $exception) {
      // log here
      // rethrow error or return, whatever works for you
      return NULL;
    }

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

    $comments = $this->entity_type_manager
      ->getStorage('comment')
      ->loadMultiple($comment_ids);

    $comments_array = [];

    foreach($comments as $comment) {
      // Loop over and get whichever fields you want from the comments
      $comments_array[$comment->id()] = [
        'cid' => $comment->id(),
        'owner_id' => $comment->getOwnerId(), // node to which this comment belongs
        'some_field' => $comment->get('some_field')->value
      ];
    }

    return $comments_array;
  }
}


multiple queries in select sql $result = db_query("SELECT {node}.title, {content_type_answer}.field_question_nid, {content_type_answer}.nid FROM {node}, {content_type_answer} ORDER by nid ASC LIMIT %d, %d", 0, 3);
while($ref = db_fetch_object($otvet)) {
    $otvets[] = array($ref->field_question_nid, $ref->nid, $ref->title);
}

I have 2 content types: 1. question, 2. answer.
In {content_type_answer} i have a nodereference field - field_question_nid that gives me the node id of the referenced question and {content_type_answer}.nid - gives me the answer node id.

But the problem is in title, {content_type_answer} table doesn't has a title row. In a code above i've succesfully selected title row from {node} table :D But how to make condition - i need only {node}.title from nodes which have {content_type_answer}.nid?

This is a job for Views.  To expound upon the comments, this is a screen shot of a quick view that will do this:

I created two quick content types, answer and question.  I used the body field just for expediency in both, and the only other field I added was a node reference called question in the answer type.

In the View, I filted on published nodes of type answer, the argument is that node reference field above, with the default coming from the URL.  I output the Title and Body field.  I set the paging options to 4 so that it would output a maximum of 4 answers to match the LIMIT in your query.  I didn't sort the output but you can do that if you want in Sort Criteria.

I created only one quick question and answer.  On my system, the question is nid 379, so:

putting that in as the argument, the view will output any answers (well, up to 4) with that nid as the node reference in question.  Create a block display for this, and you can have this displayed on your node page with the question.

Now, as you mention in the comments, if you are sure you want to do all of this yourself in your page.tpl.php file with db_query()s, feel free to scrape out the query Views has built for you from the preview.  In this case, that would be:

SELECT node.title AS node_title, node.nid AS nid, node_revisions.body AS node_revisions_body, node_revisions.format AS node_revisions_format FROM node node  LEFT JOIN content_type_answer node_data_field_question ON node.vid = node_data_field_question.vid LEFT JOIN node_revisions node_revisions ON node.vid = node_revisions.vid WHERE (node.status = 1) AND (node.type in ('answer')) AND (node_data_field_question.field_question_nid = 379 )

and modify it to your specific needs.


$form_state->setValue() doesn't save value I have an validate code:

public function validateForm(array &$form, FormStateInterface $form_state) {
    parent::validateForm($form, $form_state);

    $form_state->setValue('my_variable', $form_state->getValue('my_variable') + 1);
    $form_state->setRebuild();
}

And I previously set my_variable to 1 if it's NULL:

public function buildForm(array $form, FormStateInterface $form_state) {

    if($form_state->getValue('my_variable') == NULL){
        $form_state->setValue('my_variable', 1);
    }
...

I use ajax callback for form submission and the validation works fine. After click on submit button I display my_variable and I see 2 (before submission it's 1).

But when I hit the submit button again I see 2 again, instead of 3.
Also, when I re-load the page the data is missing (so it's get value 1 again).

How to prevail the value? It looks like I am operating on copy of $form_state instead of reference but I cannot write &$form_state (public function validateForm(array &$form, FormStateInterface &$form_state)) because it gives me an error (as it's not the correct declaration of validateForm method).

If it is a custom variable, you should use $form_state->set('property_name', 'value') (instead of "$form_state->setValue(...)").

Example:

public function validateForm(array &$form, FormStateInterface $form_state) {
    parent::validateForm($form, $form_state);

    // Update custom variable (in PHP "null + 1" equals one)
    $form_state->set('my_variable', $form_state->get('my_variable') + 1);

    // Below is only required when your "buildForm(...)" depends on the variable
    $form_state->setRebuild();
}


How to adjust the display order The HTML structure is the following one:

.........

.........

...

Since Fivestar actually appends its markup to the bottom of the node's content (instead of using Links, for example), its a bit more tricky.

Ideally you would create a seperate node template for your content type, ie: node-story.tpl.php or something like that (depends on your theme).

Once you have a node template you can safely edit, do the following at the top:

<?php
$my_node_content = $node->content['body']['#value'];
$my_fivestar_widget = $node->content['fivestar_widget']['#value'];
?>

Then, instead of <?php print $content; ?>, do: <?php print $my_node_content; ?>

This way, only your node's actual body content will be printed out.

Then, wherever you want, just print out the fivestar widget code!

Here's what it would look like using your markup:

  <?php print $my_node_content; ?>


How do I create a view that shows the results of a content type related to the current page? I have two content types on my site: "mountains" and "trip reports" with the idea being that users can create a trip report for any particular mountain they have visited.

My "trip reports" content type uses an entity reference field so that the user can select from the list of "mountains" content type.

I want to create a view to display as a block on the "mountains" pages that lists the recent trip reports associated with that mountain.  How do I structure my filter in Views?  I can either get all trip reports to show up (i.e. trip reports associated with all mountains, or none to show up!

Here's my current view setup:

Fields:

Content: Title

Filter Criteria:

Content: Published (Yes)
Content: Type (= Trip Report)

Contextual Filters:

Content: Title

Relationships:

Entity Reference: Referencing entity

You need to include a Node ID contextual filter as well that is set to Content ID from URL. Then make sure that each of the Fields are set to relate to the relationship entity reference field you are using. I'll try to explain below.

Adding a Contextual Filter that looks for the Content ID from URL is required as the view will use the found nodeID and use that to know what node it should relate it's fields and relationships too.

You will then want to add a Relationship field that is the Entity Reference field that creates the relationship between the Trips (children) and the Mountain (parent).

Now with the fields, if you just add fields and do not modify any settings, the view will only display content that is available in the original node. For instance, adding the Title field will display the title of the Mountain and not the title of the Trip reports. This is because it doesn't know it should get the information from anywhere else, even though we added the Relationship field before.

This is why you need to modify the fields and set their Relationship to the Entity Reference field. This will now tell the view that even though we are on the Mountain node and have it's ID, the fields are going to output the content related to the entity that is referenced by the nid in the contextual filter.


What is the substitute for update_sql() in D7? I am using update_sql() in hook_update of drupal .install file (D6) ?

Can update_sql() be used for D7 ?

No, it does not exist any longer. You need to use Schema API function dedicated for what you need to be done. For example to rename field you should use db_change_field.


Language missing from node field arrays For some fields, not all, the language index is missing from the field array. For example, here is the body field of the packaged blog content type (using print_r):

[body] => Array
    (
        [0] => Array
            (
                [value] =>
Shirley Temple[...]
                [summary] =>
Shirley Temple[...]
                [format] => html_raw
                [safe_value] =>
Shirley Temple[...]
                [safe_summary] =>
Shirley Temple[...]
            )
    )

Expected structure:

[body] => Array
        (
            [und] => Array
                (
                    [0] => Array
                        (
                            [value] =>
Shirley Temple[...]
                            [summary] =>
Shirley Temple[...]
                            [format] => html_raw
                            [safe_value] =>
Shirley Temple[...]
                            [safe_summary] =>
Shirley Temple[...]
                        )
                )
        )

I have only ever seen this happen on two fields (the one above and another field from a different content type). Other fields on the blog content type are fine. It looks like it is only happening on my development environment, production seems to be fine. If I set $reset to true when calling node_load() then the structure is fine.

field_get_items() returns false and wrapping the node using the Entity API's entity_metadata_wrapper() and calling $wrapped_node->body->value() I gives the following PHP error:

  EntityMetadataWrapperException: Missing data values. in EntityMetadataWrapper->value() (line 83 of /vagrant/web/sites/all/modules/entity/includes/entity.wrapper.inc).

Setup:

  Drupal 7.28
  PHP 5.3.10
  MySQL 5.5.34
  Apache 2.2.22
  memcached 1.4.13

I haven't run into this issue again. I think a Drupal update resolved the problem.


Using filter strtolower in custom Twig Extension return no result I created a module to extend Twig Extension for filter functions. However the usage of strtolower in custom module end up with no result. Below are the sampel code of my custom module.

  public static function removeSpaces($string) {
    $string = str_replace(' ', '-', $string);
    $string = strtolower($string);

    return $string;
  }

Filtering {{ title|removeSpaces }} in template end up with empty.

You have to render the array and then use the custom twig filter:

{{ title|render|removeSpaces }}


How can I add field information to an standard image? How can I automate this. I am having some sort op coupon like website. But I want the coupon code to be placed into an image. With the nessecary information from the rest of the fields, like date and other conditions, company name, etc.

How can I accomplish this?

I assume you already have image installed and a content type set up that you have an image field attached to.

You will need to install the following modules image cache actions and token
 also the following will need to be enabled "Image Effects Text" (this is part of image cahce actions)
Add an image style by going to example.com/admin/config/media/image-styles and clicking add style.
Using the select list under Effect select text and then click add
You will now be in a page where you can set all the txt setting including the actual text to overlay the image with. You can select the type of text using the select list labelled "text source" if you have token installed you can select token and browse tokens for your replacement text.


How to create pages with images in the content? I'm trying to create a page with content that looks like this:

I'm using CKEditor to edit the content, and it allows me to add images to the article. However, the images need to be already present at some URL.

Is there a way I can upload an image (the image of the doctor with a pad) to my drupal site separately, and then use its URL to insert the image in my article?

In other words, how do I upload just an image to my drupal site so that it can be used elsewhere?

You should do something like this.

Have two regions, one with the content (ie the left blurry blob). And one called sidebar. The sidebar region would have a block that you would add the right image. And a block (which I assume would be something like a view or maybe it's manually added) to do the Related Links.

Then you could have a content header region for the top part.

So you would end up with

|  Content Header  |
| Content | Sidebar|

Or at least that is how I would do it.


Views to use currentlylogged in UID or override via URL I have followed this:

Drupal 7 views, filter by owner

I have a situation where I want the view to show only results by author UID of currently logged in user and/or have the URI explicitly provide the UID.

I can get one or the other to work but not both -- the URI scheme I have is:

http://mydomain.local/myproject/%/test/test.html

I was thinking the placement of the % might affect the results -- it does not.

Ideally when someone access the page:

http://mydomain.local/myproject/test/

And they are logged in the see the results specific to them

When someone accesses the page:

http://mydomain.local/myproject/3/test

The see only the results for the specific user UID = 3

Any ideas???

I think what you're going to need to do is clone your display. One display using path 'myproject/test' where you contextual filter uses 'Provide default value' when the filter is not in the URL, with 'User ID from the logged in user' as the type.

The other display will use the path 'myproject/%/test' and since the filter in this case IS provided by the URL, you can do something like 'Show "Page not Found"' if the filter value is not provided by the URL. You'll probably also want to specify a validation criteria using the numeric validator with 'Show "Page not found"' as the action to take if it doesn't validate.


Generating pages with multiple views based on url parameter I wish to generate pages that populate a series of views of different content types based on a parameter in the url.

For example, a user may navigate to:

www.mysite.com/{tag}

The generated page would find all content tagged with the {tag} parameter and present it as a series of views, for example:

Custom page for {TAG}

View 1                 View 2
Item 1 (type A)        Item 1 (type B)
Item 2 (type B)        Item 2 (type B)
etc                    etc

and etc.

I wish to style and theme the resulting page considerably. Ideally I would also make it possible for an end user to style the resulting page.

I am a little unsure what the best 'drupal' way to make such a page is.

a) Is it possible to somehow style and manage the taxonomy page for 'tag' to look how I want?

b) Should I programatically generate the pages in a custom module that searches for content based on a taxonomy term (not even sure how this would be done)

c) Should I generate a series of views then pass parameters to them on each specific page?

d) Is there some other, better way to achieve such a page in Drupal 8?

One final question, which solution would perform best in terms of page loads, or would they all be pretty similar?

Create 7 different views, one for each content type. Create a block display for each view, and use block layout to put them all on one page.

Use contextual filters for the block view to get an argument from the URL. I believe it's a bit odd to configure:
"in the section 'What to do if the URL is not available' select ' Provide default value' and select 'Raw value from URL from the dropdown box. From the 'Path Component' box select the position in the URL that your contextual filter gets its value."

This is a straightforward Drupal approach, should be performant.

Alternatively, you could use Views aggregation to use only 1 view, divided into 7 different groups, and use CSS wizardry to adjust the layout.

Which approach you prefer depends on whether you want to be able to customise each view, and whether you want to use UI rather than CSS to control layout.


How do I display random nodes within a week? I have added Global:Random in Sort Criteria.

It displays nodes that are too old. How could I set the period to 1 week?

The nodes displayed are from last year and year 2013, how to set views to display nodes within a week.

You can achieve it by below steps.

Add filter criteria Content: Post date.
Follow the screenshot for Content: Post date field configurations.


Why can i not add a new link to the main menu? I cannot for the life of me figure why i cannot add a new link to the main menu?!

the error i get reads

'The path 'events' is either invalid or you do not have access to it.'

i have tried numerous work arounds, tricks, checked permission, menu modules, everything i can think of but i cannot understand why.

am clueless, does anyone here know?

Go to Modules list /admin/modules and make sure the Path module is enabled.


Admin UI doesn't see the correct PHP version I have a local development site on Ubuntu and currently my system has PHP 7.4 installed and I can see Drupal site using the correct version in terminal using drush st but if I browse to Admin UI and check the PHP version in status page it is showing different version.
In case it helps Initially the site was setup on PHP 7.2 later on PHP version is updated on the system.

drush @local.local st

Drupal version   : 8.9.0
Site URI         : http://local.d8site.local
DB driver        : mysql
DB hostname      : localhost
DB port          : 3306
DB username      : drupal
DB name          : d8site_local
Database         : Connected
Drupal bootstrap : Successful
Default theme    : bartik
Admin theme      : seven
PHP binary       : /usr/bin/php7.4
PHP config       : /etc/php/7.4/cli/php.ini
PHP OS           : Linux
Drush script     : /var/www/local.d8site.local/vendor/drush/drush/drush
Drush version    : 10.2.2
Drush temp       : /tmp
Drush configs    : /var/www/local.d8site.local/vendor/drush/drush/drush
                  .yml
                  /var/www/local.d8site.local/drush/drush.yml
Install profile  : standard
Drupal root      : /var/www/local.d8site.local/web
Site path        : sites/local
Files, Public    : sites/local/files
Files, Temp      : /tmp

php --version
PHP 7.4.9 (cli) (built: Aug  7 2020 14:29:36) ( NTS )
Copyright (c) The PHP Group
Zend Engine v3.4.0, Copyright (c) Zend Technologies
    with Zend OPcache v7.4.9, Copyright (c), by Zend Technologies
    with Xdebug v2.9.6, Copyright (c) 2002-2020, by Derick Rethans

You have to configure the web server to use the PHP version you want.
For example:
sudo a2dismod php7.2
sudo a2enmod php7.4

sudo service apache2 restart


How to create a rule triggered when saving a node to schedule sending an email at specified date? I have a node of content type task which has a field reminder date. When the node is saved or updated, I want to schedule sending an email to list of users on reminder date.

I have used the Rules module for that, like so:

Rules events:

after node is saved
after node is updated

Rules conditions:

node is of type task
data comparison: site current date greater than reminder date

Rules actions:

add a variable
field list of users(it is entity reference field user is the entity)
new. variable members to email
added a loop
to variable members to mail
add action to loop : send mail

The problem encountered is as follows: if I set current date equal to reminder date, then the email is never sent. But when I set a reminder date greater than current date, the mail notification is not sent on the reminder date. I.e. after the current date becomes greater than reminder date, even if the cron is run, the mail is not sent.

I think I need to use Rules Scheduler for that, right? How can I go about it?

I also saw a Using fields for setting evaluation time, which mentions these steps:

  Using flags to load user lists in Rules
  Scheduling a rules component from a triggered rule
  Some words about rescheduling the evaluation if the event date should change
  Using conditions to make fields available in Rules configuration
  Using a date field to set evaluation time
  Adding an offset to the evaluation (-1 day)
  Verifying the configuration by executing the action set manually

How can I implement this?

I also tried the Date Reminder module but it has a limitation that you can send email only if you manually enter the email address or it will send only to drupal user.

Part 1 - Make sure to include "Entity has field"

First eliminate the possibility that the missing piece to make your rule work is because you didn't include a Rules Condition like "Entity has field" (related to your Reminder date field), as the first Rules Condition.

If you didn't do that yet, then to Rules it is like the value of your Reminder date is simply blank. If needed, enable Rules debugging to double check if the value of that Reminder data has indeed the value that you expect. Refer to my answer to "How can I display the value of a variable inside a condition?" for more details about Rules debugging.

Part 2 - Rework your rule to use the Rules Scheduler

This seems to be a perfect case to actually use the Rules Scheduler (sub-module of Rules). Have a look at my answer to "Rule to store user's last post date and scheduled rule based 30 day reminder", which contains an example of how to use the Rules Scheduler for a variation of your question. The variation is that it is to only eMail 1 user instead of a list of users as in your case, though it uses a field that is similar to your Reminder date field.

The approach using the Rules Scheduler differs from what you tried to do (but couldn't get to work):

it does NOT use a Rules Condition like "check if this the right moment to send such eMail (now)".
instead it performs appropriate Rules Action to schedule such eMails for somewhere in the future. Moreover, it takes into account that the actual date for that eMail may even change in between (ie if the Reminder date field gets updated, then don't send that previously requested eMail anymore).


Menu tree page data not rendering any data if the page does not exist in drupal 7 I have this code to render the menu. I need to make extensive modifications of the elements, so this is why I extract it in this way (multidomain-multilanguage site, I tried everything and this was the only solution I found):

$a = menu_tree_output( menu_tree_page_data("main-menu") )

It works perfectly and $a is an array full of content. Works for every page, except for 404 not found pages. There it returns an empty array.

Any help would be appreciated. I was thinking of storing the menus for the different languages and domains in the database in a personal table and checking if array is empty, in order to extract the info, but I think that is not a good solution. Thank you!!!

I have guessed what happens. It seems that Drupal does not render much of the content in order to aliviate load of the system. So in admin / site / site-information, you establish a different page for 404, and you can customize it. It will now include all menu, links, etc. and personal translatable messages you want to add.


Export news items (including pictures etc.) from Drupal to SQL I would like to export newsitems from Drupal including images to import them into a whole different database.

Is there any module or whats the best way to create an export from Drupal to a SQL, CSV file?

Try Node Export.

  This module allows users to export nodes and then import it into
  another Drupal installation, or on the same site.

  Using this module you can save yourself a lot of time setting up new
  websites that have similar nodes to websites you've already made,
  migrating nodes to new Drupal versions, or between
  development/staging/production sites.

  You will need the same content types for the imports to work (unless
  using Feeds to import), and ideally relevant compatibility with
  fields, and modules.

Node export formats

The format to export with is configurable, and the Node export package comes with the following formats:

  JSON - JavaScript Object Notation code which is known for being
  security friendly. (Drupal 7 only)

  Drupal var export - A Drupalized PHP array which is similar to
  var_export(). (Drupal 7 only)

  Node code - A customized PHP array which is similar to var_export().
  (Drupal 6 only) CSV - RFC4180 compliant CSV code. Ideal for viewing in
  Windows software, and editing data as spreadsheets.

  Serialize - Very robust, though not human readable, representation
  through Serialization using the PHP serialize function.

  XML - XML 1.0 representation which is good for machine-readability and
  human-readability.


how to make an existing listbox autocomplete I have made a content type which has a list box field. now I need to change its widget to autocomplete but as you know list box fields does not have autocomplete widget. now I have added 650 contents of that type and changing the field type would be my last solution because I can't spend time in editing 650 contents!
so is there any way to add an autocomplete widget to the current list box field?

The list box field does not have autocomplete widget unless you use the taxonomy terms, and there are already 650 contents and you do not want to edit the content then you should use the Chosen module, the chosen module will allow you to search within the list. here is the examples page http://harvesthq.github.io/chosen/

following is the module page.
https://www.drupal.org/project/chosen


Drupal 7: adding an image to 1 menu tab The main menu at my Drupal 7.2 site is represented as tabs. I wonder please, how could I add an image to one of the tabs - for example a letter-icon for the last /contact tab?

When I look at the HTML code I see that tab as a class="menu-276 last" list item:

Основные ссылки

Преферанс

Как играть

Рейтинг

Форум

Этюды

Письмо админу

How would you be adding an image there, through editing the core Menu module or maybe there is a nicer way? (a CSS-solution would be ok too...)

Thank you!
Alex

You could use CSS:

#main-menu-links li.menu-276 a {
  background: url(path/to/img.png) no-repeat left;
  padding-left: 16px; /* Change depending on icon size */
}


Change Field Order of Content Type in the database I'm using drupal 7.  The drag drop interface to re-order fields for a content type seems to be buggy.  When I ADD a new Content, i noticed that Translation Settings is always appearing in the middle of my custom defined fields.   I go to Structure>Content Type>MyContent to re-arrange my fields, but no matter how I sort the fields, when I go back to Add My Content, Translation Settings always appears between the 27th and 28th custom defined field.

So I'm thinking of making this change in the database somewhere.  Does anyone know which tables I should be looking at?

Yes, I saw this too. The language form element was added by locale module in code. If you want to change the weight of this element you can create your hook HOOK_form_node_form_alter() and add #weight for $form['language'].


Rules: Display Message every first login per day; reset day 12:00am I am trying to create a rule that will display a message to the user when (s)he logs in for the first time that day.  Reset has to be per day at 12:00am.

Notice: not the first time in 24 hours but the first time that day.

So if user logs in 8/30/2016 11:59 and then 8/31/2016 12:01am then both times (s)he will see message.

I tried to achieve this using event 'User has logged in' and condition: data comparison and comparing last login date with current date and time and offset 1 day.  But it's not workings.  It might be possible to do this with the custom php?

Thanks God Bless.

------------------------------------------Update------------------------------------------

9/1/2016

I need help creating the following rule:

Trigger: User logs in

Condition: User hasn't logged in this today(since 12:00AM)

Action: Display message to user

Am I doing something wrong, or can this be achieved with custom Php?
My attempt is described in first update.  Can't seem to make this work.  The message should only appear every day.

Day = 12:00:00AM - 11:59:59PM

There's a few things to mention here.

Using the [account:last-login] token won't work here; Drupal's login process updates the user account login timestamp before User logs in event.
Using the [account:last-access] token will work however because the User logs in event triggers before Drupal updates the access timestamp.
PHP's strtotime() has a special keyword for the significant time you're looking for; strtotime('midnight') produces the timestamp of when the current day started.

Putting that together, you can create your own custom rules condition via hook_rules_condition_info() and using it compare against the [account:last-access] token in the User logs in event to produce the effect you're looking for:

/**
 * implementation of hook_rules_condition_info()
 */
function MYMODULE_rules_condition_info() {
  return array(
    'MYMODULE_condition_before_midnight' => array(
      'label' => t('Before Midnight'),
      'arguments' => array(
        'last_login' => array('type' => 'date', 'label' => t('The date to compare.')),
      ),
      'module' => 'MYMODULE',
      'group' => t('MYMODULE'),
    ),
  );
}

/**
 * Condition MYMODULE_condition_before_midnight
 */
function MYMODULE_condition_before_midnight($last_login) {
  return ($last_login < strtotime('midnight'));
}


Does securelogin module needs to have a certificate? securelogin seems to be a must to protect against spying login/password.

However it is not clear (to me) whether it requires a SSL Certificate.
I couldn't find this info neither in its module page nor anywhere else  :
http://drupal.org/project/securelogin
(is it too obvious that it does not need to say ?).
Thanks

Yes, the securelogin module requires an SSL certificate. From the README file:

  Before enabling the module, you need to set up your server to support
   23 SSL.


How to inherit 'Date' element in webforms? I tried to simply extend the Date element in webforms like this

/**
 * Provides a 'birthday' element.
 *
 * @WebformElement(
 *   id = "birthday",
 *   label = @Translation("Birthday"),
 *   description = @Translation("Provides a custom form element for birthday date selection."),
 *   category = @Translation("Date/time elements"),
 * )
 */
class BirthdayElement extends Date {}

and I see and can select it in the build options. However when I click on the Test tab, I only see the Label and no date input field. What am I missing?

Webform elements require a Drupal Form API 'Element' plugin and 'WebformElement' plugin.

@see webform_example_element.module


Best way to store custom values in Drupal 7? Is there a good (recommended) way to store custom values in Drupal 7? I've looked into variable_set / variable_get, but then read a comment suggesting NOT to use those for the purpose that I'm needing (unless I completely misunderstood). Here's the comment that I'm referring to:

http://api.drupal.org/api/drupal/includes!bootstrap.inc/function/variable_set/7

"All data created by variable_set() is loaded from the database at bootstrap. Calling variable_get() doesn't perform the database request to get you the data, it simply declares the $conf global and returns the variable you've asked for. Therefore, don't carelessly use variable_set() to store lots of data that you will only use on individual pages or in custom methods. Use your own little table and storage functions for that."

Basically, I'd like a place to store a couple of values, so that I can avoid having to hard code those values within my custom module code. For instance, I'd like to store a current Reporting Year (i.e. 2011), and a current Data Entry Year (i.e. 2012). Is this just something that I'd need to create my own table for?

No, there's no need to create your own table for that. Your use case is a perfect example of what should be stored in the variables table (in my opinion).

Since the data isn't particularly volatile, and you only have a couple of values, I can't see any benefit to adding a custom table for it.

If you start finding yourself storing a lot of data in variables, for example a single different variable for each node of a certain content type, that's when you need to start looking at a custom table.


How to reset validation errors in ajax callback? I would like to not validate fields if I submit button with ajax callback. Currently, on every button click it displays validation errors of another fields. The button doesn't submit the form, it does some another action (add more fields).

You need to set limit_validation_errors to an empty array for it to ignore the rest of the fields in the form.  Here's an example:

  $form['a_field'] = array(
    '#type' => 'button',
    '#limit_validation_errors' => array(),
    '#value' => t('Click here'),
    '#name' => 'a_field',
    '#submit' => array('my_submit_function'),
    '#ajax' => array(
      'callback' => 'my_function',
      'wrapper' => 'my_wrapper',
    ),
  );


How to add a class to the site logo of the system branding block I'd like to add a class of 'svg' to my site_logo img itself using template preprocess. Here's what I have written:

 function mythemename_preprocess_block__system_branding_block(&$variables) {
      $variables['elements']['content']['site_logo']['attributes']['class'][] = 'svg';
      kint($variables);
 }

The kint($variables) readout for where I'd expect my class to be shows DEPTH TOO GREAT. See:

I've seen some documentation saying it has to do with Kint's depth limit, which doesn't seem right as the preprocess isn't very complex. It suggested using +Kint::dump();, which I tried and can't seem to get working. +Kint::dump($variables) didn't work.

You don't need to dig into $variables['element']. In a block preprocess function, the content of the block is available in $variables['content'], so you could use the following code.

$variables['content']['site_logo']['#attributes']['class'][] = 'svg';

Edit:

Altough this is generally valid for blocks, it doesn't work for the system branding block. The branding block overrides the block template with block--system-branding-block.html.twig, where the output of {{ content }} is removed, which breaks the normal rendering of the block. Instead the template contains the html markup for the  tag directly:

{% extends "block.html.twig" %}
{#
/**
 * @file
 * Theme override for a branding block.
 *
 * Each branding element variable (logo, name, slogan) is only available if
 * enabled in the block configuration.
 *
 * Available variables:
 * - site_logo: Logo for site as defined in Appearance or theme settings.
 * - site_name: Name for site as defined in Site information settings.
 * - site_slogan: Slogan for site as defined in Site information settings.
 */
#}
{% block content %}
  {% if site_logo %}
    <a href="{{ path('<front>') }}" title="{{ 'Home'|t }}" rel="home">

  {% endif %}
  {% if site_name %}
    <a href="{{ path('<front>') }}" title="{{ 'Home'|t }}" rel="home">{{ site_name }}
  {% endif %}
  {{ site_slogan }}
{% endblock %}

To reinstate the correct behavior you could override block--system-branding-block.html.twig in your theme and replace the  markup with the render array:

{{ content.site_logo }}

Then the changes made in preprocess are effective again.

Or simply go along with the template as it is now and add the attributes to the html markup of the template.


Can't find variable: Drupal I've created a behaviours in JS but when I'm not connected as admin it show in the console this error:

  Can't find variable: Drupal

When I write console.log(Drupal) in the console explorer it show too the error.

How I can fix this error ?

Edit :

I've defined my library by this way :

myc_facebook:
  version: 1.x
  js:
    js/script.js: {}
    js/timeago.js: {}
  dependencies:
    - core/jquery
    - core/drupalSettings

I integrate my library in a block by this way :

public function build() {
        $config = $this->getConfiguration();

        // Check if the conf
        if (empty($config['token']) || empty($config['pagename']) || empty($config['pageurl']) || empty($config['limit']))
            return array('err' => array('#markup' => t('You might configure this block.')));

        $build = [];
        // Create the wrapper to include facebook posts
        $build['facebook']['timeline']['#markup'] = '

';
        // Push conf vars
        foreach ($config as $key => $value) {
            $build['#attached']['drupalSettings']['myc_fb'][$key] = $value;
        }
        // Includes libraries
        $build['#attached']['library'][] = 'myc_facebook/myc_facebook';

        return $build;
    }

Sounds like you're simply missing the dependency on core/drupal (and posibly also core/jquery) in your library, so that Drupal and JQuery get loaded, which by default it doesn't for anonymous users.


How to convert an image field to an entity reference field We have Drupal Paragraphs using image fields that are media entities. When the media entity is updated with a new image the old images still show unless we manually edit each page, remove the image from the paragraph, and add it back. We have tested using entity reference fields that reference those same media entities and they update. How can we programatically convert the image field to an entity reference field or copy over the references from that field to the media entity field?

In a mile high explanation:

add entity reference field to content type.
you can use rules, or a php-script to load all the nodes for your content type.
loop through each node, get the field value fid of the image paragraph field, assign it to the entity reference field.
save the node

After all the above is done, remove/delete the paragraph bundle.


One product, multiple sellers In a multiseller Drupal Commerce Installation, where every Drupal user being a seller,  Some products can be the same from all users, for example a book from some publisher which can be sold by many sellers. Like in amazon, if one is searching for a book, it comes up and shows other sellers also of that particular book.

Is there a way in Drupal commerce to achieve the same?

Sure! I would recommend you:

Create a taxonomy called "global_sku" ... Amazon calls their psuedo sku "ASIN" ... which is just a number that ties all the "product displays" to one page.
Now ... on your product displays, you could create a taxonomy reference to global_sku's
And then add some Views that will bring in related products based on the taxonomy.


The custom node template file is not working I've created template file named node--product-display.tpl.php as suggested by the Theme developer module, but the changes I made to this file don't show up.
I've also copied the node.tpl.php file in my templates directory. The changes in the latter one show up but that in the former one doesn't.

Do you have any suggestion?

I have cleared the cache. The template file is for a "Product Display" content type, whose machine name is "product_display."

Try node--product_display.tpl.php.

If your file is empty, it will show the default template file; make sure you have write something in your custom file.

Be sure to clear the cache.


individual user profile on click of user name in view I have a view of displaying uploaded image content by different users.
The content is displaying in box in below manner..
i.uploaded image
ii.title of the image
iii.user name and profile picture
iv.category

Now i want that
1. when the user clicks on either image or title one popup will open in a lightbox. in that popup the content should be the node content with all details.
I have done successfully with the module lightbox2 only to popup image but i want that particular node content in that popup.

2.After click on user name or profile picture that page goes to the particular users page with their details and their upload content.
Till now when i click on this link that particular user details opens in tab. but i want either all tabs merge in to one page or the things will display like i expained above.

please help me i am working it on since last 1 week but i am unable to find any solution..

please help/guide me ..

Thanks

You can try Colorbox Node to open particular node content in popup. This module gives the user the ability to display ANY page inside a colorbox modal without the header and footer.

It can be integrated with views also.

Views Integration with node colorbox modal


How to keep class object during form process If I have an object (e.g. student object - this is my own custom class)

I would like to initiate this object during 'student registration' form initialization (or form build) and keep the object until I finish with the form (form submitted).

Is there any placeholder for me to hold this object in the FormBase class?
Where I should declare my class? And how to keep the object?

Example in my code:

<?PHP

namespace bla;

use bla
use bla
use bla

class myCreateForm extends FormBase {

  private $student; // i want to initiate this (new student()) and keep until form submit
  /* where i should declare this? and how to keep it? */

  /**
   * Class constructor.
   */
  public function __construct($param) {
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
  }

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'id_form';
  }

  public function buildForm(array $form, FormStateInterface $form_state) {
    //a lot of code here code here
    return $form;
  }

  public function validateForm(array &$form, FormStateInterface $form_state) {
    //a lot of code here code here
  }

  public function submitForm(array &$form, FormStateInterface $form_state) {
    $output = $this->student->save(); // at the end, i would like to have my own save process which my class will handle it.
    drupal_set_message($output);
  }

}

No, if this is a value object then a service not the answer.

I would recommend you look at entities. Drupal will do a ton of work for you if you use (content) entities for your value objects.

See https://www.drupal.org/node/2192175 for example for documentation, also check out the entity module for additional functionality that is not yet in Drupal core.

With content entities, there is a standard EntityForm class that contains an entity and allows you to save it.

That said, what you are doing basically works, $this->student will be available, but be aware that on the first form submission, formBuild() is called again, so it will build another object. The same for entities. If you really want to prevent that, you need to store your object in the database, e.g. with the tempstore API.


Loop trough a list of referenced nodes, "entity_metadata_wrapper()" style I have a Template node that holds an Entity Reference multivalue field to a series of other nodes, all referenced nodes of the same type. The referenced nodes have a text field whose value I need to get.

In template node I have a computed field that do some calculations using the values from referenced nodes.

Now I have:

$tpl = field_get_items($entity_type, $entity, 'field_plan_tpl');
$values = array();
foreach ($tpl as $field_item) {
  $values[] = node_load($field_item['target_id'])->field_some_field[LANGUAGE_NONE][0]['value'];
}

How can I load the referenced entities in order to get field values, using entity_metadata_wrapper()?

entity_metadata_wrapper() has you covered, the entities will be lazy-loaded as you'd expect:

$wrapper = entity_metadata_wrapper($entity_type, $entity);

foreach ($wrapper->field_plan_tpl as $related_entity) {
  $foo_field_value = $related_entity->field_foo->value();
}


Uploading my Drupal Comerce Files to My Web Host I have installed Drupal Commerce using Kickstart.  It is now running on my local server.  How to I properly upload and configure it on my Web Host?  Any help would be greatly appreciated.

You can use File Transfer tools like WinSCP, FileZilla to transfer you files in your webhost. Then you need to export your database in your local then import in your webhost database. If you have some special configuration like path you may need to update that in your webhost.

Create a database creds in your webhost.

Export you local database and import it on webhost.

Upload your Drupal files

Update your settings.php to change the database information.
....


How do I make twig variables available in node.html.twig accessible in my html.html.twig? I have a boolean field on my Content Type called 'field_bootstrap'. I have some twig logic in my node.html.twig file that, if the field is set to true, includes Bootstrap via HTML inclusion.

What I need is the ability to use my {{ node.field_bootstrap }} logic in the html.html.twig template, instead of the node-level template. This would allow me to reference Bootstrap's CDNs properly in my document's head, rather than its current position in the middle of body.

I assume I need to build a preprocess in mytheme.theme to make something like {{ custom_twig_variable }} available for use in html.html.twig but I'm a little lost on how to complete this :)

Thanks everyone!

Kevin is right, creating a library and then attaching it is the better approach for this.
theme-name.theme
THEME_NAME_preprocess_node(&$variables) {
  $node = $variables['node'];
  if ($node->field_bootstrap->value) { // checks boolean is true
     $variables['#attached']['library'][] = 'theme-name/bootstrap-files';
  }
}

theme-name.libraries.yml
bootstrap-files:
  version: 1.x
  css:
    theme:
      css/boostrap.css: {}
  js:
    js/boostrap.js: {}
  dependencies:
    - core/jquery
    - core/jquery.once
    - core/drupal

and you'll have to put the bootstrap css and js files inside the /css and /js folders of your theme.

Better Yet
Install Bootstrap Library module.
theme-name.theme
THEME_NAME_preprocess_node(&$variables) {
  if (\Drupal::moduleHandler()->moduleExists('bootstrap_library')) {
    $node = $variables['node'];
    if ($node->field_bootstrap->value) { // checks boolean is true
       $variables['#attached']['library'][] = 'bootstrap_library/bootstrap-cdn';
    }
  }
}


How to render multiple values of node reference in the form of an ordered list without views? I have a node reference field that references another node and has multiple values. I want to get an ordered list of the output of that field and display it in the custom node template. I am rendering the node reference as a cck block. Any help or guidance would be greatly appreciated. Thanks.

In D6, you could do something like this:

print '
';
foreach ($node->field_whatever as $foo) {
  print '
';
    $bar=node_load($foo['nid']);
    print l($bar->title, 'node/' . $bar->nid);
  print '
';
}
print '
';

In D7 you'd have to throw in the node language stuff and there might even be something more exciting built in as well but I think they all use divs instead of lists.  (In both you could also create a content field template for this instead of hardcoding it in your node template)


Core image module not found Some how it seems like the core image module is missing from the module list.

Here is the screenshot of the module list:

Also I tried fetching the list using drush.

$ drush pml | grep image
 Image                                Image Attach (image_attach)                                                          Module  Not installed  7.x-1.x-dev
 Image                                Image Gallery (image_gallery)                                                        Module  Not installed  7.x-1.x-dev
 Image                                Image Import (image_import)                                                          Module  Not installed  7.x-1.x-dev
 Image                                Image legacy (image_legacy)                                                          Module  Not installed  7.x-1.x-dev
 Image                                ImageMagick Advanced Options (image_im_advanced)                                     Module  Not installed  7.x-1.x-dev
 ImageAPI                             ImageAPI (imageapi)                                                                  Module  Enabled        7.x-1.x-dev
 ImageAPI                             ImageAPI GD2 (imageapi_gd)                                                           Module  Enabled        7.x-1.x-dev
 ImageAPI                             ImageAPI ImageMagick (imageapi_imagemagick)                                          Module  Enabled        7.x-1.x-dev
 Other                                Image crop (imagefield_crop)                                                         Module  Not installed  7.x-1.1
 Spam control                         Image CAPTCHA (image_captcha)                                                        Module  Enabled        7.x-1.0-beta2

But the list shows up on the database system table. All the images on my site are not showing up because of this.

I fixed this issue by manual enabling the module from the database and also had to set bootstrap = 1 for it work properly, without it won't work.

so for image row I have to make this changes on system table.

status = 1 and bootstrap = 1

This is bit weird but some how the image module gets disable after some time ( days ). Not sure what is causing it. Every time I have this issue, I have to go to database and make the same changes as above. Can some one guide me what might be causing this issue or how do I debug this.

Note: this is multi site installation.

  Update: Rregistry rebuild using drush rr also fixes the issue, but
  doesn't seem to be permanent.

Missing Image module from the list suggest that it disappeared somehow from the system table which have the list of all modules.

To confirm that, double check that directly using the query, e.g.:

drush sqlq "SELECT * FROM system WHERE name='image'"

It's difficult to answer what causing that without actually debugging it. It depends what kind of modules you've installed, custom code and the environment it-self (e.g. caching).

To track the problem, you can try:

temporary disable external caches (memcached/redis),
temporary disable PHP caches (OPCache/APC/XCache/eAccelerator) or its settings which could interfere with Drupal internals,
disable any automated QA testing (such as Simpletests or Selenium) for affected environment,
disable useless non-stable modules,
temporary disable further modules which you can,
check if this is specific to environment (dev, stage, live),
if happens on all, could be some bug in the code, so follow the section below.

Debugging

This could be a tricky part to find out, so you probably need some tricky tools to debug it.

Here are my ideas:

watch the module lists and check when it's missing:

watch 'drush pml | grep -w image || echo Missing'

for example by sending your-self e-mail with the recent logs:

watch 'drush pml | grep -w image || { drush watchdog-show | mail -s missing-image drupal@niepodam.pl && killall watch; } '

run debuggers attached to MySQL which monitor everything to do withsystem table or image entry (note: it could be overwhelming for the system):

sudo strace -e recvfrom -s999 -fp $(pgrep mysqld) | grep -w image >> sql.log

run debuggers attached to PHP:

sudo strace -e sendto -s999 -fp $(pgrep -fn php) 2>&1 | egrep "system|image" >> php.log

Or simply enable log queries in MySQL configuration file.

Above is more useful if you've Devel installed, so there is an option to prepend a function name before the query (so you know exactly which function caused it).
install XDebug and enable tracing for the part which you suspect the most by adding xdebug_start_trace(); and xdebug_stop_trace(); in appropriate places (see sample ini config), suggested places would be:

system_list()
system_list_reset()

then analyse the trace files.


Display content assigned to a group I am relatively new to Drupal, so I apologize in advanced if my question is confusing.

I am building a school website that will have a parent district site and then school websites within the district. I want to have give the teachers permission to only edit their own respective sites as well.

I feel like I could do this easier with D7 but I want to be future proof so I am attempting this with D8.

Are there any methods I could try to achieve this?

It seems that all you'd need to do, is to use the Group module.

Refer to my answer to "How to configure access to courses for teachers and students?" for a sample configuration.

Resources

Community documentation for the Group module.
Video tutorial "How to use the Group module in Drupal 8 to manage editorial access control to different areas of a web site".


Can't log in to back end I have been trying to upgrade to 8.8.3 from 8.4.4 for some time. My 8.4.4 site was holding but after repairing a database malfulnction in which the watchdog file went mad with assert errors, now I can't login to the back end. After failing to login using the login module on the front page, the WSOD appears with this meesage.

'''The website encountered an unexpected error. Please try again later.Drupal\Core\Extension\InfoParserException: Missing required keys (core) in core/modules/path_alias/path_alias.info.yml in Drupal\Core\Extension\InfoParserDynamic->parse() (line 29 of core/lib/Drupal/Core/Extension/InfoParserDynamic.php).'''

I don't know where to start with this.

This is due to the new core_version_requirement key taking the place of the core key in module.info files. Here's the change record: https://www.drupal.org/node/3070687.

A dirty hack to get around this would be to add the following to path_alias's .info file:

core: 8.x

I would do this only for the purpose of getting your site back in order, and remove the key afterwards. You are likely to run into this error, or similar, for other modules as well. I think that disabling the path_alias module, and any other troublesome modules, prior to upgrade might help.

This change record about path_alias becoming its own core module might be relevant, as well: https://www.drupal.org/node/3092086.

It's also worth mentioning that, if you have drush installed, you can get a one-time login link by running drush uli 1. You'll get a link that looks something like this: http://default/user/reset/1/1584508997/mFfBCIO2zmwKOm3Bh7l5bBwGxwMO6MVqJ6-S-cvZ-pU/login. Take the part of the URL starting with "/user" and append it to your domain name.

Ex: http://my.site.dev/user/reset/1/1584508997/mFfBCIO2zmwKOm3Bh7l5bBwGxwMO6MVqJ6-S-cvZ-pU/login


Mix Honeypot and Regcheck module? newbie question...

Hi,

Before "exploding" my site, I would like to know if I can mix :
- https://drupal.org/project/honeypot
- https://drupal.org/project/regcheck

I'm trying to stop the registration process before sending a request to the server (regcheck) and still have an efficient protection from spam (honeypot).

More generally, is mixing antibot modules a good idea?

Thanks.

While it probably will do no harm, there is not much point in using both.

Regcheck is a small and super simple module that will add an invible (to humans) checkbox on your registration form. Bots will check this, and when the bot submits the form, it can be rejected.

Honeypot is a larger and more complex beast that do several thing to block 'bots. One of these thing is to let you add an invisible (honeypot) field to any form - including the registration form.  From the Honeypot docs:

  Honeypot form protection means that an invisible field is added to a form. If this invisible field is filled out (bots will usually put in a value), then the form will return an error. Normal users (read: human beings) won't ever see the field, so they won't fill it out.

If you install both, your registration form will have two invisble (to humans) fields.  There is little harm in that (having both installed will consume slightly more resources), but not much benefit either .

So I suggest you install Regcheck if you want a simple solution with minimal configuration just to stop 'bots from registering, and Honeypot if you want a more comprehensive anti-spam solution.

However, if you're looking for a solution that stops bots before they hit the registration form submit button, neither Regcheck nor Honeypot will help.  Both work by automatically dismissing registrations after they've been submitted.

If you want to block bots from trying to register, you can't do this by Drupal alone, but need to use webserver access rules.

There are projects, such as Project Honeypot (no relation to the Honeypot module) and Fail2ban  that will do this for you.

To set up a Drupal site to use the Project Honeypot blacklist of IP-addresses, there is also a Drupal module, http:BL.  AFAIK, there is no Drupal module for Fail2ban, but since it work directly with the the server, you don't need one.


List taxonomy terms in node where the vocabulary is referenced I have a taxonomy vocabulary called "Type of appendix". When adding a new node to the page, users can choose a type of appendix. When showing the node, it should list the all appendixes in a table with the category in the first column, the name in the second column and a link to the item in the last column. As shown in the image below

At the moment, my page displays the following:

I want to replace ICT manual with the table in the example.

You should be able to accomplish that with the Views Module:

  You need Views if

  You like the default front page view, but you find you want to sort it differently.
      You like the default taxonomy/term view, but you find you want to sort it differently; for example, alphabetically.
      You use /tracker, but you want to restrict it to posts of a certain type.
      You like the idea of the 'article' module, but it doesn't display articles the way you like.
      You want a way to display a block with the 5 most recent posts of some particular type.
      You want to provide 'unread forum posts'.
      You want a monthly archive similar to the typical Movable Type/Wordpress archives that displays a link to the in the form of
  "Month, YYYY (X)" where X is the number of posts that month, and
  displays them in a block. The links lead to a simple list of posts for
  that month.

  Views can do a lot more than that, but those are some of the obvious
  uses of Views.

Depending on your folder structure, you can use a contextual filter and can create a block, then limit which pages on which it is viewable.


output a referencing field in node tpl In a node type hotel I have an entity reference field to a node type offer. For the offer node.tpl I need to output some fields of the referencing node type hotel.

I have no idea how to get these fields inside the referenced node.

I'd put this in a comment but have no rep so I can't ...

Create a view of hotels as Robin said. The entity reference module provides views relationships that go in both directions , so add a relationship that corresponds to "entity referenced from field yadda yadda" -- sorry I don't know exactly how it'll be labeled offhand but with some trial and error you should be able to find the right one.

Add a contextual filter using the offer relationship on nid, default to content id from url. Be sure to choose the offer relationship when adding fields.

To attach the view to the node itself, you can either use Viewfield or just embed it directly in the template (or preprocess function) using views_embed_view (link)


How to display number of results that would show in a contextually filtered view I have a view which has some contextual filters (not exposed) which limit the view results so they are only shown to the page author. I would like to show other users how many (total) results there are in the view.
I thought I could do that with a Global Results Summary under No Results Behavior, but that only shows results AFTER the contextual filter has been applied.

Any ideas?

Add an Attachment to the View. You can control the Access and change the filters.


Show Taxonomy Terms belonging to search_api search result nodes Using search_api (and search_api_solr) i have a view that shows nodes for (in this case) Organisations in a search_view. That works very nicely.

Now, I would like to show a list of taxonomy terms that are associated with the nodes in the result set. These terms should be in a list of their own, and I need to be able to access the fields on these terms. (In this case, Districts is the Vocabulary, and each organisation can be active in 1 or more Districts. I need to get to the Geofield on these Districts so I can create an Openlayers map).

When I add a Relationship to the search_view to the District field, I see the message

"Note: This is a multi-valued relationship, which is currently not supported. Only the first related entity will be shown."

So, that is not the way (yet).

I am stuck thinking about a workaround for this. Any pointer would be much appreciated.

This may have drawbacks but I had a situation where i wanted to show the multiple tags that related to content that i had indexed.

Having looked through https://www.drupal.org/node/1378656 i opted to try by using https://www.drupal.org/project/views_field_view

Happy to report it worked

Here is the recipe:

create a new View based on Content for types involved and set just the relevant 'term' field as the display (you don't need to create any views displays).
set Contextual filter to nid with 'provided default value = raw value from url' (outcome should be if you enter the nid you should see relevant tags in preview). Save
install/enable https://www.drupal.org/project/views_field_view
over in the view that is rendering the search results (searchapi)
made sure you have Indexed Content: Node ID field already in your Fields, and set to not display
add a new field of type Global: View
in the 'view settings' of this field, find the view you made above, set the right display or use Master if you didn't make any (because you didn't need to),
in Contextual Filter, check your Replacement Patterns where you should have [%nid] == Indexed Content: Node ID (rendered), and enter [%nid]
save and I hope you get to smile like i just did.


How can I install H5P SCORM libraries? The subject says it all. I am attempting to install H5P SCORM libraries in an install of Drupal 7.59 and running into a roadblock: None of what I am reading—or understanding—is clear about how to install the libraries. I am attempting this on macOS High Sierra under MAMP 4.5 (PHP 7.1.12) and MAMP 3.5.2 (PHP 5.6.10). Apache permissions are fine as far as I can see, FWIW and other temp files and uploads work fine on this setup.

I have installed the following two modules in Drupal:

H5P: The core H5P module.
H5P SCORM/xAPI: The H5P SCORM API.

And on the module’s install page I have activated all three modules connected to them:

H5P (7.x-1.35)
H5P Editor (7.x-1.35)
H5P SCORM (7.x-2.4)

But when I go to install the libraries… I just can’t seem to get them to upload without some error happening such as a problem expanding the archive into the temp/ directory and such. The weird thing is temp direcroures are clearly created, but there is no content in them.

I have even followed the “Better Install Instructions” that appear here as a contributed “issue” but with no luck.

The libraries in question are as follows:

H5PEditor SCORM
H5P SCORM/xAPI

Do the decompressed files need to have a directory name such as H5PEditor.ScormFile.h5p or H5P.Scorm.h5p? Because if I simply rename the files, the created directory is still h5p-editor-scorm-master and h5p-scorm-master.

The tangential question is… Is there simply a way I can just physically place files in the correct directory structure user libraries/? Or must it be installed via the administration interface? It seems to me if I could just drop those files in, Drupal—and the H5P modules—should be able to see them, right?

See this page about how to manually construct H5P packages and follow the same process for each repo.

You need to download the repo Zip file. Decompress into a temp directory. Delete the LICENSE, README.md, and .gitignore files

Create a new folder to hold the rest of the files like library.json, CSS, JS For the H5P editor, name it H5PEditor.ScormFile. For the h5p-scorm-master, use H5P.Scorm:

Outside of the new folder, create an h5p.json file.

For the H5PEditor.ScormFile, use this:

{
  "title": "H5PEditor.ScormFile",
  "language": "en",
  "author": "Pavlo Shevchuk",
  "license": "cc-by-sa",
  "preloadedDependencies": [
    { "machineName": "H5PEditor.ScormFile", "majorVersion": 1, "minorVersion": 0,"patchVersion": 8, }
  ],
  "mainLibrary": "H5PEditor.ScormFile",
}

for the H5P.Scorm, use:

{
  "title": "SCORM/xAPI",
  "language": "en",
  "license": "cc-by-sa",
  "preloadedDependencies": [
    { "machineName": "H5P.Scorm", "majorVersion": 1, "minorVersion": 1, "patchVersion": 16, }
  ],
  "mainLibrary": "H5P.Scorm",
  "embedTypes": ["div"]
}

Now Zip up the right h5p.json folder and the H5PEditor.Scormfile or and the other with H5P.Scorm directory. Zip compress each, naming the editor file H5PEditor.ScormFile.h5p and the second library H5P.Scorm.h5p.

Creating H5PEditor.ScormFile.h5p.

So create Zip file renamed to H5PEditor.ScormFile.h5p. Inside of that you have a folder named H5PEditor.ScormFile with contents of the Git repo, https://github.com/pavloshevchuk/h5p-editor-scorm, specified files removed. You also create a h5p.json file with the code provided. Place it in the Zip file but outside the H5PEditor.ScormFile directory.

H5PEditor.ScormFile.h5p
├── H5PEditor.ScormFile
│   ├── library.json
│   ├── scripts
│   │   ├── scormFile.js
│   │   └── scormFileUploader.js
│   └── styles
│       └── scormFile.css
├── H5PEditor.ScormFile.h5p

Creating H5P.Scorm.h5p.

Create a second Zip file renamed to H5P.Scorm.h5p. Inside of that you have a folder named H5P.Scorm with contents of the Git repo: https://github.com/pavloshevchuk/h5p-scorm, specified files deleted. Place the icon.svg file in a directory called content, inside the Zip file. You also create a h5p.json file with the code provided. Place it in the Zip file but outside the H5P.Scorm directory. The Zip file contains this structure:

H5P.Scorm.h5p
├── content
│   └── icon.svg
├── h5p.json
├── H5P.Scorm
│   ├── css
│   │   └── scorm.css
│   ├── js
│   │   ├── api
│   │   │   ├── api_1_2.js
│   │   │   ├── api_2004.js
│   │   │   ├── datamodel.js
│   │   │   ├── debug.js
│   │   │   └── flash_detect.js
│   │   └── scorm.js
│   ├── library.json
│   └── semantics.json

You should now have two H5P files and you will now be able to update them at the H5P admin libraries page:

admin/content/h5p

Here's a repo containing the files I made following these instructions:
https://github.com/jackrabbithanna/h5p-scorm-libraries


Node listings on taxonomy term page How to disable/remove node listings on taxonomy term page in Drupal 8?

function THEME_NAME_theme_suggestions_page_alter(&$suggestions, &$vars) {
            if (\Drupal::routeMatch()->getRouteName() == 'entity.taxonomy_term.canonical' && $tid = \Drupal::routeMatch()->getRawParameter('taxonomy_term')) {
              $term = Drupal\taxonomy\Entity\Term::load($tid);
              $suggestions[] = 'page__taxonomy__' . $term->getVocabularyId();
            }
          }

Create template file "page--taxonomy--VOCABULARYNAME.html.twig" in template folder and you can customize the page with the help of template file.


db_query - Get all nid in more than one nodetype This is a simple query , but i really dont know why its not working. I think the problem is with single quote used!

$type = array('node_type_1', 'node_type_2', 'node_type_3');
$placeholders = db_placeholders($type, 'text');
$query = "SELECT nid FROM {node} WHERE uid = %d AND type IN ($placeholders) AND status = 1 ORDER BY nid DESC";
$result = pager_query($query, 10, 0, NULL, $user->uid, $type);

It tried this also

$result = pager_query($query, 10, 0, NULL, $user->uid, implode(', ',$type);

I am getting error

warning: mysql_real_escape_string() expects parameter 1

The correct way to use db_placeholders() with page_query() is shown in taxonomy_select_nodes(). In your case, the code should be the following one.

$type = array('node_type_1', 'node_type_2', 'node_type_3');
$placeholders = db_placeholders($type, 'text');
$args = array_merge(array($user->uid), $type);

$query = "SELECT nid FROM {node} WHERE uid = %d AND type IN ($placeholders) AND status = 1 ORDER BY nid DESC";
$result = pager_query($query, 10, 0, NULL, $args);


How to make a display mode of the current user on the home page? I have a site built with Drupal 8 and the Twig Tweak module. I want to make the current user's frontpage_tasks display mode on my home page. How to do this ?
I can make a user's frontpage_tasks display mode by manually entering their ID :
page--front.html.twig :
{{ drupal_entity('user', 51, 'frontpage_tasks') }}
{{ drupal_entity('commerce_store', ???, 'frontpage_tasks') }}
{{ drupal_entity('group', ???, 'frontpage_tasks') }}

For stores, I want to display all stores that the current user owns.
For groups, I want to display all groups whose current user is the creator.
What I want to do is render the current user account, stores and groups with frontpage_tasks view mode.

In a Twig template you can get the current user id with user.id.
With the help of Twig Tweak you can use it to render the user entity:
{{ drupal_entity('user', user.id, 'full') }}

As discussed in the comments this only works if your template has already a cache context for the current user.


Alter weather block behaviour? In the weather module, if a user has not configured a custom weather block, the block does not display:

/**
 * Implement hook_block_view().
 */
function weather_block_view($delta = '') {
  global $user;
  module_load_include('inc', 'weather', 'weather.common');
  $block = array();
  // Handle the 'system_NUMBER' type of blocks
  if (strpos($delta, '_') === FALSE) {
    $display_type = $delta;
  }
  else {
    list($display_type, $display_number) = explode('_', $delta);
  }
  $forecast_days = (int) variable_get('weather_forecast_days', '2');
  switch ($display_type) {
    case 'user':
      if (weather_access_userblock()) {
        // Show the user's custom weather block, if there is already
        // a place configured. Otherwise, do not show the block.
        $places = weather_get_places_in_use('user', $user->uid);
        if (!$places) {
          return;
        }
        ...
        [from weather.module]

Is there a way of displaying a 'Please set your weather location' link, instead of nothing at all, without applying a patch to the module?

Thanks.

Use the hook_block_view_MODULE_DELTA_alter in your custom module to display text if user has not configured the custom location.you can access the current user object from global $user if you want to perform any operation on it.

/**
 * Implements hook_block_view_MODULE_DELTA_alter().
 */
function demo_wipe_block_view_weather_user_alter(&$data, $block) {
//Check here that whether user has configured or not.
  if(!is_array($data)) {
    $data['subject'] = t('Blah Blah Blah!');
    $data['content'] = t('Blah Blah Blah! link');
  }
}

P.S. : I have tested it on php 5.5.3

I think you should also specify this as a feature request in the module issue queue to set default whether location(that should be in admin configuration) on user whether block if user has not configured the block yet.


views filter for current user with a relationship I know how to create a view that filters nodes that were authored by the current user. What I want to do is filter based on the author of a node that has a relationship with the node.

For example:
My view has a filter to show nodes of type A
type A has a field that is a reference to type B
I want a filter that shows nodes (of type A) where the referenced type B node was authored by the current user.

In D6, I did this by creating a relationship to B, then adding a filter where (B)User=Current (that is, User = current with a relationship to type B). I can't figure out how to do this in D7.

So far I have created a relationship to "Content:Author" which does not allow me to define a relationship to type B. Then I created a filter for "(author) User: Current (Yes)" but this appears to be filtering based on the author if my type A nodes.

I've tried googling, but can't seem to come up with the right keywords.

If I correctly understand the requirement then you are missing the relationship between content type 1 and 2

You need a view of nodes with:

A filter that only shows node of type A.
A relationship from node type A to node type B via your reference field.
A relationship from node type B to its author user.
A filter to restrict the user author (of content b) to the current user.


List fields for a content-type? Possible Duplicate:
  Listing entity fields

Is there a function or technique anywhere in the Drupal API to list fields for a particular content type?

About list your fields for your content type, I guess that you can use node--NAMECONTENTTYPE.tpl.php in your directory template.

to be more detailed, you can copy/paste to your theme directory the file node.tpl.php (located in modules > node or already located inside your theme directory) and rename it according your content type. for example, if the Content Type is Article the name will be node--article.tpl.php

already inside in node--article.tpl.php you can list the fields with the variable $content using print_r($content); to see the list of the fields that you can use to your node (or if you use Devel module, is best use dsm($content);)

to call each field you can use:

for example I have a field called field_demotext1, then:

print render($content['field_demotext1']);

here is the example of zone in the node--article.tpl.php using dsm($content); to print list of fileds:

  <div class="content clearfix"<?php print $content_attributes; ?>>
    <?php
      hide($content['comments']);
      hide($content['links']);
      print render($content);
      dsm($content);
    ?>
  </div>


Drupal.settings.ckeditor is undefind in CKEditor module I have installed CKeditor module as per the guidelines of ckeditor README.txt file.
But in neither text area ckeditor is loading.
When I inspected in firebug it shows me following error

  Error: TypeError: Drupal.settings.ckeditor is undefined Source File:
  localhost/drupal7/sites/all/modules/contrib/ckeditor/includes/ckeditor.utils.js
  Line: 5

I am wondering is there any problem in configuration?

I have installed and configured CKEditor module previously many times but I haven't encountered such type of error

Finally I got a clue. I had enabled HeadJs module for improving jquery loading time. This module was creating bottleneck. Just uninstalled this module and work like a charm.


Where are the best places to post Drupal 7 RFP? Do you have any thought on the best places to post an RFP for Drupal 7 development and theme work?

I have posted on drupal.org and groups.drupal.org but someone mentioned odesk, but I wasn't sure if that would be fruitful or just overkill.

drupal.org reaches a wide audience, and is a good venue.  That said, please be aware that widely distributing an RFP can be harmful to your project.  Many of the best shops don't respond to RFPs.  Advomatic has published an interesting presentation on this topic.


Categorizing Contents I am creating a Drupal Commerce website in which I have created 4 Product Types and 4 Product Displays as following

Health
Eye / Sunglasses
Contact Lenses
Sports

To classify the products I have created several vocabularies, some vocabularies are common in all product display types and some are available in one or two product display types.

Now I want to use default Taxonomy Term view provided by the views module and add those vocabularies as exposed filter in that but in the way that if Health Taxonomy page is being viewed it must show the vocabularies as exposed filter related to Health Only and so on

give the module hierarchical_select or it's simpler approach a try.

or see here how to programmatically play with the exposed filter(s): https://drupal.stackexchange.com/a/96769/3218


Setting cache max-age to 0 has no effect on Block built using BlockBase? I've built a custom block using BlockBase and as the content this block displays is different depending on the URL it's accessed via (a query parameter is passed in the URL) this block needs to either not cache, or cache relative only to the specific URL it's accessed using.

I've tried the following:

return array(
    '#theme' => 'testing_block',
    '#testBlockData' => $testBlockData,
    '#cache' => array(
        'contexts' => array('url.path'),
    ),
);

Which doesn't work. So then I tried this:

return array(
    '#theme' => 'testing_block',
    '#testBlockData' => $testBlockData,
    '#cache' => array(
        'max-age' => 0,
    ),
);

This also didn't work, so I tried the two cache settings combined together:

return array(
    '#theme' => 'testing_block',
    '#testBlockData' => $testBlockData,
    '#cache' => array(
        'contexts' => array('url.path'),
        'max-age' => 0,
    ),
);

None of these work, and I can't for the life of my figure out why. According to everything I've read, this is the right way to do it.

Is it actually possible to set a block like this not to cache in Drupal? And if so, what am I doing wrong?

This is a known problem for anonymous requests, see this issue PageCache caching uncacheable responses (violating HTTP/1.0 spec) + D8 intentionally disabling HTTP/1.0 proxies = WTF.

Until this is resolved, put this trigger in your block build():

\Drupal::service('page_cache_kill_switch')->trigger();


Disabling the links in menu item When I visit  a page , say 'About Us' I want the 'About Us' in the menu-items to act as a simple text (not as a link). How can I achieve that ? Thank you in advance.

You can use the Special menu items module.
In your case you can use the <nolink> placeholder in the menu link path field to show the menu item as text.


Search snippet does not appear in Search API search page I am using

Drupal 7.28
Apache Solr 4.4.0
Search API Solr 7.x-1.5
Search API attachment 7.x-1.3 and
Search API Page 7.x-1.1.

I have created 2 content types with
 - Title
 - ID
 - Document date (not the default node creation date)
 - Attachment

My index and preprocessing settings are the following:
Index Fields:
Processor settings:

In the search page I am searching all the fields and have set
View mode: Themed as search results

The searches work correctly only that when I search for a keyword appearing in the attachment text, the results return without the search snippet, whereas when I search in the title, the returned result is correctly highlighted

The funny thing is that when I submit the query directly to solr with e.g. q=tm_title:Spain?hl=on the <lst name="highlighting"> is empty.

Any ideas?

It appears that Create Excerpt was the option that was not allowing the search snippet to appear. After I disabled it, everything worked as expected. Should have done my homework better :-/


How do I add a date picker that is rendered from most the browsers? I am migrating from Drupal 7 to Drupal 8. In forms I use '#type' => 'date_popup' for date fields, which Drupal 8 replaces by '#type' => 'date' and uses HTML 5.

I'm finding it most unsatisfactory because:

It has poor browser support; Internet Explorer 11 doesn't provide a popup.
I can't find anyway to change the input format from 'm/d/yyyy' to either 'd/m/yyyy' or 'yyyy-mm-dd'.

I have ensured that my browser language setting is English (Australian) which has a default date format of 'd/m/yyyy'.

Does anyone have a solution that provides a date picker for most the browsers and a text input format that can be controlled by the server, not the client?

I had a similar issue just recently within a client's intranet application, after Firefox added HTML5 date field support. (FF is their corporate browser of choice.)

You can still use any JavaScript based datepicker that suits your needs. (E.g. jQuery UI's datepicker.)

In your JavaScript bind this datepicker to all input fields of type date and then change the type of the input fields to text. This prevents the browsers from using their own datepickers.

PS.: It's not exactly a Drupal specific question, but tomorrow when back in my office I might add a code example that works for Drupal 8.


How to display instances of a field (field collection) in tabs? I have a content type with a field which has a number of instances (actually, it's a Field Collection with a vimeo embed and a text field). I would like to have each instance of the field to be shown as a tab? Field Group seems like a natural candidate for this role, but from what i understand it enables me only to build tabs for particular fields, not fields instances.

The way I'd dream this functionality to be is:
1) I add another field to my field collection named, say, "Tab title"
2) In "manage display" of the node I set the display of the field to be of "tabbed instance" type.
3) In settings of this display I set the title of the tab to be the new field introduced in 1) by Token.
Of course, any other way of acieving the goal would be also most welcome.
Is there a simple way to obtain such a functionality?

Someone up there likes you...
Field Collection Tab formatter

Field collection tabs provides a field formatter that allows you to output a multi value field collection field as a tabset, with one tab per field collection item.
Features
You can optionally choose a field from the field collection item to be used as the tab title.

It's uncannily close to what you're asking for. Your question might as well have been the user story that inspired that module :)


Is there a way to set two separate views with exposed filters in a panel page? I have been attempting to create a panel page with two columns, one to display view1 and the other view2. The intent is to have the user choose a content type in each column using exposed filters and have the list of content displayed by the view in the panel page.  This has turned out to be more complicated to execute than I first thought.

The problem is with the URL. I can have a URL to invoke the panel page, eg.relate/relate, and it will display the same list of all content in each column by default.  However, when I change the content type in one of the columns, the URL is changed in response and only the changed view is displayed (the panel is not longer activated.

So I am trying to find a way to manage two views from the same page panel that either does not change the URL request or that the panel can manage correctly.

I have tried passing both content type names in the URL eg. relate/%type1/%type2 and have each view read one of the URL positions using contextual filters.  This has approach has several problems

I am not sure how to tell the view contextual filters how to react to only the relevant wildcard in a two wildcard URL relate/%/%.
How do I set up a contextual filter to read the value in the path segment and interpret it as a filter for a content type?  The contextual filter can be set up to read the raw URL path segment (in the section re: what to do when the filter fails), but there does not appear to be a way to set up the validation to determine a content type.

Has anyone ever achieved this or can you suggest an approach that might work?

ADDITIONAL INFO

I found that I can prevent the URL from changing by setting a n option in the view content pane to use the Panel URL.  This keeps the display as two columns (from the panel), but does not unlink the two similar view content panes. They still both change when I set the exposed filter for either.  Apparently the exposed filter is only created once , but displayed twice and sends its setting to both panes.  I found this to be true even if I create two distinct View definitions.  If the settings for the filters are the same they appear to both run if either exposed filter is changed.

yes . you can show exposed filters in a block. See you view, on right hand side under Exposed form Caption. here you can put yes for Exposed form in block:No.
Now your filters are available in a separate block.


Is there existing integration between the Salesforce and Location modules? I'm using the Salesforce module in Drupal 7 and am attempting to create a mapping to one of my content types that contains a Location module field. After looking at both modules, I don't see an existing integration for them.

I tried adding a field mapping for just the street address (the only method available was using a token, so I selected [node:location:street]).  When I kick off the import of salesforce data, I get the following error:

WD Salesforce Pull: Unknown data property [node. Processing failed for entity XXXXXXXXXX
associated with Salesforce Object ID: XXXXXXXXXXXXX

I tried other variations of the token, too, including:

[node:location:street:0]

[node:location:street:?]

Both gave me the same error.

It's difficult to say what's the exact problem, but I think you could have unmapped property in your configuration.
So please go to /admin/structure/salesforce/mappings and verify all the objects that have the properly set mappings and the tokens are valid.

If this doesn't help, try the following options:

Clear the cache (including memcached).
Check watchdog logs for further info.
Double check your Salesforce mappings again if you didn't miss anything.
Upgrade your Location and Salesforce module to development version just to test.
Look for any existing issues.
Debug the code using xdebug.
Report the issue or bug report on Drupal site against the right module.

You may also try the following related links:

Location - Select User Primary
Support Salesforce attachment sync


How to bind to AJAX complete event in regard to styling the AJAX button submit throbber With this I can bind to the AJAX button submit event:

Drupal.ajax.prototype.beforeSend = function (xmlhttprequest, options) {
...
}

My question, how to bind to the opposite (i.e. when AJAX button submit finishes)? Thanks.

You can use success function. You can refer this for its usage.

/**
 * Handler for the form redirection completion.
 */
Drupal.ajax.prototype.success = function (response, status) {
  ...
}


on submission of form respective form should open in my form i have to show two radio button and one submit button, for example

candidate(radio)

organization(radio)

submit button.

my requirement is that

if user click/check on candidate and submit then candidate form should be open.

or

if user click/check on organization and submit then organization form should be open.

my code:

<?php
/**@file
*donation.module*/
/**
*Implements hook_menu()*/
function donation_menu(){
$items['donate'] = array(
'title' => 'Donate',
'page callback' => 'drupal_get_form',
'page arguments' => array('donation_donate_form'),
'access arguments' => array('access content'),
'access callback' => TRUE,
);
return $items;
}
/**
*Implements hook_form().
*/
function donation_donate_form($form, &$form_submit){
/*the options to display in our form radio buttons*/
$options = array
'candidate' => t('Candidate'),
'organization' => t('Organization'),
);
$form['officials'] = array(
'#title' => t('OFFICIALS'),
'#type' => 'radios',
'#options' => $options,
'#default_value' => $options['candidate'],
);
$form['name'] = array(
'#title' => t('NAME'),
'#type' => 'textfield',
);
$form['submit'] = array(
'#value' => t('PROCEED'),
'#type' => 'submit',
);
return $form;
}

I'd do something like

function donation_donate_form_submit($form, &$form_state) {
  switch ($form_state['values']['donate']) {
    case 'candidate':
      $form_state['redirect'] = 'donate/candidate';
      break;

    case 'organization':
      $form_state['redirect'] = 'donate/organization';
      break;
  }
}

and from this point I can do two things

Solution 1

Create other two menu items with different form for each

Solution 2

your original form would be called if you don't create any extra menu items (drupal falls back to the longest menu item that match the current URL), then change the existing form depending on the argument like this

function donation_donate_form($form, &$form_submit) {
  $form = array();
enter code here
  // No argument ? we must be in the selection phase.
  if (arg(1) == NULL) {
    $form['officials'] = array(
      '#title' => t('OFFICIALS'),
      '#type' => 'radios',
      '#options' => array(
        'candidate' => t('Candidate'),
        'organization' => t('Organization'),
      ),
      '#default_value' => 'candidate',
    );

    $form['name'] = array(
      '#title' => t('NAME'),
      '#type' => 'textfield',
    );

    $form['submit'] = array(
      '#value' => t('PROCEED'),
      '#type' => 'submit',
    );
  }
  elseif (arg(1) == 'organization') {
    // Candidate form stuff.
  }
  elseif (arg(1) == 'candidate') {
    // Organization form stuff.
  }
  return $form;
}

It depends on how you like your code, and what you are trying to do.


Managed_file form does not show #default_value I am using managed_file in Drupal 7 for my custom module. Other than the form api and managed_file, I'm using my own custom tables for this module.

This will eventually be used on shared hosting via Dreamhost, so the requirements of using PECL extensions are probably not available at this answer suggests.

The behavior I want is when the file is uploaded by clicking the "upload" button, I at least want the image file to be a link that appears to indicate to the user that the file is uploaded. When I left the default #progress_indicator in place, the AJAX indicates it never uploads. However, this is false as I can see the file in managed_file table in the db.

I've looked through several searches for this and this is the form that I've come up and I cannot see what I'm doing wrong.

$item is the result of a database call of the previous object. Its genesis was derived from a post jaypan provided.

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

dpm($item); => //every attribute to the sponsor object in the database.

$uri = isset($item->logoFileID) ? fetch_name('file_managed', 'uri', 'fid', $item->logoFileID) : '';

$uri = isset($item->logoFileID) ? fetch_name('file_managed', 'uri', 'fid', $item->logoFileID) : '';
dpm($uri); => 'public://logos/myfile.gif' //to show valid return of $uri
dpm($item-logoFileID); => 'public://logos/myfile.gif'

  $form['logoFileID'] = array(
    '#title' => 'file key',
    '#type' => 'hidden',
    '#default_value' => $item->logoFileID,
    );
 $form['logo_fid'] = array(
    '#type' => 'managed_file',
    '#title' => t('Logo'),
    '#description' => t('Upload a file, allowed extensions: jpg, jpeg, png, gif'),
    '#upload_location' => 'public://logos/',
    '#progress_indicator' => 'none',
    '#default_value' => $file->uri,
    );

As I said, managed_file does save the file and returns an fid that I save with the sponsor record. The behavior I have gotten in this module is that the filename was showing in this part of a form, that when clicked in Drupal shows a popup modal of the image. My question is how do I get this back link back to appear in the form to show the user it has been uploaded?, thx sam

The value of a managed file field is a file ID, rather than its URI.

Assuming $file in your code is a file object, change the element array to:

$form['logo_fid'] = array(
  '#type' => 'managed_file',
  '#title' => t('Logo'),
  '#description' => t('Upload a file, allowed extensions: jpg, jpeg, png, gif'),
  '#upload_location' => 'public://logos/',
  '#progress_indicator' => 'none',
  '#default_value' => $file->fid,
);


how to show links inside a block function custom_block_view($delta = '') {
$brands = $brand->getChildrenCategories();
      foreach ($brands as $node) { #print_r($node);
        $items[] = array(
            'data' => t($url = Mage::getUrl($brand->getUrlPath()).'.html')
            #'data' => t($node['name'])
        );
      }

$block['content'] .= theme('item_list', array(
          'items' => $items
              ));

    }

I use this code to display items in a block. I want this to be a link but was not able to achieve it. The output is shown below:

You need to use the l() function in place of t() (which is a string translation function):

$url = Mage::getUrl($brand->getUrlPath()).'.html';
$link = l('Link Title', $url);

If the URL is external you'll also want to provide that information in the $options parameter:

$link = l('Link Title', $url, array('external' => TRUE));


Showing latest news article from taxonomy I have News content type on my Drupal 7. With views I want to show latest news within specific taxonomy. So each News content type has taxonomy field where I can set news for example into "Cars" category.

Now I have News Lift content type where I have entity reference field called news_type that is linked to same taxonomy as is my News content type. When I make a new news lift and I set I want to show post from "Cars" category. On this just created page I want to now show that latest post in that category using views. In Views my current set up is this:

Filters (published & News -content type)
Relationships (Entitry referecing news_type field).

But at the moment it just shows the latest post. It ignores the relationship about the category. What's wrong. Do I  need contextual filter too?

Download the Views PHP module:

  This module allows the admin account (user 1) to add fields, filters
  and sorts to views which use PHP code. It also supports additional
  accounts when the core PHP Filter module is enabled.

In Views:

create a View of News Content Type, as a block and set it up to show all entries for now in the format and layout you desire
add a contextual filter for the Category field
Provide a default value, PHP code:

$node = menu_get_object();
return $node->field_category['und'][0]['tid'];

The first line retrieves the page object (which should only ever be a News Lift node if the block is set up properly), then returns the term ID associated to the current node as a contextual filter to the view. This assumes a single language site.

Under /admin/structure/block set the view-block to show where you want on the page, limit it to show only on the content type News Lift