Why not programatically created nodes in the simpletests? Most core and many contrib simpletest test create nodes by preparing the interface, logging an admin in and then filling out the form on /node/add/foo. Not only is this terribly slow, it fails at the most basic rule of Testing: only test your own concerns; mock and stub the rest.

For a test, all I need is N nodes with X tags (taxonomy-terms) attached to them. I am (in no way) interested in whether or not some "Save" button exists somewhere; which is what I am testing when I follow along with core tests, e.g my helper function createNodesWithTags().

This helper is modeled after TaxonomyRSSTestCase which has the same concern as my: make sure there are some nodes with tags, so that some interface can then be tested using these nodes. The helper first creates an entity-field on the node type "article", required because otherwise one cannot add tags to that node. It then proceeds to open up the node/add/article-page, attaches the term and presses Save.

  private function createNodesWithTags($amount) {
    $field = array(
      'field_name' => 'taxonomy_' . $this->vocabulary->machine_name,
      'type' => 'taxonomy_term_reference',
      'cardinality' => FIELD_CARDINALITY_UNLIMITED,
      'settings' => array(
        'allowed_values' => array(
          array(
            'vocabulary' => $this->vocabulary->machine_name,
            'parent' => 0,
          ),
        ),
      ),
    );
    field_create_field($field);

    $this->instance = array(
      'field_name' => 'taxonomy_' . $this->vocabulary->machine_name,
      'bundle' => 'article',
      'entity_type' => 'node',
      'widget' => array(
        'type' => 'options_select',
      ),
      'display' => array(
        'default' => array(
          'type' => 'taxonomy_term_reference_link',
        ),
      ),
    );
    field_create_instance($this->instance);

    //Create N nodes and attach all N to tag1, N-1 to tag2, N-2 to tag3 etc.
    $attachable = $this->tags;
    for ($i = 0; $i < $amount; $i++) {
      // Post an article.
      $edit = array();
      $langcode = LANGUAGE_NONE;
      $edit["title"] = $this->randomName();
      foreach($attachable as $tag) {
        $edit[$this->instance['field_name'] . '[' . $langcode . '][]'] = $tag->tid;
      }
      $this->drupalPost('node/add/article', $edit, t('Save'));

      //remove one tag, so the next node gets one less tag attached.
      array_shift($attachable);
    }
  }

Why do core tests test this way? Why is TaxonomyTestCase concerned with whether or not saving a node works (i.e. an admin can be created, logged in and finds the Save button)? Why don't they just call node_save() or some other API?

Is there a reason why I should implement it this way too, instead of just dropping records in the database, possible trough the node_save() API?

Here is what the Drupal documentation says on it's simpletest page.

  Testing methodology
  Drupal testing focuses on functional testing
  instead of unit testing. What this means is that the tests are written
  in such a way that they test the interface as a whole instead of
  testing individual functions or finite pieces of code. Drupal focuses
  on functional testing because it is more effective for the way Drupal
  is written. Functional testing ends up being just as effective if not
  more effective than unit testing and especially so due to the code
  style used in Drupal. The testing framework is geared towards this
  type of testing and the documentation focuses on writing functional
  tests.

Drupal tests are almost always functional tests and not unit tests. As quoted above, Drupal was coded in such a way (e.g. hooks system, forms api, etc) that Unit tests generally don't make sense.


Filter in view with some dynamic value I have a content type, have a integer value field suppose field name is "field_xyz" and I have also variable from variable tables (variable_set('xyz')) which have some dynamic value

Now I want to create a view in which I need to add a filter and showing all node having field_xyz's value greater than equal to variable_get('xyz') value. I can do this using views_php module but I want to do it with manual configuration (No PHP code). Is there anyway ?

I won't recommend views_php module. This will hamper performance of the site.

You can use hook_views_query_alter(&$view, &$query) for this. What you have to do is - add field_xyz filter inside view, and override it in hook_views_query_alter(&$view, &$query).


Getting the value of a select option I would like to validate the company name chosen in a form in a "select" form field.

When I try $form_values['submitted_tree']['company_1']; it shows me the key instead of the string value.

I tried the following code, but it still prints '1' (the key) instead of the value associated with the key.

    $_page_num = $form_state['values']['details']['page_num'];
    $key1 = $form_state['values']['submitted_tree']['company_1'];
    $value1 = $form['submitted_tree']['company_1']['#options'][$key1];
    $key2 = $form_state['values']['submitted_tree']['company_2'];
    $value2 = $form['submitted_tree']['company_2']['#options'][$key2];

    if (($_page_num == 2) && ($value1 == $value2)) {
      drupal_set_message(print_r($form['submitted_tree']['company_2']['#options'][$key2]));
    }

Could anyone help me to retrieve the actual text value displayed in select option chosen? I have tried $form_state as well, but it returns the same result.

You can use the key to get the value by referencing the options array in the original form element:

$key = $form_state['values']['submitted_tree']['company_1'];
$value = $form['submitted_tree']['company_1']['#options'][$key];


White screen of death when uploading a file attachment I am currently experiencing a problem when adding file attachments to nodes in Drupal 6. When attaching a file and clicking the upload button, the screen goes white. I checked the files directory and the file does not appear there so it would seem it never gets uploaded. This problem occurs on the production server but not the test server. I have tried displaying php errors by modifying the index.php file but that does not display anything. I have the php memory set to 154MB but still no dice. I have Googled and searched this site but can't find a solution. Has anyone else experienced this problem? Can anyone provide some insight as to what the cause of this might be (and hopefully how to fix it)?

System setup

Ubuntu 10.4,
Apache,
PHP 5.3,
MySQL 5.1

Drupal 6.22,
CKK 6.x-2.9,
jQuery UI 6.x-1.5,
jQuery Update 6.x-2.0-alpha1,
plus a whole boatload of other modules (that may or may not be relevant).

Thanks for any possible insight into this.

mod_fcgid have to do with FastCGI.

There are actually a few PHP settings you may need to investigate and modify.

Reference: Increase upload size in your php.ini

In short though, you will need to up your upload_max_filesize as well as your post_max_size

Also, I would recommend watching your /var/log/apache2/error.log (Default location in Ubuntu 10.4) while debugging.  Generally running sudo tail -f /var/log/apache2/error.log will show you 'white screen' errors in real time.


hook_node_info or node_type_save? I've created a custom module that creates 2 content types in it's .install file (with node_type_save). This works fine, but now i have trouble implanting the hook_xxxx system. As the content types are already defined there is little need hook_node_info to define them again in the .module file, and even if i wanted to this will not work.

Now i can get around this by using hook_node_xxxx but i wonder if this is the right approach. It seems a bit dodgy to use the general hooks in a module which just defined those hooks.

Here is the code:

<?php

/**
 * Implements hook_install().
 */
function vakantie_install() {

    $t = get_t();
    $content_types = array(
        'name1' => 'vakantie_blok',
        'name2' => 'vakantie_pagina',
    );

    $types = array(
        array(
            'type' => $content_types['name1'],
            'name' => $t('Vakantie Blok'),
            'base' => 'node_content',
            'description' => $t('Maak een Vakantie Blok item.'),
            'custom' => 0,
            'modified' => 1,
            'locked' => 0,
        ),
        array(
            'type' => $content_types['name2'],
            'name' => $t('Vakantie Pagina'),
            'base' => 'node_content',
            'description' => $t('Maak een Vakantie Pagina item.'),
            'custom' => 0,
            'modified' => 1,
            'locked' => 0,
        ),
    );

    foreach ($types as $type) {
        $type = node_type_set_defaults($type);
        node_type_save($type);
        node_add_body_field($type, $t('Inhoud'));
    }

    foreach ($content_types as $type) {
        // add persistent variables that control settings
        variable_set('additional_settings__active_tab_' . $type, 'edit-menu');
        // 0 = disabled, 1 = optional, 2 = required
        variable_set('node_preview_' . $type, 1);
        // array(0 => 'status', 1 => 'promote', 2 => 'sticky', 3 => 'revision') remove to uncheck
        variable_set('node_options_' . $type, array());
        // 1 = Display author and date information, 0 = none
        variable_set('node_submitted_' . $type, 0);
        variable_set('menu_options_' . $type, array());
        variable_set('menu_parent_' . $type, 'main-menu:0');
    }
}

/**
 * Implements hook_uninstall().
 */
function vakantie_uninstall() {

    $content_types = array(
        'name1' => 'vakantie_blok',
        'name2' => 'vakantie_pagina',
    );

    // gather all job nodes created and delete them
    $sql = 'SELECT nid FROM {node} n WHERE n.type = :type1 OR n.type = :type2';
    $result = db_query($sql, array(':type1' => $content_types['name1'], ':type2' => $content_types['name2']));
    $nids = array();
    foreach ($result as $row) {
        $nids[] = $row->nid;
    }
    node_delete_multiple($nids);

    // remove persistant variables that control settings
    foreach ($content_types as $type) {
        variable_del('additional_settings__active_tab_' . $type);
        variable_del('node_preview_' . $type);
        variable_del('node_options_' . $type);
        variable_del('node_submitted_' . $type);
        variable_del('menu_options_' . $type);
        variable_del('menu_parent_' . $type);
    }

    // delete our content type
    node_type_delete($content_types['name1']);
    node_type_delete($content_types['name2']);
}

Here the .module:

<?php

function vakantie_node_view($node, $view_mode, $langcode) {
    if($node->type == 'vakantie_blok') {

        $extra_field = 'test_extra';

        $node->content['test'] = array(
            '#markup' => $extra_field,
            '#weight' => 1,
        );

        $node->content['test2'] = array(
            '#markup' => $extra_field,
            '#weight' => -1,
        );
    }
}

I would suggest doing as a Drupal module does: the Blog module. That is the correct code to use for a module that defines its own content type.

In the installation file, the code the Blog module uses is the following.

function blog_install() {
  // Ensure the blog node type is available.
  node_types_rebuild();
  $types = node_type_get_types();
  node_add_body_field($types['blog']);
}

In the module file, it implements the content type hooks, which are:

hook_form()
hook_node_info()
hook_view()

Another Drupal core module that implements its own content type is the Forum module. Differently from the Blog module, the Forum module adds a field to the nodes of its content type. The code it uses to set its content type is similar, though. (See forum_enable().)

  // Ensure the forum node type is available.
  node_types_rebuild();
  $types = node_type_get_types();
  node_add_body_field($types['forum']);

Notice that Drupal core modules don't remove the content type they define, when they are uninstalled; eventually, they remove any field they attached to their content type. (See forum_uninstall().)

As side note, the string passed to t() contains English words, not in other languages.


Sort Entity Reference Fields I am trying to find a way to sort the referenced entities in a node. I have found a related question "Ordering of referenced entity" but it cannot be applied in my case for the following reasons:

1) The manual ordering is out of the question in my case. In some of the nodes that need to be fixed there are more than 2000 referenced entities and they are ordered randomly right now. I also need to find a way to do that efficiently, since there will be a lot of nodes in the future that will also have multiple entity references that will need to be ordered.

2) The array_reverse option will obviously not work since the referenced entities are ordered in a completely random manner.

3) The third option in the accepted answer does not even apply to sorting.

4) The rest of the answers are just improvements over the accepted answer's methodology and obviously cannot be applied.

What I would ideally like to achieve is grab the first number in the title of the referenced entity and use this to sort the referenced entities.

Note: It is very important to handle cases of "software release number ordering" which in plain English means that 1.1 comes before 1.2 which in turn comes before 1.10.

I recently faced a similar problem and I solved it using the hook_form_FORM_ID_alter hook so that I can have an overview of the changes before actually applying them. My idea was to set the weight of each entity reference field to the number that can be found in the referenced entity's title. In your case however, the "numbers" in your title are not actual numbers with decimal parts but 2 different numbers that happen to be connected with a period (the first number has higher priority in the ordering than the second).

In your case you should do something like this:

function YOUR_MODULE_NAME_form_YOUR_CONTENT_TYPE_node_form_alter(&$form, &$form_state, $form_id) {
  if($form['nid']['#value'] == "22312") {  // The node id instead of 22312
    $keys = array_keys($form['field_FROM_ENTITY_REFERENCE']['und']);
    foreach ($keys as $value) {
      if (is_numeric($value)) {
        $weight = preg_match_all("/\d+\.\d+/", $form['field_FROM_ENTITY_REFERENCE']['und'][$value]['target_id']['#default_value'], $matches);
        if (empty($matches[0])) {
          $weight = preg_match_all("/\d+/", $form['field_FROM_ENTITY_REFERENCE']['und'][$value]['target_id']['#default_value'], $matches);
        }
        if (!empty($matches[0])) {
          $tempweight = explode(".", $matches[0][0]);
          $lengthtopad = (isset($tempweight[1])) ? 5 - strlen($tempweight[1]) : 5;
          $tempweight[0] = str_pad($tempweight[0], $lengthtopad, "0");
          $finalweight = implode("", $tempweight);
          $form['field_FROM_ENTITY_REFERENCE']['und'][$value]['_weight']['#default_value'] = $finalweight;
        }
      }
    }
  }
}

This solution is based on the idea that if from the 2 different-priority numbers that you have, you create numbers with the same amount of digits by padding the number with the highest priority with zeros, your final numbers will be properly ordered.

I assumed that the first number is single digit and that the second number can only go up to 3 digits. You can however adjust this to support more digits in the "decimal" part of the number.

Just to give you a couple of quick examples of how the numbers will look like after the transformation described above:

1 -> 10000
1.1 -> 10001
1.2 -> 10002
1.10 -> 10010
2.45 -> 20045
2.456 -> 20456

Of course, you can apply the same method to change the weights implicitly by using node_load, altering the weights and then using node_save to apply the new weights. It would work just fine, but with the solution described above, you edit the node-in-question and you can inspect the referenced entities and their ordering before deciding whether to save the node or not.


Views adds "nid" to SELECT and GROUP BY when trying to aggregate by title I tried to create a simple aggregated View, but Views added nid, even though I did not select it as a field, and also ruined my GROUP BY making the view unusable.

Any tips how to avoid this nid addition?

SELECT node.title AS node_title_1, node.nid AS nid, COUNT(node.title) AS node_title
FROM
{node} node
WHERE (( (node.type IN  ('my type')) ))
GROUP BY node_title_1, nid
LIMIT 10 OFFSET 0

Try to enable checkbox Query settings -> Distinct in your view settings.


Search results only for the current language I have a site with 4 languages and am using the builtin search to look for content on the site. How is it possible to restrict the search results only to the currently selected language?

I tried looking into Configuration > Search Pages, but do not see any way how to do that there.

The "Advanced" core search has this built in. If you prefer to do this from a theme - you could do it with form_alter. This basically hides the advanced search settings and sets current language as the only language to get results from, in the search block and search page.

Alternately you can just allow users to control which language they want to get results from and simply allow them to use advanced search.

Code for theme:

/**
 * Implements hook_form_FORM_ID_alter().
 */
function hook_form_search_form_alter(&$form, &$form_state) {
  $form['help_link']['#access'] = FALSE;
  $form['advanced']['#access'] = FALSE;
  $form['basic']['keys']['#title'] = '';
  $manager = \Drupal::languageManager();
  $form['advanced']['lang-fieldset']['language']['#default_value'] = [$manager->getCurrentLanguage()->getId()];
}

/**
 * Implements hook_form_FORM_ID_alter().
 */
function hook_form_search_block_form_alter(&$form, &$form_state) {
  $manager = \Drupal::languageManager();

  $form['advanced-form'] = [
    '#type' => 'hidden',
    '#value' => 1,
  ];
  $form['f[0]'] = [
    '#type' => 'hidden',
    '#value' => 'language:' . $manager->getCurrentLanguage()->getId(),
  ];
}


users see all replies to a message sent by admin [Privatemsg module] I (admin) sent a message to couple of users by their username (not by role) . If "user1" replies back to the admin , user2 and user3 will see the message too ,

that's why the module is called PrivateMessage right :)

any clue ?
thanks

This is by module design and works as expected.

If you add multiple recipients to a message, Privatemsg treats it as a "conference" discussion and notifies everyone in the group when someone replies.

If you want to keep the conversation only between you and a particular user, you must send it only to that particular user.

What you need to do is to hook into the submit function of the form and instead of generating messages for all recipients at once, loop through them and do that for each separately.

You should not modify source code, as that might make it work incosistently and will create maintenance problems for you later on.

What I suggest is to create a custom module, add your submit callback for privatemsg_new() form and process the messages separately. Check out privatemsg_new_submit() function in the source. Also make sure the default privatemsg submit handler does not get executed - just unset it form the $form['actions']['submit']['#submit'] array.


Theming Panels with Zen Grids I want to theme Panels using Zen Grids for layout.

Question:

Since all content in Panels appears in the 'content' div, what is the most flexible way to use Panels to place content anywhere on the page?

EG. Right now, my content-item that is styled with 'region-sidebar-first' is appearing in the main content section (of course).

Do I use
 - Panels Everywhere?
 - Mini-Panels?

I don't want to over-complicate things. Is there some way of configuring Panels to place content within ANY div within the body section of a page? I'd like to avoid using too many other modules etc.. and keep it very clean.

Ideal Scenario:

I place all the content-items inside a ONE column layout with Panels : (layout not important, but Panels does it's magic to create content based on Context etc... )
I style each content-item using 'css-properties' inside Panels, and choose CSS from Zen Grids
I use SASS to create a responsive layout via Zen Grids

Thanks in advance,

PW

Your answer is quite flexible actually.

You select the one column template and disable drupal standard regions and then just add a php filter custom content for each row in your grid. You add the grid classes inside your php filter and then use block render or views_embed_view.

Another more clean solution would be to create your own layout plugins for panels. It is not as difficult as it sounds. Just download and fork panels_extra_layout and you have everything you need in order to create your own custom and reusable grids.

Have fun.


PUT method using drupal_http_request I need to update data in HP Quality Center with Drupal.

After login with success, I get some data from QC with the following code (simplified):

$headers = array('Cookie' => $cookie);
$request = drupal_http_request('http://qc.intra.xxx.com:8090/qcbin/rest/domains/' . $domainname . '/projects/' . $projectname . '/test-instances?query={cycle-id["' . $id . '"]}',
    array('headers' => $headers),
    'GET'
);
$xml = simplexml_load_string($request->data);
$json = json_encode($xml);
$testset_array = json_decode($json, TRUE);

What I want now is to update some QC fields. For that, instead of GET, I need PUT. The code I've tried to update a test instance:

    $xml_data = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
            <Entity Type="test-instance">
                <Fields>
                    <Field Name="my_field">
                        <Value>my value</Value>
                    </Field>
                </Fields>
            </Entity>';

    $headers = array('Cookie' => $cookie, 'content-type' => 'application/xml');

    $url = 'http://qc.intra.xxx.com:8090/qcbin/rest/domains/' . $domainname . '/projects/' . $projectname . '/test-instances/404886';
    $request = drupal_http_request($url,
       array('headers' => $headers),
       'PUT',
       $data
    );

    $xml = simplexml_load_string($request->data);
    $json = json_encode($xml);
    $testset_array = json_decode($json, TRUE);

This is not working and I don't get any error also, what am I doing wrong?

Thanks

For starters, looking at your code, $xml_data is instantiated but never used in your call to drupal_http_request(), you use the $data variable instead. Intentional or the culprit?

Second, your call to drupal_http_request follows the Drupal 6 (and earlier) syntax, what system are you using?

For Drupal 7, it should look like this:

$response = drupal_http_request($url,
  array(
    'headers' => $headers,
    'method' => 'PUT',
    'data' => $xml_data,
  )
);

// this should reveal what was actually sent out
dsm($response->request);

Hope this helps some!


Automatically create hyperlink based on span class Does anyone have any idea how I can do this? I want my content writer to be able to add span classes to certain numerical amounts that then automatically hyperlink to a pre-defined URL. Example:

  And the price at John's hardware shop is$2.35

I am fully aware there is a module called Word Link Which does a fantastic job of hyperlinking specific keywords but as numerical amounts are not specific to anything this is a tad more challenging. What I mean by this is in Word Link you can say:

"coca cola" - link automatically to www.cocacola.com
"Nike" - link automatically to www.nike.com

"$5.67" is just a number so a span class would be approriate.

Grateful for any help.

You could do this in your field-template file.

<?php foreach($class in $classes)): ?>
  <?php if ($class == 'johns' ): ?>
    // do something
  <?php endif; ?>
  <?php if ($class == 'sarahs' ): ?>
    // do something
  <?php endif; ?>
<?php endforeach; ?>

Downside this way is you need to maintain a list in the templatefile.


Rules: how to programmatically set the bundle of an entity? For some tasks, rules requires to know the bundle of a given entity, the most obvious situation being when you need to set a field of a node and rules requires the type of node.

Normally you can solve this in the "condition" side of rules, where you can check that your entity is of a given bundle or that it has a specific field.
However there are situation where this approach is not possible, as when the entities derives from the result of an action, in my case they are loaded from a VBO view.
Hence how can you tell rules that a given list of entities - or a single entity - is of a given bundle, so I can use its specific fields ?

Actually, if you need to do something that's like an additional 'condition-then-action' within your rule's Action section, what you need is a Rules component!

You've loaded some entities in your action (perhaps in a loop) and now you need to apply a condition and action to those entities.  Here's the basic recipe for using components in your action section:

Go to /admin/config/workflow/rules/components to create a new rule component to run for each of the items in your loop (or for a single item you've gotten in your rule action). Click the 'Add new component' link at the top of the page
Select 'Rule' from the drop-down options, since this will be a component that contains both a condition and an action
Name the rule, and in the 'Variables' section, we have to let it know we're going to pass it a parameter to work with. In your case, this will be the entity you want to check.
Once you've named your components and named the parameter you'll pass it, the next screen looks very much like a regular rule.  Just set up the condition (make sure the entity is of type whatever) and the action (use the appropriate fields of that entity to do something).
Finally, save your component and call it in your original rule's action section (within the loop if you have one), passing it the entity to work with

Sorry that this is rather text-y.  I actually just recently answered a question about using rules components with commerce items in another question and included screenshots there, so see if you can use that as a reference too: https://stackoverflow.com/questions/17797285/drupal-commerce-order-object-extra-data/17843597#17843597

Let us know if rule components solve your issue!


privatemsg link for anonymous users I crated a view to show a list of registered users such as as name, email, job etc. one of the fields I am also listing is a private link so other members of the site would be able to contact that user.
Authenticated users can see the link and send a private message, but what I would like to to is to allow anonymous users to see the private message link but when they click on it they should be redirect to the login form. Is there a way to do that? I´ve been googling around and can´t find an answer.

I would really appreciate if you can help me to find a way to to this.

Thanks in advance

This might be what you are looking for (https://drupal.org/node/1988848)


Add a link to a tableselect row I'm interested in adding a link in a tableselect form row. Utilizing the #options key I can only add columns with strings. I am able to add form elements in the #options array similar to the #rows array.
$rows[$nid] = [
    'edit_link' => [
        'class' => 'edit_link',
        'data' => [
            '#type' => 'link',
            '#url' => Url::fromRoute('group_manager.edit'),
            '#title' => 'test',
        ],
    ],
]

//…

$form['table'] = array(
    '#type' => 'tableselect',
    '#header' => $header,
    '#options' => $rows,
);

Implementing this example as is doesn't render this column in the table, so I assume it has failed somehow.
The 'edit_link' element works if the form is changed to a 'table' instead of 'tableselect'.

I solved my issue.
The links column was not rendered for the tableselect form because I didn't update my $header array with the new element name edit_link.
It appears a table form does not map the element names to the header names, meaning I did not have to update the header array for my link columns to appear.  As long as the element name was in the header array Tableselect would render the column.  I believe this to be the basis of my issue.


What is $delta for in Field API hook_field_widget_form? d.o defines it as such:

  $delta The order of this item in the array of subelements (0, 1, 2, etc).

So that you can use it as an index into the $items array, but i can't seem to wrap my head around when the $items array would have more than one element.

See the answer to my question re; delta field in views.  I got an answer for $delta as well.


How to make user profile image reflect a transparent background? I made a site with Drupal 7.26. Added on the Advanced Forums module with some other things.

Everything works fine except the user profile image is displayed with a white box/background instead of being transparent in the forums and user profile when clicking on the user name. I'm using a png image that has a transparent background.

Here's a cropped screenshot of how the picture is being displayed in the forums.

As you can see there is a white box/background instead of it being transparent. The strange thing is that when I hover over the image with my mouse the white box/background disappears and the image displays as it should.

Here's a cropped screenshot of what it looks like when the cursor is hovered over the image.

That is how I would like the profile pictures to be displayed in the forums should a picture have a transparent background.

Does anyone know of a setting or something on how to get this done?

I'd really really appreciate any help with this as I'm pretty clueless.

Thanks in advance for any replies

Barrels

If the image background is transparent when you hover over it, then the picture has transparency, and must be a .png or .gif file.

Therefore the white background must be down to CSS

In Chrome or Firefox, right click on the image and select "Inspect Element". Find the CSS controlling the div or img, and change the CSS from

.picture {
   background:#FFFFFF;
}

to

.picture {
   background:none;
}


how to pass arguments in forms submit array in drupal I would like to pass arguments from the code.

`$form['td_deals']['fetch_deals'] = array(
    '#type' => 'submit',
    '#value' => t('Fetch Deals'),
    '#weight' => 45,
    '#submit' => array('td_import_fetch'),
  );`

The submit in the form calls a function td_import_fetch, i would like to pass another argument (A variable ) in that array. is it possible?

I assume you want to pass some data not entered by user. You can use hidden fields for that and when user submits his data you will get that field data as well and if you are bothered about tampering of data you can use #access to make sure its not tampered with.


tab tamer - problems with hiding tabs I have found quite nice drupal module, the "tab tamer". It allows admin to edit labels of tabs and sub tabs, but also disable or enable them. I have install the module, and set that user/register and user/password to "Disabled". Unfortunately I can see all the time both labels. Did I make something wrong? I use the latest drupal7. Great thank for any tips or advices :)

nykon

Most of the cases in drupal will have a class called as not-logged-in in the body. Make use of this and write

.not-logged-in .tab-class{
display: none
}

This will hide the registration and login form tabs. It is the easiest way to achieve the need.


Search facets by title vs node id I have Search API, Search API Solr and Facets setup in drupal 8.  The view settings used as data source for the facet is as below.

There are two content types: Language and Role.  Both are used as inline entities in other content types with field names: file_language and field_role.  The facet setting are as below:

However, in the facet browse view language is displayed with title link and role is displayed as node id link.

I am not sure which setting is causing this issue. How to display role by title, similar to language?

Thank you

Compared the facet definitions via Dev module and noted the " Transform entity ID to label" option.  That does it.


Can I extend the image field formatter without defining a custom one? XY problem: I need to extend the default image widget in the entity edit form with some custom fields so that, per image, e.g. a copyright and description, independently from the alt and title field, can be set.

I can add the fields by altering the core image module files, and by manually adding the respective database columns. But of course, I would like to alter the plugins with a custom module.

I was able to create a custom formatter based on the ImageWidget as described in this tutorial.

My question is: is there a way to alter the default image widget/ field type to add custom fields rather than defining custom formatters/ widgets?

As an alternative, more flexible way, you could chose to use either File entity or Media entity, both give you a fieldable entity that you can add your additional fields, without having to write a single line of custom code.

File entity makes the files themself fieldable and adds file types, so images can have different fields than videos for example.

Media entity adds a separate entity that you work with, and works well combined with a number of other modules like Entity Browser and Inline Entity Form. There are some good tutorials out there:

http://www.annertech.com/blog/reusable-media-drupal-8-tutorial
http://flocondetoile.fr/blog/managing-media-drupal-8


Why is $form_state always empty, even when my form-building-function is called after validation? I'm having a little trouble with the terminology here, so I'll explain my problem directly with code samples (trucated for clarity).

myModule.module

Here I create a menu with a link to a form built using a function declared in form_identification.php

[...]
require_once(dirname(__FILE__) . '/form_identification.php');
[...]
function myModule_menu() {
    $weight = 1;
    $items = array(
        'identification' => array(
            'title' => t('Identification'),
            'page callback' => 'identification_callback',
            'access arguments' => array('Acces myModule'),
            'type' => MENU_NORMAL_ITEM,
            'weight' => $weight++
        ),
        [...]
    );
    return $items;
}
[...]
function identification_callback() {
  return drupal_get_form("form_identification");
}
[...]

form_identification.php

This file holds the function which builds the form, called form_identification

function form_identification($form_state) {

    error_log("form_state: " . print_r($form_state, true));
    // always outputs `form_state: Array\n(\n)\n`

    $form = array(
        '#attributes' => array(
            'enctype' => 'multipart/form-data'
        ),
        'sex' => array(
            '#type' => 'textfield',
            '#title' => t('Sex'),
            '#disabled' => true
        ),
        /*[...]*/
        'enregistrer' => array(
            '#type' => 'submit',
            '#value' => t('Enregistrer'),
            '#submit' => array('form_identification_enregistrer')
        )
    );
    return $form;
}

function form_identification_validate($form, &$form_state) {
    /*[...]*/
}

function form_identification_enregistrer($form, &$form_state) {
    /*[...]*/
}

As you can see, I'm printing the contents of $form_state to the log every time form_identification is called, so I can confirm that the function is called on page load and also after validation. The problem is that in both cases, I just get an empty Array (Array\n(\n)\n). I would have expected to get an array full of form info when the function is called after validation. That way, I could have a look at the values entered and decide how to build the form based on them. Is there any way to achieve this? In what situation would $form_state NOT be an empty array?

You've just got the signature for the form function slightly wrong, it should be:

 function form_identification($form, &$form_state) {

The first arg that's passed to your form function by the form builder is the $form, which for a new form is pretty much always an empty array.


Programmatically create user reference field I want to add a user reference field in taxonomy term. I create field and it's instance:

$field = ['field_name' => 'mymodule_employee',
        'label' => t('Employee'),
        'type' => 'entityreference',
        'cardinality' => 1,
        'settings' => [
            'target_type' => 'user',
            'handler' => 'base',
            'handler_settings' => [
                'target_bundles' => ['user']
            ],
        ],
];
field_create_field($field);

$instance = ['mymodule_employee' => [
            'entity_type' => 'taxonomy_term',
            'bundle' => 'my_vocabulary',
            'field_name' => 'mymodule_employee',
            'label' => t('Employee'),
            'widget' => array(
                'type' => 'options_select',
                'active' => 1,
            ),
            'settings' => array(
                'target_type' => 'user',
                'handler_settings' => array('target_bundles' => null),
                'handler' => 'base',
            ),
            'display' => array(
                'default' => array('label' => 'inline', 'type' => 'entityreference_label'),
            ),
            'required' => 0,
            'default_value' => null,
        ],
];
field_create_instance($instance);

Everything goes ok. But when I'm creating the term and try to choose a user there is an empty list. When I go to the field settings in admin form and just save it, everything begins to work.

What do I forget creating field and instance?

Check if Entity Reference Autocomplete  module helps you. The module page says

  This module defines a new form element type, called "entityreference",
  that allows developers to add autocomplete fields to forms, so that
  users can reference any entity in the same way they would do through
  an Entity Reference field.


How to enable user defined module from the administration menu list? I am beginner to Drupal 7. I am trying to start with Basic Form handling. I created a directory my_module in sites/all/modules. Created my_module.info file using notepad with the following contents

name = My module
description = Module for form api tutorial
core = 7.x

Then I created my_module.module file with the following contents

<?php
/**
 * This function defines the URL to the page created etc.
 * See http://api.drupal.org/api/function/hook_menu/6
 */
function my_module_menu() {
  $items = array();
  $items['my_module/form'] = array(
    'title' => 'My form',
    'page callback' => 'my_module_form',
    'access arguments' => array('access content'),
    'description' => 'My form',
    'type' => MENU_CALLBACK,
  );
  return $items;
}

function my_module_form() {

  // This form calls the form builder function via the
  // drupal_get_form() function which takes the name of this form builder
  // function as an argument. It returns the results to display the form.
  return drupal_get_form('my_module_my_form');

}

/**
 * This function is called the "form builder". It builds the form.
 * Notice, it takes one argument, the $form_state
 */
function my_module_my_form($form_state) {

    // This is the first form element. It's a textfield with a label, "Name"
  $form['name'] = array(
    '#type' => 'textfield',
    '#title' => t('Name'),
  );
  return $form;
}

But when I goes to module list and tries to enable the newly created module  it is not being listed. Kindly help me to resolve this problem.
I have gone through several techniques shown in different forums like deleting multiple copies of the files,providing permissions etc.But all in vain.

You should follow these steps. This may help you to better understand that how to create custom module. If you have any query then comment below.

Link


Drupal Colorbox with Prezi iframe I have a Prezi file and the embedded code is like this:

I have installed Colorbox and activated Colorbox load and Colorbox inline in the module settings.

How can I open this file with Colorbox?

I've created a link and tried like this:

open in Colorbox (iframe)

The colorbox is opening, but it shows "This content failed to load".

You created your link by concatenating width=500&amp;height=500&amp;iframe=true with an ? instead with another &amp;
So the working link would be:

open in Colorbox (iframe)


How do I redirect a form after has been submitted? I need to upgrade this Drupal 6 code to Drupal 7.

I add a form submission handler to a form, using an implementation of hook_form_alter() that executes the following code.

array_unshift($form['buttons']['submit']['#submit'], 'MODULE_case_form_pre_submit');
$form['buttons']['submit']['#submit'][] = 'MODULE_case_form_submit';

The code for MODULE_case_form_submit() is the following.

function MODULE_case_form_submit($form, &$form_state) {
  if ($form_state['values']['type'] == 'case_slide') {
    $form_state['redirect'] = 'case/' . $form_state['values']['cid'];
    return;
  }
}

There isn't anything different between Drupal 6, and Drupal 7, for the code you are showing, which means:

$form_state['values'] still contains the values submitted from the users
$form_state['redirect'] is still used to redirect the users to a different page

What changes is that the submission buttons for the node edit form are inside $form['actions'].

  // Add the buttons.
  $form['actions'] = array('#type' => 'actions');
  $form['actions']['submit'] = array(
    '#type' => 'submit',
    '#access' => variable_get('node_preview_' . $node->type, DRUPAL_OPTIONAL) != DRUPAL_REQUIRED || (!form_get_errors() && isset($form_state['node_preview'])),
    '#value' => t('Save'),
    '#weight' => 5,
    '#submit' => array('node_form_submit'),
  );
  $form['actions']['preview'] = array(
    '#access' => variable_get('node_preview_' . $node->type, DRUPAL_OPTIONAL) != DRUPAL_DISABLED,
    '#type' => 'submit',
    '#value' => t('Preview'),
    '#weight' => 10,
    '#submit' => array('node_form_build_preview'),
  );
  if (!empty($node->nid) && node_access('delete', $node)) {
    $form['actions']['delete'] = array(
      '#type' => 'submit',
      '#value' => t('Delete'),
      '#weight' => 15,
      '#submit' => array('node_form_delete_submit'),
    );
  }


Not able to get textfield value to generate a ajax dependent dropdown option I am not able to get the textfield value to generate an ajax dependent dropdown option.That is when i am trying to enter a textfield value in the form and clicking a button to call the ajax function. The form value for the textfield i am getting is blank.Here's the code snippet:

/*
* function to add the images to the gallery
* @param: none
* @return: none
*/
function image_gallery_add($form, &$form_state) {
$form['#tree'] = TRUE;
$form['add_image'] = array(
    '#title' => t('Add images to gallery'),
    '#type' => 'fieldset',
);
$form['add_image']['gallery_name'] = array(
    '#type' => 'textfield',
    '#title' => t('Please enter the gallery name'),
);

$form['add_to_dropdown'] = array(
    '#type' => 'button',
    '#value' => 'Add To Dropdown',
    '#ajax' => array(
        'event' => 'click',
        'callback' => 'image_gallery_select_options_callback',
        'wrapper' => 'dropdown_gallery_replace',
    ),
);

$form_field_val = isset( $form['values']['add_image']['gallery_name'] ) ?  $form['values']['add_image']['gallery_name'] : '';
$form['add_image']['select_gallery'] = array(
    '#type' => 'select',
    '#title' => 'Select Gallery',
    // The entire enclosing div created here gets replaced when textfield gallery_name changes
    // is changed.
    '#prefix' => '
',
    '#suffix' => '
',
    // when the form is rebuilt during ajax processing, the $selected variable
    // will now have the new value and so the models will change
    '#options' => automobile_get_model_dropdown_options($form_field_val),
    '#default_value' => '',
);

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

}
/**
* Handle post-validation form submission.
*/
 function image_gallery_submit($form, &$form_state) {
    $name = $form_state['values']['add_image']['gallery_name'];
     print( $name );exit();
  }

 function automobile_get_model_dropdown_options($key = '') {
     //dpm($key);
   $options = array(
            t($key) => drupal_map_assoc(array(t($key))),
        );
     if (isset($options[$key])) {
          return $options[$key];
      }
      else {
           return array();
      }
  }

 function image_gallery_select_options_callback($form, $form_state) {
   return $form['add_image']['select_gallery'];
 }

Can anyone suggests what i am doing wrong? I am attaching a screenshot of the situation too...

Not sure, but from the looks of it (I think) you need to set

$form['#tree'] = TRUE;

When building your form.


Hiding referenced term name from node display I've stumbled upon a situation where I want to display a link and a custom icon for the link (I'm using paragraphs module) which will be themed correctly later, BUT. After providing a taxonomy term with a image field and making it display ONLY the image by default I'm still getting a h2 of the linked terms name.

I already tried hook_entity_view, but it doesn't have separate values for icon and the randomly displayed term name - only the term id meaning I cannot unset it at this hook.

Any suggestions/experience on how should we work with this?

In the content type or paragraph type go to Manage Display and configure the format of the term field as "Rendered entity".

Copy taxonomy-term.html.twig to the template folder of your theme and remove the linked title:
{{ name }}

taxonomy-term.html.twig

  {{ title_prefix }}
  {% if not page %}

{{ name }}

  {% endif %}
  {{ title_suffix }}
  {{ content }}


Pager will come by default in blogs template or not? I am using blogs  module in one of the website. I have created a template file for that, I want to add pager if blog items exceeds that 10. So my question is in that template file how can I use pager. It will display by default or is there any other ways to add pager to that template.

If you are creating a custom template for the blogs created by the blog module you will have a variable called $pager available to you in that template. Wherever you want it displayed you can just add something like this:

<?php echo $pager ?>

If you look in blog.pages.inc you'll see that the "pager" is added to the "$build" render array in each of the menu callback functions defined in that file.


What is the suitable file permission for 'files'? I have written this small bash script to rebuild D6.22 file permissions:

#!/bin/bash
cd /path/to/drupal

chown -R bob:www-data .

find . -type d -exec chmod u=rwx,g=rx,o= {} \;
find . -type f -exec chmod u=rw,g=r,o= {} \;

cd /path/to/drupal/sites

find . -type d -name files -exec chmod ug=rwx,o= '{}' \;
find . -name files -type d -exec find '{}' -type f \; | while read FILE; do chm$
find . -name files -type d -exec find '{}' -type d \; | while read DIR; do chmo$

chmod -R 777 /path/to/drupal/sites/default/files  #bad idea??
chmod -R 755 /path/to/drupal/tmp

echo "Permissioin rebuild is done!"

Of course prior to executing the script 'bob' should have been added to www-data group using

  usermod -G www-data bob

I know that a security-aware admininstrator should avoid giving 777 permission to web server, however when I assign 755 to files, users can not upload image/avatars and I get a warning that says sites/default/files/pictures/picture is not writable.

So what alternative permission do you use for 'files' (and works)?

Thanks

This really depends on how you have Apache configured.

I almost always run Apache in prefork mode.  When I do this, I

chown -R apache.apache sites/default/files
find sites/default/files/ -type d -exec chmod 755 {} \;
find sites/default/files/ -type f -exec chmod 644 {} \;

This lets Apache write to that directory.  Note that the owner/group depends on the setting from httpd.conf.

When I use FastCGI, then I use the user that Apache runs as.

The main key is that your files/ directory is owned and writable by just Apache, and that the rest of the files in docroot are owned and writeable by someone else, and not writable by Apache.  Normally this is the user I run drush as.

One quirk has to do when drush runs things that write to this directory, like bam-backup.

Then I will add my drush user to the Apache group, and do

chown -R apache.apache sites/default/files
find sites/default/files/ -type d -exec chmod 775 {} \;
find sites/default/files/ -type f -exec chmod 664 {} \;

so that drush can write to files, but Apache can't write to the rest of docroot.


Pass Webform Submission Back to Form Template I'm trying to use a webform to accept data, do some processing and calculation, and pass it back to the user. For user-friendly purposes I don't want to redirect to a confirmation page, but back to the form page so they can enter the information again. So essentially, I want the form template to submit back to itself, and if it has received a submission, print out the results (for now). I'm having trouble finding a way to do this.

I have an override template (webform-form-9.tpl.php) in my theme folder and it is successfully overriding the default, however I can't find any any way to actually get the values the user just submitted - even printing all available variables doesn't display the submission. I can't even seem to check if the user submitted a form or not. Does the form template not even receive the submission data? That seems extremely peculiar if so, so I can only imagine I'm not just not getting it right.

Any advice here?

Just configure your webform, so the "redirect URL" is the following:

node/[node:id]/submission/[submission:id]

Now after submission you will see the result overview page of that submitted form


Drupal unexpected "Fatal error: Class name must be a valid object or a string [...] common.inc" on every page "Fatal error: Class name must be a valid object or a string in C:\xampp\htdocs\uc\includes\common.inc on line 7506"

The error above showed up unexpectedly. I was adding a "Long text" field to a content-type, but when I expected to be brought to a saved field configuration page, I instead got a Fatal error on every page.

I had a look at includes\common.inc:

/**
 * Get the entity controller class for an entity type.
 */
function entity_get_controller($entity_type) {
  $controllers = &drupal_static(__FUNCTION__, array());
  if (!isset($controllers[$entity_type])) {
    $type_info = entity_get_info($entity_type);
    $class = $type_info['controller class'];
    $controllers[$entity_type] = new $class($entity_type); // Line 7506
  }
  return $controllers[$entity_type];
}

However, I just don't understand Drupal at a low enough level to understand the relationships between these variables and functions.

I also searched Drupal for people with a similar problem:

(1) I found one user who claims that I have to install the submodule "Relation Endpoints Field", but searching Drupal, there doesn't seem to be such a module.

(2) Another user suggested clearing the cache manually:

DELETE FROM cache;
DELETE FROM cache_filter;
DELETE FROM cache_menu;
DELETE FROM cache_page;
DELETE FROM watchdog;

(via WordPress API, misleading name, I know.)

Clearing those tables from the cache did not help.

(3) And another user suggested disabling old modules, specifically the "Old search facets" module. Because I can't find a module specifically pertaining to old search facets, I went into MySQL system table, and marked the Search module's line with a 0 status, indicating to stop loading the module altogether.

On that same link as (3), one user suggested enabling the Database Search Module, so I dropped all the tables, imported the latest stable .sql, and installed the module, but after recreating the problem (trying to add a field to a content-type), that as well concluded fruitless.

Still, the problem remains

The Fatal error shows up on every page, making the site completely non-functional. Any help or direction would be immensely appreciated. Thank you for looking.

The error means that Drupal can't find the entity type information for a entity that it tries to load.

Add var_dump($entity_type); in there and reload the page. The last one that it's going to print (if there are multiple) is the culprit. What you need to do then depends on the entity type. It could for example be that you disabled a module which is still being called.


Sub folders and how to namespace classes In Drupal 7 I can have a module inside another module. Is this still the case in Drupal 8 and how would I namespace classes inside the sub module?

Another thing I can do in Drupal 7 is to create sub folders inside the modules folder to group my modules.

Example:

sites
--- / all
--- / --- / modules
--- / --- / --- / Collection_Alpha
--- / --- / --- / --- / module_a
--- / --- / --- / --- / module_b
--- / --- / --- / Collection_Beta
--- / --- / --- / --- / module_x
--- / --- / --- / --- / module_y

Is this still possible in Drupal 8? If yes, how would I have to namespace my classes so the autoloader can resolve it to the correct folder structure?

e.g.: Drupal\Collection_Alpha\module_a\myClass1 ?

@Clive is correct.

The namespace is always Drupal\{module_name}. Where that module lives is irrelevant (as long as it is somewhere where Drupal can find it). That namespace always points to $path_to_module/src.

It would not possibly work in any other way. Different sites have modules in a different structure and different places, but the same code has to work no matter where.


Profile 2 - My account displayed together i included profile2 into my account page via any settings, and now have realy problem to find where i set it, could someone please help me? It was just one check box, please help me. thx

Do you mean you want to have separate tabs to edit your account information and profile information? If so, edit the profile type and check the "Provide a separate page for editing profiles." option.


path alias hook menu i18n Is it possible to make path alias that is not storing in database, like using system hook menu path I want to make url for en/weather and rs/vreme.

e.g

<?php
function weather_menu() {
    $items = array();
    $items['weather'] = array(
      'title' => 'title',
      'description' => t('description hook menu'),
      'page callback' => 'weather_page',
      'access callback' => TRUE,
      'type' => MENU_CALLBACK
    );
     return $items;
}
?>

Follow below steps to add path aliases to "weather" menu path

Enable locale module
Go to admin/config/search/path/add
Select language rs and add path alias as "vreme" and Existing system path as "weather"

That should work !:-)


Git Workflow Acquia Cloud and Acquia Dev desktop I use Acquia Cloud and installed Drupal 8 and cloned this (origin) locally using Acquia Dev desktop.

To use Dev Desktop I think I'm able to develop the Front-end design
faster, instead of committing the changes every time and push them
to Acquia Cloud to see them in the browser. Am I right?
And will my client also be able to commit his code from his local branch
to the Acquia Cloud repo?

Working on the frontend isn't tied to using Acquia Dev Desktop or
not. It's a personal preference to work locally by cloning a remote
site and work on theming/frontend and commit changes periodically to
the remote repo when you're happy with the changes you see in your browser. Some customers prefer working directly on the Acquia Cloud dev environment with Livedev. Really, it's what you think is best for you.
Git is a decentralized version control system. It means both you and your client can checkout the Acquia Cloud repo and hold a live copy of the repo. You and your client can then commit/push code either to the default branch (master) or with a feature branch. This is by no means specific to Acquia Cloud. This is how git works. What matters is you git pull always before committing / pushing code, so that you can retrieve the changes your client has made on the current working branch (e.g. master). With a feature branch, it'll require you merge it back to e.g. master when it's ready. See https://git-scm.com/book/en/v2/Git-Branching-Branches-in-a-Nutshell for details.


can't delete the preview button I have used the following code to delete the preview button which is on one of my create content type pages, but its not doing anything, what am I doing wrong?

function example_module_form_alter(&$form, $form_state, $form_id) {
// Check for a particular content type's node form.
if ($form_id == 'example_content_type_node_form') {
drupal_set_message("entering formId");

unset ($form['preview']);
}
}

the drupal_set_message does go off, so I know that I am entering the if statement. I have put this code in a custom module (example_module).

You don't need to use custom code to delete the preview button.  On the Content Type administration page at admin/structure/types/manage/your_content_type, you can selection Disabled for Preview before submitting under Submission form settings.  This will remove the preview button for that content type.


How to add library if Ajax is enabled for view? We have a view, myview, where Ajax is disabled. We created a custom library that would override the load more button's indicator so that we can use our own. However, we would only like to add this library conditionally if myviews->Use Ajax->Enabled, but when it is disabled then do not add the library. I know how to conditionally add the library, but not sure how to check if myviews->Use Ajax is set to enabled.

How can we detect if myview->Use Ajax->enabled?

mytheme.libraries.yml

mytheme-custom-indicator:
  version: 1.0
  js:
    /path/to/js/custom-indicator.js: { attributes: { defer: true }}
  dependencies:
    - core/drupal
    - core/drupal.ajax
    - core/jquery

custom-indicator.js

 /**
   * Infinite scrolling progress indicator.
   *
   * @type {{attach: Drupal.behaviors.progressIndicator.attach}}
   */
  Drupal.behaviors.progressIndicator = {
    attach: function (context, settings) {
      Drupal.Ajax.prototype.setProgressIndicatorFullscreen = function () {
        this.progress.element = $('<div class="myclass"> </div>');
        $('body .pager').after(this.progress.element);
      };
    }
  };

What we tried

/**
 * Implements hook_views_pre_render().
 */
function ns_general_views_pre_render(ViewExecutable $view) {
  // Add library to all for ajax progress.
  $view->element['#attached']['library'][] = 'mytheme/mytheme-custom-indicator';
}

Goal

/**
 * Implements hook_views_pre_render().
 */
function ns_general_views_pre_render(ViewExecutable $view) {
  // Add library to all for ajax progress.
  if($view->hasAjax) {
    $view->element['#attached']['library'][] = 'mytheme/mytheme-custom-indicator';
  }
}

Found my answer after doing ksm($view)

/**
 * Implements hook_views_pre_render().
 */
function ns_general_views_pre_render(ViewExecutable $view) {
  // Add library to all for ajax progress.
  if($view->ajaxEnabled()) {
    $view->element['#attached']['library'][] = 'mytheme/mytheme-custom-indicator';
  }
}


How to get the list of blocks for the current page? I'm trying to get the list of all blocks for a certain page, but I can't figure how to do that.

How do I get the list of all the blocks that are rendered for a page, independently from the region where they are put?

To get all blocks in an array by region, you can do as follow

// Get the current theme used
$theme = \Drupal::theme()->getActiveTheme()->getName();

// And pass the theme name to get all the regions
$regions = system_region_list($theme, $show = REGIONS_ALL);

// This will give you all the regions in array format
$regions =  json_decode(json_encode(system_region_list(\Drupal::config('system.theme')->get('default'),$show = REGIONS_ALL)),true);

// Loop over each regions
foreach ($regions as $key => $region) {
  // Get the blocks in particular region
  $blocks[$key] = \Drupal::entityManager()
    ->getStorage('block')
    ->loadByProperties([
      'theme' =>  \Drupal::config('system.theme')->get('default'),
      'region'=> $key,
    ]);
}


Custom fields for every page I have few pages and need to add custom color and background image to every page and need to edit it from admin.

The best solution for me is adding custom variables in view or menu item. And then use it in page.tpl.php.

Is there any way to do it without a module?

ok let us try this ,,, maybe help

1- add new image field to your content type (background field)

2- open node.tpl.php in your theme

3- test if this node from this content type ,, then get the value of the background field image

4- do some thing to make this image url as a background

do the same with a little bit different for the styles :)

For Specific URL (this way maybe not professional):

1- create new content type (Backgrounds) with two fileds (URL + Image)

2- open page.tpl.php and write some php code can test if the current URL exists in any node from content type (Backgrounds)

3- if yes => get the image field and make it as background


How can I have a employee ID read-only in Drupal Profile, set by Admin? I need to have a field in user profile named Employee ID, this field should only be set by admin (Read and write), read-only to user, and hidden from all other users.
Thank you.

You can use the field_permissions module to set up permissions for fields by user role and then limit access to admin. If you want to limit to one person then set up a separate role and give that role only to one person.


How to wrap a contact form with another block? Is there a method to wrap a contact form with another block and make them together a new block or something?

I want to put some information next to the contact form and put them together in a container. Furthermore I want to place other blocks above and under it, so I prefer not to edit in the region twig file.

Note: I want to have some text next to my contact form. So it doesn't neccesary have to be a block, but that was the first that came up to me.

Have a look at either of the contributed modules below (quotes are from their project pages).
Contact Block

... provides contact forms in a block. It uses the contact forms that can be created using the Drupal 8 core Contact module.

Release info: only for D8.
Entityform block

Allows to load a specified entity form as a block.
Usage: Go to the Block layout admin page (admin/structure/block), press Place block in the desired region and select Entity form.

Release info: Either for D7, or D8 (but only an alfa release for D8 right now).


User Reference field with full list of users, but with current user as default selected value Whether I'm using User Reference module or Entity Reference module, I can't seem to create a drop-down list of all users, where the current user is selected by default.

So all users will be in the list, but I just want to the default selection to be the current user.  How can I do this?

Using hook_form_alter():

function example_form_alter(&$form, &$form_state, $form_id) {
    global $user;
    if ($form_id === 'my_form') {
        $form['field_user']['#default_value'] = array($user->uid => $user->name);
    }
}

Not tested, but it's the idea.


How to override single function of theme's template.php using sub-theme? Target: Drupal 7 Sub-Theme Development
I don't want to override whole template.php file. I just want to override single function of template.php file.

It really depends on the type of function:

If it's a theme function (theme_username()) you could simply re-declare the function with your sub-themes name (SUBTHEME_username()).
If it's a preprocess function, you can have your own version of the preprocess in your sub-theme, but IIRC the parent theme preprocess will still be invoked.
If it's a your own function (not a standard HOOK based function), then you would have to put some of your own logic to allow other themes to overwrite it.

Maybe provide some more information on the function in question so that someone can give you a more specific answer.


Change module's weight - by module or manualy I am looking for solution how to change particular module's weight in D7. I know that it is possible to do in config tables in database, but I don't know how. Another solution that I found in Drupal.org is to use hooks - but I need more detail explanation or some guidance where I could get some tutorials about that.

The thing that I need to do is to make some priorities of some particular modules higher for it to load faster than other modules as otherwise they will not work. One of the examples is video streaming using Lightbox2 popup watching that on Safari browser on OS X - it's not loading until you change the priority of Lightbox module.

Since it was explicitly asked, there is also a module, Modules weight, that performs this task as well.

  We always need to modify modules execution order, and some could write
  a code that execute a query to modify the weight of a module in system
  table, some might go straight to his favorite SQL client and modfiy
  the record directly, This module provide admin interface for
  users/people has the access to modules page to reorder the module
  weights as they want


How to decrypt data from Encrypt module One of my webform component is using Webform Encrypt. The Encrypt feature is from Encrypt and Key modules. I set the key and encrypt as following. Everything is working fine in the submission data, but how can I decrypt the encrypted data if I send the data to someone? I have been searching this for days with no solution. Some online AES calculator has "IV" input and I don't know where to get that information.

Key:
type type: AES Encryption
key size: 256
key provider: file
file location: something/encrypt_key.key with based64-encoded

Encrypt:
General setting: enabled
Encryption Method: Mcrypt AES (CBC mode)
Key Provider: Key module(It's the key I made from Key module)

--- update question --- Apr 14th 12:24pm
How the person decrypt the data when I sent the encrypted data to him/her?

You can call the decrypt() function as seen in _webform_encrypt_decrypt_nested_values:

/**
 * Helper function to recursively decrypt values in a webform structure.
 */
function _webform_encrypt_decrypt_nested_values(&$element, $key = '#default_value', $restrict = array()) {
  // Determine if we are checking access.
  $access = empty($restrict) ? TRUE : user_access('view encrypted values', $restrict['account']);

  // Loop through each item and decrypt the value.
  foreach (element_children($element) as $name) {
    $component = &$element[$name];
    if (!empty($component['#webform_component']['extra']['encrypt'])) {
      if (is_array($component[$key])) {
        foreach ($component[$key] as &$value) {
          $value = $access ? decrypt($value, array('base64' => TRUE)) : t('[Value Encrypted]');
        }
      }
      else {
        $component[$key] = $access ? decrypt($component[$key], array('base64' => TRUE)) : t('[Value Encrypted]');
      }
    }

    // Recurse if the current item has children.
    _webform_encrypt_decrypt_nested_values($component, $key, $restrict);
  }
}

So in your own code you want to call something like decrypt($value, array('base64' => TRUE)) where $value is (saved) encrypted webform submission data.


Module to embed content in a iframe? I'd like to add a button to every of my article pages, that would open a box containing an iframe code embedding for example the title, the content and the image of the article in another page.
Does it already exist a module doing this? I tried Iframe and Entity Iframe, couldn't get what I want though.

Thanks for your help.

In your node--contenttype.tpl.php you can add a div (optionally with a textbox) which is hidden by default and fill it dynamically with the title and content of your node. Create a button that uses the colorbox module to show that div when pressed and your done.

  <textarea>

<?php echo $node->title;?>

      etc..

  </textarea>

Alternatively you could just use javascript to copy the content of your page to a div when the button is pressed.


Webform : A partially-completed form was found. Please complete the remaining portions Yesterday I have updated webform module from 7.x-4.0-beta3 to 7.x-4.9.

Post to that I am getting this notification message, throughout the site :

  A partially-completed form was found. Please complete the remaining portions

I have also checked some threads :

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

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

When I check log entries I got this  error :

  Notice: Undefined property: stdClass::$is_draft in webform_client_form()

Which suggest that some alteration leading this issue but unable to get any solution.

Try this:
Delete the form submission that is having problem(that is the submission id that is partially filled) in the following tables:

webform_submitted_data
webform_submission


Loading a form by ajax I've been stucked on problem since two weeks.
Basically, what i'am trying to do is:
1) Create a page, in which there is an link ("Click me"),
When i click on it, a form is fetched from another page and added to the current page.
The form is correctly fetched, but it seems any javascript/ajax related to the form is lost.
I have a custom  Ajax submit callback for this form, on the page of the form(submit button has class ajax-processed), it is working correctly but when fetched by Ajax(submit button does not has the class ajax-processed), it doesn't.

Below is my code:

<?php

function custom_preprocess_page(&$vars){

  drupal_add_library('system', 'drupal.ajax');
  drupal_add_library('system', 'drupal.form');
    drupal_add_js(drupal_get_path('module','custom').'/custom.js', 'file');
}

/**
 * Implements hook_menu
 * @return string
 */
function custom_menu() {

    $items['my-test/my_form'] = array(
        'title' => 'Ajax test',
        'description' => 'Page containing form',
        'page callback' => '_custom_retrieve_webform',
        'access callback' => TRUE,
    );

    $items['my-test/retrieve_form'] = array(
        'title' => 'Ajax test',
        'description' => 'Page where form should be loaded by ajax',
        'page callback' => '_custom_retrieve_html',
        'access callback' => TRUE,
    );
    return $items;
}
function _custom_retrieve_html(){
    return '
'. t('click me'). '
';
}
function _custom_retrieve_webform(){

   $node = node_load(12);
   $submission = (object) array();
   $enabled = TRUE;
   $preview = FALSE;
   $form= drupal_get_form('webform_client_form_12', $node, $submission, $enabled, $preview);
  return '
'.drupal_render($form).'
';
}

function custom_form_alter(&$form, &$form_state, $form_id) {
    if ($form_id == 'webform_client_form_12') {
        $nid = $form['#node']->nid;
        $form['submitted']['gender']['#default_value'] = 'M';
        $form['actions']['submit']['#ajax'] = array(
            'callback' => 'mymodule_webform_js_submit',
            'wrapper' => 'webform-client-form-' . $nid,
            'method' => 'replace',
            'effect' => 'fade',
        );

       //$form['#theme']=array('custom_web_form');

       array_unshift($form['#theme'], 'custom_web_form');
    }
}

function mymodule_webform_js_submit($form, $form_state) {
      // define the $sid variable (submission id from webform)
      $sid = $form_state['values']['details']['sid'];
      // if we have a sid then we know the form was properly submitted, otherwise, we'll just return the existing $form array
      if ($sid) {

        dsm($sid);

        $confirmation = array(
          '#type' => 'markup',
          '#markup' => 'sucess',
        );
        // return the confirmation message
        return $confirmation;
      }
      else {
        // return the form
        return $form;
      }
    }

My js:

(function($){

    Drupal.behaviors.my_custom= {

        attach:function(context,settings){
            $('a.clickme').click(function(e){
                $('#justadiv').load('/d7/my-test/ajax_loaded #webform-client-form-12', function(response, status, xhr) {

                    Drupal.attachBehaviors('#webform-client-form-12');

                });
                Drupal.attachBehaviors($('#webform-client-form-12')[0]);
            });

        }

    }

})(jQuery)

CAn anyone tell me what is wrong ?

Solution posted here:

basically:

  You need to generate the javascript settings for the form, and send
  them to the browser to be merged with the existing settings. Without
  doing this, any AJAX on your form will not work.

https://drupal.org/node/2009252


Sending a value to JavaScript I have set theme handler for a form in Drupal and this handler has a template file.
What is the easiest way to send a value from PHP to JavaScript in that include file?

The standard way to do this in Drupal is with drupal_add_js, using the "setting" type:

drupal_add_js(array('variableName' => 'value'), 'setting');

That will make the variable available on the JS side at Drupal.settings.variableName.


is it possible to have two input fields per label in a Drupal form? I've got a Drupal 6 form API question which may or may not be possible, or a good idea.

Is it possible to have two input fields per label?

I'm familiar with this format:

$form['example_textfield'] = array(
'#type' => 'textfield',
'#title' => t('text here'),
'#size' => 30,
'#maxlength' => 32,
'#required' => TRUE,
);

As the way to make one label with one field, but is it possible to have one label and two input fields? and create something like:
label: {input field} {input field}

If there is a way to do it, how would I get the two values into the DB table?

Is such an approach even a good idea?
or should I stick to the single label/single input field method demoed above?

You cannot have a label for two form fields, as the label is output with HTML code similar to the following one.

Category: *

The attribute for accepts a single form element ID; you cannot use the following HTML, for example.

Category/Recipients: *

If you don't want to use a label for the second form element, you can simply use an empty string for the #title property.

As for saving those values in the database, a label is not used when saving the value of a form element, but it is used only on the user interface. The code for saving the content of a form element doesn't use the label value, but the identifier associated to the form element.
In your case, the form submission handler would get the value entered from the user for the $form['example_textfield'] element from $form_state['values']['example_textfield'] where in Drupal 5 would have used $form_values['example_textfield'].


Is there a flag hook (flag module) which is called when a flagged node is saved? I am using the flag module to flag content.

Say user A flags a node. When user B updates the node, I want to send a mail to the user A (who flagged the node - I know I can use the Notifications and Messaging module but I want to send a notification in another way).

Is there an hook called when a flagged node is saved? So I can tap in on that hook and then retrieve a list of all users who flagged the node?

Thanks!

Paul

Is there an hook called when a flagged node is saved ?

No

However, you can use hook_node_update to trigger on a regular node save and check users who have flagged the current node ID.

You can also do most of the work without any coding using Rules, Views, Views Bulk Operations and obviously, Flag module.


What permissions are needed for omega tools to create subtheme I am looking to use Omega Tools, and similar modules quite a bit in the near future, and I am running into this error when trying to create a subtheme using Omega Tools:

I'm at least familiar with the concept of permissions, but I'm unfamiliar with what permission needs to be given to what.  Also, is this something that should be done?  I know that write permissions shouldn't be given willy-nilly.

Note: ygf is the directory for the site.  The current permissions on the folder are rwxrwxr-xThe all folder, which is the default gives the same error.

To work, the user that runs your web server needs to have write permissions to the target folder. Typically, you have a user that owns the files and then the web server runs as the group so permissions of 755 (ex. rwxr-xr-x) would work on most files except files/directory that drupal needs to write to (ex. files directory, or in this case, your themes folder).

What you need to do is either

change group ownership of the ygf folder above to the same user that runs your web server;
or - you can blow open the permissions to the folder (ex. chmod -R 777 ygf) temporarily and then switch it back after this operation.

Regardless, you're probably going want to remove the write permissions on this folder after omega tools has generated the sub theme. Omega Tools just needs this temporarily and it can be risky to have group-writable folders outside of the files directory.


How do I get the submitted moderation state of a custom block? I am a bit new for Drupal and currently working on Drupal8. I need to implement custom restrictions for workflow. Basically i want to get the submitted value of moderation_state filed in mymodule_form_alte

Here are the things that i have tried but all returns Null. The strange thing is that the below method works for node but do not work for block_content

 function mymodule_form_alter($form, &$form_state, $form_id) {
   $formSate = $form_state->getValue('moderation_state')[0]['valye'];
   var_dump($formState); // Output : Null

   $formSate = $form['moderation_state']['widget']['#default_value'];
   var_dump($formState); // Output : return the default value of dropdown not the one that i have selected
}

Here is the moderation_state field

all most there try the following

// Get the current  entity.
$entity = $form_state->getFormObject()->getEntity();
$moderation_state = $entity->get('moderation_state')->getString();
// Do the things.

or
   in a submit or validation thing
   try to

// use dump() as it is way better
dump($form_state->getValues()) // <-- and find in the array


default email not showing up in webform I had used files of a website to create new website. I had changed the database and user details in settings.php. Now everything is working fine except email settings in webform. It is showing old informations as default.

I need the default email to be "noreply@pharmahelpdesk.net".
In Configuration > System > Site Information , I had used the same email id. But it is not getting updated. Due to this I am not receiving emails. Please see the images and suggest.

.

I think here is a option to change default email admin/config/content/webform.


How to get custom product line item text field value? by using commerce customisable products module, I created a custom product line item type to which I added a text field (Machine name field_license_details). By following this excellent video tutorial
http://commerceguys.com/blog/commerce-module-tuesday-commerce-customizable-products-screencast

I was able to create a node/page which include the text field I mentioned before. However, what I find impossible to do, is to get the value that the user entered to that field. For example, when the user has entered something in the text field and clicks the add to cart button, I want the text he typed , to be 'placed' to a variable so i can do whatever i like with it for example display it back to the user or write it down to a file etc.
I understand that in order to achieve that I would need to write my own module , but I am not sure which hook I should implement, and how exactly  extract the string to a variable.
As you probably already understood by the nature of the question ,I am just getting started on drupal, so any suggestions would be more than welcome.
Thanks in advance
PS I am using drupal 7.22 (the latest stable version and I have installed the drupal commerce module, the commerce file and commerce customisable products modules.

I ended up doing the following :

    function my_Module_form_alter(&$form, &$form_state, $form_id){
           if ($form_id == 'commerce_cart_add_to_cart_form_12'){
                  dpm($form, 'cart form'); //to use with deve module
                  $form['#submit'][]=('my_Module_commerce_add_to_cart_form_12_submit');
                  }
            }

       function my_Module_commerce_add_to_cart_form_12_submit($form, &$form_state){

             $user_text_temp=$form_state['values']['line_item_fields']['field_license_details'][LANGUAGE_NONE][0]['value'];
             dpm($user_text_temp, 'extract value is ');
            // whatever else you want to do with that user_text_temp value
          }

I think that's the easiest way to do what i want. I posted it because it may be of use to people new to drupal.


How to theme the PAGE template for user account? The user account page should have the title(name or username),user pic on the left, basic details like gender, city, state and country to the right. The local tasks tab should be available below those regions.

I tried page--user.tpl and page--user--profile.tpl. Doesn't work.

Am using drupal 7 with an adaptive sub theme and don't know PHP much.

it can be override with user-profile.tpl.php file.

  Default theme implementation to present all user profile data.

  This template is used when viewing a registered member's profile page,
  e.g., example.com/user/123. 123 being the users ID.

REF here


Relative and broken image with simplenews and mime mail I have a content type with an image field. When I send a test mail with the simplenews module I get an image with an absolute path in email and see the image, but when I send it with cron I get a broken image because image url is relative. How can I solve this problem?

I am using simple news 6.x-1.3.

How are you calling cron?

You need to make sure that the base_url is set.

E.g., when calling cron with drush, you need to provide the --uri http://example.org parameter.


Tracking multiple items in a Commerce order individually I need to track items individually in a Drupal Commerce store that I'm building, and I'm wondering if anybody here have an idea how to make this happen. Let me expand on this a bit:

If a customer puts 3 items in the cart, does the whole checkout process, pays for them etc. the store manager should be able to set statuses individually for those 3 items.

Most of the times these items will be shipped seperately, therefore the store manager should be able to set the first item to shipped while the other two is pending for example.

The only solution we've came up with is to explode the order into three seperate orders so after that one order, the store manager would see three orders with each product on the admin interface. Making this solution happen perfectly (set the right order totals to each order, set them to paid after the one payment, delete original order etc) introduces a lot of problems and it's a lot more complicated than we've expected.

Is there more straightforward, better solution out there for this purpose?

Thank you!

Since line items are fieldable, why not consider adding a field to the line item type and either switching to the Inline Entity Form for line item management on the order edit page or else creating a custom interface (Views + editablefields?) for manipulating the value of those fields?

That's what I'm going to be doing on a friend's site to track related eBay listings.


Is there anything like get_variable storage that doesn't get loaded every page? I have a custom module and I want to store a long bit of text (~20kB).

I was going to use variable_get but as I understand all vars accessed this way are loaded for every request, which is a memory waste as this will only be used for one block.

cache_get is not appropriate because I don't want the data getting cleared on cache clear. It's not really cache.

Is there anything else like that?

Variables are loaded on every page anyway, regardless of whether your custom code requests a specific variable be loaded or not.

So, the only extra memory overhead you will incur is whatever PHP packs your 20kB of data into.

If your app is sensitive enough for that to matter, then either create a custom table to store the data, or just write it to a static file and read it back from there. If not (more likely), then just use the standard variables method, it's easier.


user_login_block not displaying status messages I am creating my own theme for my website, and am having an issue with the user_login_block form. I have a simple jQuery dropdown style content div in which I am outputting the form, and have no clue why it is not displaying status messages (invalid login attempts, ect..). When entering incorrect credentials, the page simply refreshes and nothing is displayed to the end user. I am new to Drupal, but not new to PHP. I have no idea what I could be doing wrong. My code is below, any help would be much appreciated.

hook_form_alter:

function dtn_form_alter(&$form, &$form_state, $form_id) {
    switch($form_id) {
        case 'user_login_block':
            $form['links']['#markup'] = '

' . t('Request new password') . '

';
            $form['name']['#title'] = Null;
            $form['name']['#attributes'] = array('placeholder' => t('Username'));
            $form['pass']['#title'] = Null;
            $form['pass']['#attributes'] = array('placeholder' => t('Password'));
            break;
    }
}

Login Form Source:

$userLoginForm = drupal_get_form('user_login_block');

$output .= '
';
$output .= '
' . t('Login') . '';
$output .= '
';
$output .= render($userLoginForm);
$output .= '
';
$output .= '
';
$output .= '
' . t('Register', ['!url' => url('user/register')]) . '
';
$output .= '
';

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

return $output;

}

I think you are embedding Login Form directly in .tpl file. Either assign login block to some region or bring it through a variable from hook_preproces_page() function.


Conditional Field in Content Type I am looking for a module or a method in Drupal 7 that can achieve the following:

I have a field in a content type called e.g. "Is the Ladder Attached".
It has a select list, YES or NO.

When a user selects YES then I want it to populate another field next to it saying "No Hazard".

When a user selects NO then I want it to populate another field next to it saying "Hazard".

How can this be done?  I tried the conditional field module and it doesn't seem to be the right solution.

Thanks

You can try the Field Conditional State module: With field conditional state module you can set #state form field attribute based on value selected in other form fields.

Module splits fields into two types:

Control field - field which set #state attribute based on the value from that field
controled field - field for which #state attribute is set based on the value from the control field.

Module supports AND/OR functionality for control fields which means:

AND - all choices must be selected to control the filed (example: field A will be visible when in field B option 1 and option 2 is selected)
OR - any choice will control field (example: field A will be visible when in field B option 1 or option 2 is selected).


What operation should I use to write node's information in an email when the node is saved? I am using hook_nodeapi() to display the node's information in an email when the user clicks on the "Save" button. I tried writing code for the "presave" operation, but that didn't work the way I wanted. I tried using a query to pull out the node data, but the data wasn't in the database until after the "postsave" operation.

Which $op is the right one for me? I tried 'insert' as well, and that didn't work.

Thanks to a bit of a to-and-fro in your other questions (this one and this one) I think I know what the problem is.

Without going into great detail, the content module (CCK) also implements hook_nodeapi(), in order to commit the field data to the database. What's currently happening is that the hooks implemented by your module are being called before the hooks for the content module, which means at the time your implementation of hook_nodeapi() is run, CCK's implementation has not run; hence the data not being found in the database.

In my experience unless you explicitly set the weight of certain modules, they're ordered by name alphabetically, and as your module name begins with 'a' it does make sense that this would happen.

To get around it you just need to increase the 'weight' of your module in the system. Have a look at How to update a module's weight for more information but essentially you want to run a query like this against your database:

db_query("UPDATE {system} SET weight = 100 WHERE name = 'yourmodulename'");

After that clear Drupal's caches and you should see things starting to behave a bit differently.


How do I make ugly URLs such as "/index.php?main_page=about_us"? I'm converting a Zen Cart site to Ubercart and need to keep Zen Cart’s ugly URLs for SEO purposes. The site is top ranking on Google Search for their keywords and I’ve been advised that changing the URLs to something cleaner could potentially hurt rankings.

I wonder if there is any way to give a node a URL like http://example.com/index.php?main_page=about_us?

By default Drupal encodes special characters, so it tries to make my URL /index.php%3Fmain_page%3Dabout_us and I also get a 403 error.

My advice would be to keep Drupal's URL handling as is and simply configure a set of redirects with code 301 in your .htaccess.
That way your URLs will maintain their google ranking.

A useful quote:

  "Be aware that when moving a page from one URL to another, the search
  engines will take some time to discover the 301, recognize it, and
  credit the new page with the rankings and trust of its predecessor.
  This process can be lengthier if search engine spiders rarely visit
  the given web page, or if the new URL doesn't properly resolve."

This is an excerpt from https://moz.com/learn/seo/redirection, I would recommend reading that whole article, it's quite useful.

And an example of such a redirect:

RewriteCond %{QUERY_STRING}     ^main_page=about_us$     [NC]
RewriteRule ^.*$             /node/1234     [NC,L,R=301]

Hope this helps!


Get taxonomy field value in forum-list.html.twig I am customizing the appearance of the forums.
I added all my forums and container. Additionally, I added a custom taxonomy field I need to show for each forum category.

How can I show the custom taxonomy field in forum-list.html.twig?
I know how to show content fields from nodes in node.html.twig, but how do I show custom taxonomy fields in forum-list.html.twig?

Your question is very vague.
I suggest setting up xdebug (https://www.drupal.org/docs/develop/development-tools/xdebug-debugger) then using the function devel_breakpoint() to be able to see how to reach the values/fields of your entity.
If your taxonomy is attached to your topic, I'm assuming that the solution will be something like forum.taxonomy_field.value.
If your taxonomy is not attached to your topic, you should have a look to preprocess your topic to add the missing data by using template_preprocess_forum_list()   I guess?
Here is the list of all preprocess hook, maybe another one with forum might do the trick: https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Render%21theme.api.php/function/implementations/hook_preprocess_HOOK/8.2.x


How can I use HTML in a field of paragraphs module I am using the paragraphs module. And I add a text field (plain,long). In this field I want to add e.g.

After rendering the output in browser is in quotation marks like this

""

How can I avoid it?

Make it a body field, and then edit the source - put your HTML in there


Add text to user login page I'm attempting to add text to user login page, with general info about accounts rather than only displaying the login form.

I have a page.html.twig template like so

{{ page.header }}

This is my page template

{{page.content}}
{{ page.footer }}

I then can create content in page--user--login.html.twig like so.

{{ page.header }}

This is my page template

Enter your login information here

{{page.content}}
{{ loginform }}
{{ page.footer }}

But is there anyway to just add text to the login form without recreating page.html.twig. Since it would just be a copy I'd rather consolidate everything so any change wouldn't have to be made to both. Is there a template I could use like node--user--login.html.twig. So that the content would use page.html.twig and use the page.content block?

I understand that you can make changes to the form using a theme_form_alter hook but I'm not sure how to add html to the form from there. I can only change things like placeholder text, and submit values.

You can do this very simple way using hook_form_FORM_ID_alter.

Paste following code in your themename.theme file and clear the cache

function YourThemeName_form_user_login_form_alter(&$form, FormStateInterface $form_state) {
    $form['newline'] = array(
      '#type' => 'markup',
      '#markup' => t('
Enter your login information here!
'),
      '#weight' => -10,
    );
}

Image output:

Before:

After:

This way you do not need to worry about anything, it will only show in Login page.


Drupal: on node save, redirect user to homepage? How can I redirect the user to the home page (or another drupal page) on node save instead of them seeing the saved content?

The Rules module will help you.

If you found a problem with using this module and you want to know how to do this technically, just tell me and I will explain in detail.


Custom Markup to item in views I created a view that displays my user profile picture.  I created a template for this view using 'views-view-fields--name.tpl.php.  This is the output I get.

What I want to do is add a link to my image, like so:

 ......

But it keeps adding that line to just before the "user-picture" div, and I want it after it.  Is there any way to achieve this? Custom templates seems to not do the trick.

You can do this in the views ui.

Create a custom field
Hide the display of the image field
Use tokens provided to add image field output to your custom field

Example:

[image_field]

UPDATE

Also ensure the style options are set to none on the image field so you don't get any div wrappers.


Integrate facebook into rating logic I want to build a functionality on my website that allows you to +1 (add a vote) a post.
I want to integrate this functionality with facebook, so that 1 single vote is allowed per facebook user (without creating an account for that user on my site -- if it is possible).

Please point me in the right direction for this.
I'm looking for any solution that is a Drupal Best Practice, or any idea that you have on the subject and how it can be achieved.

Right now I think I will go with Fivestar module, but I'm not sure how to integrate this.

You are looking for Entity External Rating module. Check the site using this module.

  This module can be used to implement a rating system based on external
  sources. What that means is that the actual rating, voting or whatever
  action, happens on an external application (for example on Facebook),
  and the results are fetched into your system. By itself, this module
  is intended for developers to use it like an API.

One key question would be why to use this module and not the Voting API with the Fivestar module for example. Here are the most important reasons:

The main advantage of this module is that your system does not handle now the actual rating process. This now happens on external systems.
You can have many sources from which your rating is fetched. The results will be aggregated from all of them.
If you have a site with mostly anonymous traffic, it will be very easy for your users to rate content through Facebook or Twitter.


Flexslider views messing up my other images styles Installed flexslider and the flexslider views module.
But when in enable them my other image styles don't work no more.
In my view everything (image style) is ok.
But on my page it doesn't work.
www.thewizard.eu
Someone advise?

Thanks,
Tom

You need to remove a flexslider css style:

.flexslider .slides img {
display: block;
width: 100%; }

The width setting is messing your brands up.


Create a custom form in Drupal CMS for editors I need to create a form for our Drupal Editors. The form must allow them to add records to database.

I see next steps to do:

I add action in place I want.
User clicks on action and modal form appears (that's I do not know how to do in Drupal way).
User submits form and record is added to database.
If possible refresh current page so user can see new record.

Could somebody please point me in the right direction?

So far I'm looking on: CTools Auto-modal and CTools Auto-modal Admin Interface. However I'm not sure if that is right direction.

Maybe just use a regular content type, add whatever fields you'd need, and let your Drupal editors edit regular nodes.

As a variation, use the ECK module so that you have custom entities (instead of nodes). And then let Drupal take care of storing the data in an appropriate table in the database. With such approach you get all sorts of extra facilities (integrations with other modules), out-of-the-Drupal-box ... Views, Rules, Group, Flag, you name it.

Another approach could be like I described in my answer to "How to implement a multi step approval with webforms/entityforms based on form components?".


How can I assign an icon to users depending on their gender? I'd like comments on my website to look like this:

Every comment has to be preceded by an image, depending on the gender of the user who wrote the comment. Users can choose Male/Female as their gender when they register, so the icon can't be changed: it's only related to the gender. How can I achieve this?

Create a vocab as gender and add two taxonomies to it as male and female. To the gender vocab add image field and while creating the male and female taxonomy term add the respective images.

Now add the term reference file to user entity and keep it as stele list.

In your custom module hook_user_presave and get the value for the taxonomy field.when you know the selected taxonomy you can load the taxonomy to get the image field fid associated with it assign the fid to $user->picture.

Now everywhere image will load as per the gender selected.