How to create a chart about the number of nodes by content type? I am trying to make a chart with 1 column for each content type. Values are the addition of each total.

I have created a view (using the Views module) with two content-type fields. One of them is configured to Count Distinct in aggregation.

In a graph, however, only one column named Type appears, and not a column for each content type.

I am trying both with Views Dataviz and Google Charts Tools.

Any help on this would be appreciated.

Let me try to answer this if I am getting you clearly. There are several contributed modules available for creating charts in Drupal. Refer to the comparison of charting modules for more details. You are not specifying the Drupal version, let me assume a use case for 7. Also know that there are various types of licenses (commercial, open source, ...) for each of the charting libraries, so your choices may be limited by your license needs (each module typically requires at least 1 such charting library as its charting engine).

The solution I am giving has a lot to do with the Google Charts API implemented via the Google Chart Tools module. The module provides a simple API that allows you to build your graphs on that.The module ships with an example that gives a nice pointer to writing your own custom module.

A simple module to get the content types.

function example_block_info(){
  //lets display this in a block. You can do a page if you like.
  $blocks['example_chart'] = array(
     'info' => t('Example Line Bar Showing Content Types'),
     'cache' => DRUPAL_CACHE_PER_ROLE //This is a Drupal default.You can set your own.
   );
 return $blocks;
}

function example_block_view($delta = ''){
    //Create a display for the block.
    switch ($delta) {
      case 'example_chart':
       $block['content'] = example_block_contents()
      break;
    }
  return $block;
}

function example_block_contents(){
  //This is a function specific to the block that lets you prepare the content for the chart.
    //Google Chart Tools integration begins here.
    //First empty the array that is to be passed to draw_chart().
    $settings = array();
    //We then populate the array.
    $settings['chart']['Chart for Nodes'] = array(
      //I am using just one content type. You can loop to get the other node types.
      'header' => array('My Node'),
      //This is the array to be presented to draw().
      'rows' => array(array(
                example_node_count(),
               )
           ),
      'chartType' => 'ColumnChart',
      'containerId' => 'example_chart',
      'options' => array(
            'forceIFrame' = FALSE,
            'title' => 'A column chart for nodes',
            'width' => 800,
            'height' => 600
        )
    );
    draw_chart($settings);
    //Return the DIV containing the chart.
    return '

';
}

function example_node_count(){
  //Custom function to count the nodes available.
  //Put to use Entity Field Query.
  $query = new EntityFieldQuery;
  $query
    ->entityCondition('entity_type', 'node')
    ->entityCondition('bundle', 'my_node_type');
    //Count your node type.Introduce a loop to count your other nodes as needed.
    $my_node_type_count = $query->count()->execute();
    return $my_node_type_count;
}

This is just a shell of a working module. Get some education of the charts at Google Visualization API docs. Warning: There might be some typos in there. Just trying to give an alternative.


Is it better for performance to disable unused default core views? I'm seeing 5 views on my site that I'm not using and want to disable to keep things clean and performant, but I worry it could cause a problem somewhere down the road.

The views are:

Frontpage (frontpage)
Recent content (content_recent)
Taxonomy Term (taxonomy_term)
Who's New (who_s_new)
Who's Online (who_s_online)

I have disabled these views and haven't seen any issues. I am not using any of them. Is core expecting these to be enabled? Does disabling these actually improve performance in any way?

I am not using any of them. Is core expecting these to be enabled?

They are just examples and can be disabled if you don't need them.

The taxonomy term view is a bit different because that is the one that provides list of content when clicking on a term, if you disable that then those pages become practically meaningless as all they do is show the term with its fields.

  Does disabling these actually improve performance in any way?

Most likely not a in a measurable way. There are a handful of routes less due to that that don't need to be regenerated on a cache clear but that's a tiny amount of the total routes and it should have no impact on runtime performance.


Cloned site pointing to original site's database - can this cause problems? Can pointing a cloned site to the original site's database cause problems?

I'm running a Drupal 7 site with a MySQL database sitting on a separate server.

I pulled a clone of the site's codebase repository onto a seperate development server, then imported a very recent backup of the database into a fresh database. The site ran correctly, from a different domain.

However, I forgot to update the local.settings.php file, so the cloned DEV site pointed to the PROD database. This file was incorrect for about 16 hours, overnight, and I've since updated it to point to the correct database.

While the DEV sit pointed to PROD, I did not create, edit or delete any content on the DEV site. My only change was to disable 'aggregating CSS/JS files' under performance settings. The CRON would have run many times overnight.

I've since cleared all caches and purged all cached URLs from Varnish, but for political reasons I cannot simply restore an earlier backup of the site.

Could this database crossover cause any problems now or in the future?

The only way this could cause problems would be if the filesystem became out of sync. Since you didn't create, edit, or delete any content, this shouldn't be the case. If you have anything running on a cron hook which creates files you may see 404s in your logs. An example of this would be something like boost or advagg which create cached html/css in the files dir. Even if this is the case however you will be fine once cron has run again from the live codebase.


Limit nodes in views per group I'm using Group field in views. There are several events in one month. How can i limit my events. 2 events should be displayed in every month.

July
Event 1
Event 2
Event 3
Event 4

August
Event 1
Event 2

Thanks.

If you dont want to write custom code you can use the
views limit group module

  This is a basic Views style plugin that allows for a limit on the number of rows displayed within a grouping field.


How to disable CKeditor for a particular node? I want to style the content within a particular node but the CKeditor seems to interfere with that by introducing unnecessary tags.

In Drupal 6 you could disable it by adding the generated id on the node form to the profile settings of ckeditor.

I could find no similar settings in the Drupal 7 version.

Am I missing something here? Is there no similar configuration for Drupal 7?

or should I go with a hook_form_alter?

Any help is appreciated.

You can configure text formats to have different editors with WYSIWYG API, all you need to do is create a new format (like Full HTML) and set it for no editor, then on any node you don't wish to have an editor, simply set the text format to your new custom one.


Delete query is called while updating the value of node Delete query is called while updating the cck field value of node.

After debugging i find following code in

  var/www/drupal-7.40/modules/field/modules/field_sql_storage/field_sql_storage.module

in field_sql_storage_field_storage_write($entity_type, $entity, $op, $fields)

we have following code

// Delete and insert, rather than update, in case a value was added.
if ($op == FIELD_STORAGE_UPDATE) {
  // Delete languages present in the incoming $entity->$field_name.
  // Delete all languages if $entity->$field_name is empty.
  $languages = !empty($entity->$field_name) ? $field_languages : $all_languages;
  if ($languages) {
    db_delete($table_name)
      ->condition('entity_type', $entity_type)
      ->condition('entity_id', $id)
      ->condition('language', $languages, 'IN')
      ->execute();
    db_delete($revision_name)
      ->condition('entity_type', $entity_type)
      ->condition('entity_id', $id)
      ->condition('revision_id', $vid)
      ->condition('language', $languages, 'IN')
      ->execute();
  }
}

May be someone explain why ?
And also can i use update Query instead of delete, insert ?

As the comment at the top states: Delete and insert, rather than update, in case a value was added.

So to make sure all old data is cleared, the records are deleted and re-added with new data (as you can see on line 481: $query = db_insert($table_name)->fields($columns);.

Of course you could use the update query, but this query would need to contain all fields because it is impossible to know which fields are added, modified or deleted. A simple delete and add solves that problem.


Can't insert data to database on form submit I am trying to insert some datas into database table on form submit like this:

function form_example_submit($form, &$form_state) {

    if ($form_state['values']['select']=='1') $gender = 'male';
    else $gender = 'female';

    db_insert('form_example_table')->fields(array(
      'name'    => $form_state['values']['name'],
      'gender'  => $gender,
      'message' => $form_state['values']['message'],

    ))->execute();

    drupal_set_message("Message is successfully saved");

    return $form;

}

My schema in .install file looks like this:

function form_example_schema() {

    $schema['form_example_table'] = array(
        'description' => 'Table for form_pokus module',
        'fields' => array(
            'id'        => array('type' => 'serial', 'unsigned' => TRUE, 'not null' => TRUE),
            'name'      => array('type' => 'varchar','length' => 30,     'not null' => TRUE, 'default' => ''),
            'gender'    => array('type' => 'varchar','length' => 30,     'not null' => TRUE, 'default' => ''),
            'message'   => array('type' => 'text', 'not null' => TRUE,   'default'  => ''),
            'status'    => array('type' => 'text', 'not null' => FALSE ),
            'created'   => array('type' => 'int',  'not null' => TRUE,   'default'  => 0),
        ),

        'primary key' => array('id'),

    );

    return $schema;
}

But nothing happens on form submit, only page is reloaded. What I am mising?

your schema

<?php
function form_example_schema() {

    $schema['form_example_table'] = array(
        'description' => 'Table for form_pokus module',
        'fields' => array(
            'id'        => array('type' => 'serial', 'unsigned' => TRUE, 'not null' => TRUE),
            'name'      => array('type' => 'varchar','length' => 30,     'not null' => TRUE, 'default' => ''),
            'gender'    => array('type' => 'varchar','length' => 30,     'not null' => TRUE, 'default' => ''),
            'message'   => array('type' => 'text', 'not null' => TRUE,   'default'  => ''),
            'status'    => array('type' => 'text', 'not null' => FALSE ),
            'created'   => array('type' => 'int',  'not null' => TRUE,   'default'  => 0),
        ),

        'primary key' => array('id'),

    );

    return $schema;
}
?>

needs to look like:

function form_example_schema() {

    $schema['form_pokus_table'] = array(
        'description' => 'Table for form_pokus module',
        'fields' => array(
            'id'        => array('type' => 'serial', 'unsigned' => TRUE, 'not null' => TRUE),
            'name'      => array('type' => 'varchar','length' => 30,     'not null' => TRUE, 'default' => ''),
            'gender'    => array('type' => 'varchar','length' => 30,     'not null' => TRUE, 'default' => ''),
            'message'   => array('type' => 'text', 'not null' => TRUE,   'default'  => ''),
            'status'    => array('type' => 'text', 'not null' => FALSE ),
            'created'   => array('type' => 'int',  'not null' => TRUE,   'default'  => 0),
        ),

        'primary key' => array('id'),

    );

    return $schema;
}

you had the wrong table name as the schema index.


Taxonomy shows term ID not term name in Facet API Im trying to facet by taxonomy fields but I see just the ID, not the name of the term, why?

I'm getting this:

3 (76)
4 (35)
176 (7)
167 (6)
177 (5)
168 (4)
5 (2)
163 (1)
7 (1)

and it should be

Casa (76)
Depto (35)
Duplex (7)
...

Any ideas?

in

  admin/config/search/facets/your_facet_name/edit

you must select :

  List item label
 Translate entity label


Taxonomy Term Reference Tree Widget with Other field I am using Drupal 7 Taxonomy Term Reference Tree Widget my requirement is, user should be able to create new term while adding the content. Is it possible in this module? Any patch available?

Please help me.

Thanks,

You might do this with the alternative module Hierarchical select.

Hierarchical select:

  Hierarchical Select has the ability to save the entire lineage of a selection or only the "deepest" selection. You can configure it to force the user to make a selection as deep as possible in the tree, or allow the user to select an item anywhere in the tree. Levels can be labeled, you can configure limit the number of items that can be selected, configure a title for the dropbox, choose a site-wide animation delay, and so on. You can even create new items and levels through Hierarchical Select!


One exposed filter with different values in one view I've searched a lot for this one with no luck.
My problem is the following:

I have an exposed filter of brands (adidas, nike, etc). It is displayed as a block on the home page.
while entering the brand and click apply, it displays a page containing two content types mall and store.

the store content type contains a term reference field brand.
As for the mall content type, it contains entity reference stores with term reference field brand in them.

If i add a relationship in the views for the referenced entity and enable the relationship on the exposed filter field brand, it will display the mall content type only. if i remove the relationship it will display the store content type only.

How can I have one exposed filter block to display both the malls and the stores?

I appreciate any help given.

I'm using drupal 7.

you can use views autocomplete filters, add all fields you wish in the view, including the ones with a relationship (can be: contentypes, commerce products and commerce line itmes with propper relationships), then on add an exposed filter choose: Global: Combine fields filter, and on filter settings select all fields you wish to filter on, like the image below. This wokrs on D7 & D8. Enjoy.


How to get "User ID From URL" with contextual filter in Pfofile2 page I'm using Drupal7.

I wanted to display some fields from user account in profile2 page by using Views. I tried to do this by using views block and views_embed_view() coded in profile2--ProfileType.tpl.php for profile2 page.

So, I created a view and set contextual filter like below.

-"USER:UID"
-the default value is "User ID From URL"

But that doesn't display View in profile2 page even though the URL is "Mydomain.com/profile-My_Profile_Type/User_ID". On the other hand, that View works in the user account page. So, this means that it may be because contextual filter of "User ID From URL" doesn't work in the profile2 page even though its URL has User ID. I changed the contextual filter from "USER:UID" to "(Profile) Profile: User uid", but it doesn't work either...

Can anybody give me the advice how to make it work?

Thank you

If the url schema is alway the same, you can use the default value "Raw value from url" instead of "User Id from URL" and set the 'path component' in your example to '3' to get the user id.


Render a node as plain text for sending by mail I like to use a node as mail body in Drupal 8. I have written a simple module which works fine except for output formatting:

function foo_notification_node_insert($node) {
  $type = $node->getType();
  if ($type === 'foo') {
    $to = 'test@examples.com';

    // passed to hook_mail
    $params = array(
      "node" => $node
    );

    \Drupal::service('plugin.manager.mail')->mail(
      'foo_notification',
      'notice',
      $to,
      'de',
      $params
    );
  }

function foo_notification_mail($key, &$message, $params) {
    $node = $params["node"];

    // subject
    $message['subject'] = "New node: " . $node->getTitle();

    // render body
    $view_builder = \Drupal::entityTypeManager()->getViewBuilder($node->getEntityTypeId());
    $view = $view_builder->view($node, 'default', 'de');
    $message['body'][] = render($view);
}

If I understood correct $view_builder->view($node, 'default', 'de'); returns a render array. This one is rendered to HTML by render($view);. Drupal mail service converts HTML in message body to plain text. And that looks ugly.

Rendered mail body looks like:

---------------- My node title -------------------------------------
first field label
               first field value

      second field label
                second field value

      third field label
                third field value contains a longer text which break
at some point and is continued like this. Just for demonstration a
few more lines.
This ist how it looks like if it contains a line break. It's ugly.

The node has multiple fields and I like to use same view for representation on page (HTML) and in mail (plain text) - especially the order and formatting of node fields.

So what's the correct solution?

The render engine of Drupal cannot render Node as plain text (at least natively).

I think you have to choice between send the mail in HTML format with is very easy by changing the $message['header'] of your mail or installing Mail system with Swift Mailer (very easy too). Or you have to parse the field value yourself by escaping HTML markups (bad way IMO).

I strongly recommend you to send your mail in HTML format if you want to enjoy the benefits of the drupal render engine, which is made for generate HTML output.


Adding Where clause in Views Query using a custom filter Handler How can I add a where clause in custom filter handler for views query.

I need to add where clause to alter views query using custom filter handler.

My code in custom filter:

class fee_management_handler_filter_payment_status extends views_handler_filter_many_to_one {
  function get_value_options() {
    $this->value_options = array('1' => 'Paid', '0' => 'Unpaid');
  }

    /**
        * Called to implement a payment status.
    */
    function query() {

        if filter = unpaid or 0

        view conditions  + = ' AND pid IS NULL';

        parent::query();
    }
}

function query() {
        parent::ensure_my_table(); #$this->ensure_my_table();
        $alias = $this->table . '_' . $this->view->base_table;
        $operator = ($this->value['0']) ? 'IS NOT' : 'IS';
    $this->query->add_where(0, $alias . '.pid', NULL, $operator . ' NULL');
        #debug($this->query);
        parent::query();
    }


Display decimal field without right side zeros I have a decimal field for length (cm) with precision 2. If I enter number without '.' it should display as it is only. For example If I enter 23 it should display 23 only not 23.00. If I enter 23.14 it should display 23.14. How can I do that? Am I missing any thing here?

Sorry, editing my question:

It should display the numbers like following (in Full node view, Views, Forms and wherever it appears)

If any one entered 93 it should be displayed 93 only not 93.00 (cause of the scale 2).

If entered 93.40 it should be displayed 93.4

If entered 93.14 it should be displayed as 93.14 only

I know that the value will be saved with scale 2(As given in Fields Form) in the database. But the value should be displayed as a whole number etc

You can format the field from Manage Display as follow:

Go to manage display of the respective entity
Click on settings button of the field to do formatting
Change the value of Scale dropdown to zero
Click update
Click Save button at bottom


how to make url string absolute? In order to get entity link, I'm using:

$entity->getTranslation($language)->url();

So it gives me : /en/node/21

But I want this url to be absolute.

How to pass $options = array('absolute' => TRUE); in above node url?

The options are the second parameter in url(), then you also have to pass the first parameter, which is by default 'canonical':

$entity->getTranslation($language)->url('canonical', ['absolute' => TRUE]);

url() is deprecated, so better use toUrl():

$entity->getTranslation($language)->toUrl('canonical', ['absolute' => TRUE])->toString();


Need to change the subdomain URL structure - D7 Need to change the subdomain URL structure from:

sub1.example.com
sub2.example.com

To:

www.example.com/sub1
www.example.com/sub2

Is there any module to do this in Drupal 7

If there is no other module in the text I need to rewrite the module for D7 version which is available in D6 in the below link. But before doing that I would like to confirm is there any modules ?

Below text is taken from the link:

  Of course this could quite easily be achieved using a redirect /
  RewriteRule in an htaccess file – but in this case we wanted to to
  achieve the URL re-routing without actually using a redirect. In other
  words, the URL in the browser’s address bar should always show URLs
  like this

I believe you will still need some mod_rewrite redirection rules (RewriteRule), but only after the fact; it can be used used to ensure users accessing subX.example.com get redirected appropriately to the new content URL instead of mod_rewrite being the solution to the problem (which, as you mentioned, is not what you wanted).

Have you tried using pathauto to set a URL pattern and then using views_bulk_operations to mass update node aliases? I recall VBO will overwrite any existing alias, but if it doesn't simply make a database backup for good measure and then drop your existing node path aliases from the database directly as they will be regenerated anyways using VBO.

If you need to create redirects from the old node aliases to the new ones (ignoring the hostname component), the redirect module will automatically create 301s.

Here is a quick guide on pathauto + VBO: http://drupal.org/node/1326928


How to add a single taxonomy term as a body class in Drupal 8 I'd like to add a single taxonomy term into the body tag as a class in drupal 8 - so I page styles can be controlled easily.
I have tried (path and ID as class in body How can I dynamically add URL or taxonomy to body class and https://www.drupal.org/node/2634364) which only get me part way there, taxonomy term would provide a future proofed solution.

i found a solution which worked perfectly for me. Add this in your .theme file and replace mytheme_preprocess_html by your theme name and field_section by name of your taxonomy field.

[https://gist.github.com/awasson/d8ef8d7c1b64b2ccb8a0][1]

<?php

    /**
     * Prepares variables for the html.html.twig template.
     */

    use Drupal\taxonomy\Entity\Term;
    use Drupal\Component\Utility\Html;

    function mytheme_preprocess_html(&$variables) {

      if ($node = \Drupal::routeMatch()->getParameter('node')) {

        /**
         * Get the term id from the 'field_section' taxonomy field.
         * If greater than zero, load the term and acquire the name value
         * as a css safe value.
        */
        if($node->hasField('field_section')) {
          $tid = $node->get('field_section')->target_id;
          if($tid > 0) {
            $term_object = Term::load($tid);
            $variables['attributes']['class'][] = 'terms--' . Html::getClass($term_object->get('name')->value);
          }
        }

        /**
         * Get the node id from the node object.
         * If greater than zero, add the node id to body classes
        */
        $nid = $node->get('nid')->value;
        if($nid > 0) {
          $variables['attributes']['class'][] = 'page--node-' . $nid;
        }
      }

    }


Does $element['#title'] need to be escaped with check_plain()? I see (with grep) that the value of $element['#title'] in a render element is sometimes sanitized with check_plain(), and sometimes printed unfiltered.

Which one is correct? Is the value considered safe to print? Or does it depend on the theme hook?

Examples from core:

modules/field/field.form.inc
314:        'data' => '<label>' . t('!title !required', array('!title' => $element['#title'], '!required' => $required)) . "</label>",

(notice the "!" in the placeholder, this means that format_string() will not escape the placeholder value)

modules/field/field.module
1052:  $variables['label'] = $variables['label_hidden'] ? NULL : check_plain($element['#title']);

This question applies in both ways:

When setting $element['#title'] in a render element.
When printing the value of $element['#title'].
When printing a $variables['title'] value that was extracted from a render element property.

Note: Very often the $element['#title'] property comes directly from a t() call.

It's user input and should be considered unsafe; you should always sanitise it.

For the specific example you've given where it isn't, the title is already sanitised before it's passed to the theme function containing the t() call. This happens in field_multiple_value_form()

$title = check_plain($instance['label']);

...

$element = array(
  ...
  '#title' => $multiple ? '' : $title,
  ...
);

As an aside, if you ever did need to preserve HTML in the title for whatever reason, you could consider using filter_xss() instead.


How is a variable passed to theme_hook (theme_item_list, FacetAPI) Problem

I'm trying to register a new theme function based off theme_item_list to alter the display of a facet.

Theme_item_list is passed in an array $variables. Crucially I can't work out how the facetAPI passes the variables needed for theme_item_list to render a list. It sets up the array in the execute method of FacetapiWidgetLinks and somehow successfully passes this to theme_item_list but I can't get my own theme function to receive anything.

How does theme_item_list receive it's $variables array?

More Information

Code altered thanks to kiamlaluno

I currently have the following code in my module:

function my_module_theme($variables) {
  return array(
    'item_list_aggregate' => array('variables' => array(
      'items' => array(),
      'attributes' => array(),
      'title' => NULL,
      'type' => 'ul',
  )));
}

//this is correctly called but $variables is empty
function theme_item_list_aggregate($variables) {
  $items = $variables['items'];
  $title = $variables['title'];
  $type = $variables['type'];
  $attributes = $variables['attributes'];
  ...

#items and #attributes values are set in the execute method below.

They are correctly passed to theme_item_list because I can't get them to pass to my theme function, theme_item_list_aggregate, the $variables variable in my_module_theme is empty.

class FacetapiWidgetLinks extends FacetapiWidget {

...

public function execute() {
    $element = &$this->build[$this->facet['field alias']];
    $this->setThemeHooks($element);

    // Here I call my own theme function. It's identical
    // to theme_item_list at the moment but my own theme function
    // never gets passed the $element array.
    if(strpos($this->facet['field alias'],"aggregation") != FALSE) {
      $element = array(
        '#theme' => 'item_list_aggregate',
        '#items' => $this->buildListItems($element),
        '#attributes' => $this->build['#attributes'],
      );
    } else {
      $element = array(
        '#theme' => 'item_list',
        '#items' => $this->buildListItems($element),
        '#attributes' => $this->build['#attributes'],
      );
    }
  }

...

It is not necessary to create a new theme function. You could use the existing theme_item_list and extend it with double underscore. Rename item_list_aggregate to item_list__aggregate in FacetapiWidgetLinks::execute. And implement theme_item_list and theme_item_list__aggregate in your theme.

Look at node_title_list in core, this function uses the same pattern.


Commerce Shipping - arbitrary calculations I'm using Drupal Commerce to create a simple shop and I wish to add shipping cost calculations based on the weight (in grams) of items in the cart. I have set a weight field on each product so I can work out what the total is, but the client has specified arbitrary prices depending on weight and destination:

UK
weight = 0 price = 0.00
weight < 250 price = 1.00
weight < 500 price = 1.50
weight < 750 price = 2.00
weight < 1000 price = 3.00
weight < 2000 price = 5.00

Europe
weight = 0 price = 0.00
weight < 250 price = 2.50
weight < 500 price = 4.00
weight < 750 price = 5.00
weight < 1000 price = 6.25
weight < 1250 price = 7.50
weight < 1500 price = 8.75
weight < 1750 price = 10.00
weight < 2000 price = 11.25

Other
weight = 0 price = 0.00
weight < 250 price = 4.00
weight < 500 price = 6.50
weight < 750 price = 8.75
weight < 1000 price = 11.25
weight < 1250 price = 13.75
weight < 1500 price = 16.25
weight < 1750 price = 18.75
weight < 2000 price = 21.25

Would I need to add a shipping calculation rule for each possible scenario or is there a way to configure rules to look up a table?

I found a module that does exactly what I want: Commerce Shipping Weight Tariff.
I set up three services, one for each destination, and used rules based on the shipping address to work out which service to use. Then I added the weight tariffs for each service.


About Drupal interact with Android Requirements:~

Android app post json data to a certain url.
Drupal can  receive the json data and then verify the json data and return result data in json format.

My question is on receive Json data and return Json data steps. What module or api can I use?

It would be greater help if you can share a sample.

Services module is what you are looking for. It supports json data. More about the module:

  A standardized solution of integrating external applications with Drupal. Service callbacks may be used with multiple interfaces like REST, XMLRPC, JSON, JSON-RPC, SOAP, AMF, etc. This allows a Drupal site to provide web services via multiple interfaces while using the same callback code.

It also has an extensive documentation.


Adding a form to user profile? I would like to add a form to the user account page, is there a specific way of doing this?

I guess this leads me to a large question: how can you embed forms in pages? I understanding using hook_menu & the drupal_get_form callback. But this creates a new page, what about adding forms to an already existing page.

I have a feeling the answer is here: https://api.drupal.org/comment/6679#comment-6679, but I can't seem to understand it. Anyone have any good suggestions or tutorials....

You can add user forms by creating a render array for the Form API and print render($form) in a custom template, but I would just use the Webforms module and include all elements in a Panel or View.


Check if a node exist where field_a = Sessionvalue && field_b=arg1 Hello I need a an if else statment to check if a node with 2 given field values exist.(1 value from a Session and 1 from an Url argument)

I dont need to load the node I only want to check if it exist.

thanks for your help.

If you want to get value from entity without loading the entity object. You can use EntityFieldQuery

Example:

$query = new EntityFieldQuery();

$query->entityCondition('entity_id', 1)
      ->fieldCondition('field_custom_field', 'value', '', '!=')
      ->addMetaData('account', user_load(1)); // Run the query as user 1.

$result = $query->execute();

if (!empty($result['node'])) {
  // field value exists!.
}


How can you show taxonomy child terms on the parent term page? I am trying to figure out if there is a way to modify the default taxonomy view so it shows nodes tagged with that particular term (already done) plus all children of the taxonomy term you are viewing.

I have seen solutions for D7 but nothing for D8.

One way of doing this is with the use of https://www.drupal.org/project/eva which lets you attach any entity to any other entity

Just for demonstration I have setup

parent 1
  child 1.1
  child 1.2
parent 2
  child 2.1
  child 2.2

install and enable eva
create a taxonomy terms view called children with no block or page display

Then add an EVA views display from the dropdown
You will need to set a contextual filter parent term with following settings

Hide when value not available
specify validation criteria
   taxonomy term id:
      [NAME-OF-VOCABULARY]
   hide view

and on entity content settings set entity type: taxonomy term and bundle: [vocabulary name]

I had to clear cache so it does not hurt to do it and visit any of the taxonomy parent pages you should see the children terms

you can change where the children are displayed at your taxonomy term display settings page


how to fetch webform records from table by using drupal db_select i want to display the output in the following format by using the following source code but the following source code shows error

  Notice: Undefined offset: 0 in eval() (line 20 of /....----modules/php/php.module(80) : eval()'d code).

<?php
include_once(drupal_get_path('module', 'webform').'/includes/webform.submissions.inc');
$query = db_select('webform_submitted_data', 'u');
$query->fields('u', array('sid','nid','data'));
$query->condition('nid','1','=');
$results =$query->execute();

echo "
";
echo "
";
echo "  Profile Photo 	";
echo " Faculty  Name and Department  	";
echo  "
";

if($record = $results->fetchAssoc())
{
$sid = $record['sid'];
$nid = $record['nid'];
$submission = webform_get_submission($nid,$sid);
echo "
";
$val = $submission->data[15][0];

$query1 = db_select('file_managed', 'u');
$query1->fields('u', array('fid','filename'));
$query1->condition('fid',$val,'=');
$results1 =$query1->execute();

if ($record1 = $results1->fetchAssoc())
{
$path = $record1['filename'];

echo "   	";
}
echo "" .  "Name : " . $submission->data[1][0] . "
" .  " Designation : " . $submission->data[2][0] . "
" . " Department : " . $submission->data[3][0] ."
" . " E-mail : " . $submission->data[4][0] .  "	";
echo "
";
}
echo "
";

?>

Just as it says, the error is in the line

$val = $submission->data[15][0];

so the variable $submission->data[15] does not contain a value [0]. Most likely the array is empty.

Of course, it's probably a bad idea to go to the database yourself, rather than using Webforms API functions. A little searching can get you started.


How to create a folder after clicking on a button? I got a requirement like this: In the admin page there should be one create folder button, user can create a new folders as per his wish. How can I achieve this programaticaly.
Till now I created a admin page there one button is also coming, but I am not getting how to proceed further.So please give some suggestions, thanks in advance.
 Below code I have tried.

  $form['create_folder'] = array(
    '#type' => 'submit',
    '#value' => t('Create folder'),
    '#submit' => 'custom_submit',
  );
function custom_submit($form, &$form_state){
  $new_folder = 'public://newfolder/';
  file_prepare_directory($new_folder, FILE_CREATE_DIRECTORY);
}

When I click on the submit button I got this warning Warning: Invalid argument supplied for foreach() in form_execute_handlers() (line 1507 of C:\xampp\htdocs\drupaltest\includes\form.inc).

The #submit property takes an array of function names rather than a single string:

$form['create_folder'] = array(
  '#type' => 'submit',
  '#value' => t('Create folder'),
  '#submit' => array('custom_submit'),
);


eCommerce system with simple order form I need a food order system to embed in my drupal 7 website.
I added the screen shot of the design here:

I don't want a full eCommerce system.User can select items and the items will be listed in the order list.They can edit the no of items from remove items form the order list.After send an order the order will be stored in db and the site admin can view it on the admin part.From he can process it manually.There is no payment system for it and this is only to track the order and deliver it manually.

Can you please suggest me better way to accomplish it.

thanks in advance.

I had to do something similar to this in the past, where the website client wanted users to be able to mark items as favorites, and then email that list of favorites to the client for pricing and further information. Rather than building a whole e-commerce setup, I used webform and webform view.

Here is the basic setup:

Create 'food item' content type or whatever will be most appropriate for each of your food items
Create a view that displays the food item nodes.
Create a webform that collects user information (such as contact information when submitting an order
Embed your food item view in that webform using the webform view module.

When people then fill out the form, they can select which 'food item' nodes they, want, the quantity, or any other custommizations that you can create using the webform (special requests, delivery method, anything you'd like). They will also enter in any relevant contact information and send it to you as a standard webform.

Webform view has great documentation. It can be a little confusing the first time you try to use it though, so I suggest you follow exactly the documentation in webform view to get an idea for how this module works, and then modify it accordingly for your food item view.

I liked this method too as then the food items are their own content type, so if you do want to do something with e-commerce for real in the future, you should be able to migrate those nodes to products for something like drupal commerce.


How to use dd(debug_backtrace()); for an error debugging? I have this exact error on my site.
I am trying to troubleshoot the error using dd(debug_backtrace()); through the Devel module as is described on the link above.
Being the noob on developing I can't figure out how to print the output in a drupal_debug.txt file under the tmp folder in the root of my Drupal Installation (As is described in the in the link above).
I have tried dd(debug_backtrace()); but I don't see any error file being created so I also tried  dd(debug_backtrace('drupal_debug.txt')); but I get the error:

Warning: file_put_contents(): Only 0 of 1 bytes written, possibly out of free disk space in drupal_debug() (line 1793 of  /home/bigcypru/public_html/sites/all/modules/devel/devel.module).
Devel was unable to write to /tmp/drupal_debug.txt.

I created the file manually and set 777 permissions to be sure is writable but still get the same error and I am sure I have enough space in my hosting plan.

You can run:

dd(debug_backtrace());

which prints the output to drupal_debug.txt file by default in your temporary folder which can be found in your tmp folder (See: Where Drupal creates temporary files?). You can specify different file, but in Drupal settings related to file system.

The call to dd(debug_backtrace('drupal_debug.txt')); is invalid, since debug_backtrace() accepts int $options, not the file.

Regarding this warning:

  Only 0 of 1 bytes written, possibly out of free disk space in drupal_debug(). Devel was unable to write to /tmp/drupal_debug.txt.

it says you're likely to be out of free disk space on your hard drive. So you should remove this file from your temporary folder at /tmp, then try again.

To make it more light, use the following version:

dd(debug_backtrace(FALSE, 5));

which won't populate all objects (FALSE) and limit number of stack frames returned to 5.

If your function is called too many times, try adding die() or exit(); to avoid multiple calls.

You can also use the following one-liner:

array_walk(debug_backtrace(),create_function('$a,$b','print "<pre>{$a[\'function\']}()(".basename($a[\'file\']).":{$a[\'line\']});</pre>\\n";'));

which will print even more minimalized version of the backtrace to avoid out-of-space issues.


How to check if is anonymous user's first visit to site when using varnish If one has a Drupal 7 site which uses varnish for caching, is there some method which would enable one to serve a different version of front-page if it is first time the anonymous user has visited the site?

As I understand it, varnish caching will not work if a session variable is used. Is there some way of doing this using client side cookies?

The varnish caching will not work if you use cookies : http://systemsarchitect.net/2013/07/08/reading-php-session-from-varnish-cache/


Search index as custom view for taxonomy term with hierarchy. Showing all children results in term parent in taxonomy menu Ok so title is pretty epic, but it goes like this:
Key elements: views, taxonomy_menu, taxonomy, search api, facets.

I created vocabulary "Products" (Drupal Commerce but I don't think it's important), and there term - "Chemistry" - which should be a root of tree of other more specific terms. I added some products. Next I enabled Taxonomy Menu and created a menu, so far so good, but I wanted to use search api, so I created a view of my search index with path:

  /taxonomy/term/%

That way I wanted to override view of my taxonomy, and be able to have facets in it. And it perfectly displays indexed products of terms that have them, but it fails to display all products of CHILDREN terms. So if I have my term "Chemistry" - after clicking it - I would like to be able to see every product of its children terms. I cannot see how can I do this with current approach, as it seems that I doesn't have contextual filters for that (as my view is displaying search index).

What can I do?

If I'm understanding correctly what you're asking, here are some tips.

Under your defined search index, go to Fields. If you have "Products" taxonomy defined, uncheck the taxonomy term, then go to the bottom and open "Add Related Fields" and add "Products", then save changes. When it reloads, you'll now have more taxonomy options. Check "Products >> All parent terms". You should now have additional facets for parent/child terms.

Use in conjunction with Facet API Pretty Paths for even more powerful usage. Take a look at one of my other response about how to use that.


Running an immutable setup in production I'm looking into using Docker to streamline my Drupal development workflow. One approach would be to locally create a Docker image for my Drupal installation (not the database, just the Drupal files default found under /var/www/html), and deploy that image to production.

This approach would imply that all changes to the Drupal installation, i.e. all changes to anything under /var/www/html, would be considered immutable or read-only in production. Any changes here would be gone when the next deployment comes along.

I assume the content created by our content creators logged into our production server, is stored in the database, not in the Drupal installation itself.

My question is: Is there any reason why the Docker installation (i.e. files under /var/www/html) would need to be changed when deploying to production, or can these files remain consistent across environments (dev, test, prod)?

Note that I'm quite new to Drupal.

The file containing the credentials for accessing the database, and other site configurations (e.g. the proxy settings, the trusted domains), is inside the server document root (for example, sites/default/settings.php). The answer to Is there any reason for which the content of the server document root would need to be changed when deploying to production? is then yes.

Add to this the fact that the directory for the public files (e.g. the uploaded images attached to nodes) is by default sites/default/files, you have a reason more to preserve one or more directories under the server document root directory in the production environment.


Adding "Create New Node" link in views pages SO I have two content types, a "Candidate" and a "Job Opening". "Candidate" has an Entity Reference field that points to a Job Opening. I've currently got separate views for both, but on the "Job Opening" view I'd like to have a field that users can click to apply for a job, which would ideally create a new Candidate node with the Job Opening ER field pre-filled so users don't have to fill that in.

I tried adding a Custom Text field containing

Apply Now!

but I just get an "object not found" error when I click on it.

Is there any way to accomplish this be it with existing modules or built-in stuff, or am I gonna have to dive in and start coding?

Edit: So I've managed to get half of what I want. Turns out because my installation is at "/localhost/drupal", then my link needed to be

Apply Now!

So now I just need to find out how to pass a reference to the job opening its from and I'm golden.

It's possible without writing any PHP etc. and you'll need one of the modules mentioned Entityreference prepopulate, Prepopulate, etc.

Add Global: Custom text to your fields, in the Text field enter Apply Now!
Under Rewrite results, check Output this field as a link
In the Link path field enter node/add/candidate (this will get passed through the l() function and correctly deal with subfolders, etc.)
Add Global: Unfiltered text to your header/footer, etc. in the Text field enter [nothing], check Display even if view has no result and check Use replacement tokens from the first row
Test this is working correctly and Exclude from display the Global: Custom text in your fields
Play around with the Link path field to correctly pass the correct variables so your fields are populated correctly - this will probably require trial and error to get this correct which is why this is the last step.


POST method returns 415 Trying to create a node page through web-service.But returns 415 Unsupported media type

This is how I have done

Here is some example raw data you should be sending (don't send it as form data):

{
  "type":[{"target_id":"article"}],
  "title":[{"value":"Hello World"}]
}

You do not need to send the Accept header, because that no longer matters because of the _format=json query string. And in this case, when successful, it will return a 201 so you can disregard the _format query string.

The POST to ?q=entity/node is correct, but don't forget to send an X-CSRF-Token header with a value that can be retrieved here: ?q=rest/session/token


How do I make a form field go back invisble after I uncheck a radio button? I'm currently building a form where the goal is that the administrator will have to choose between 3 radio buttons. If one click on any of the radios, a specific field shows up (There are 3 fields set as "invisible"). My issue is that, I have no problem making these fields show up, but they don't disappear if I select something else.

Here is my code:

function walk_handler_form_alter (&$form, FormStateInterface &$form_state, $form_id)
{
  $form['field_prestation_walk']['#states'] = [
  'visible' => [
    ':input[name="field_prestation_type"][value="walk"]' => [
        'checked' => true
      ]
    ]
  ];
}

So, as I said earlier, this code makes my forms show when I click on their related radios. However, if I click on another radio, they don't disappear.

I had a lot of troubles to find some documentation about that (well, I found some, but the examples given wheren't thorough enough for me). Also, I tried to add an invisible after the visible one, with the exact condition except that 'checked' was set to false, but it didn't work.

Should I use plain Javascript / jQuery for this, or am I just it the wrong way?

Thanks in advance

Hello try this ...

$form['field_prestation_walk']['#states'] = [
  'visible' => [
    ':input[name="field_prestation_type"]' => [
        'value' => 'walk'
      ],
    ]
  ];


Is it possible to write node migrations for D8 alpha/nightly yet? If the migrate api in core is currently capable of doing simple d8-to-d8 migrations, where could I find documentation on how to do so?

This is more or less a learning exercise and I am only trying to migrate standard article nodes from one alpha version to the next.

We haven't written Drupal 8 sources yet and they won't be written until Drupal 6 and Drupal 7 is done. It's not a priority. You could, of course, help with writing them :)


How to set up a child theme using pattern lab? I have multisite architecture in drupal 8. and I am using pattern lab in my base theme but now I want to access some component from parent theme to child theme. What would be the best way to create child theme using pattern lab? Thanks in advance.

Welcome to Drupal answers.

Patternlab does not have opinion about Drupal theme hierarchy. So given you are maintaining the parent child hierarchy as per Drupal theming structure your child theme must be able to inherit all the component templates from parent to child.

While there could be multiple ways you can go ahead with development in future, one way would be to keep creating new components at parent theme & pattern lab. Patternlab can continue using base theme styling to show the components whereas  in Drupal styling(css) would be dynamic via variables which would be decided for what theme you are building.


Access callback return true, but still is: you are not authorized to this page function updatable_news_menu() {
    $items['updatable_news/test'] = array(
        'title' => 'Updatable news',
        'page callback' => 'updatable_news_test',
        'access callback' => 'updatable_news_permission',
        'access arguments' => "hello",
    );
}
function updatable_news_permission() {
    return true;
}

I have used a similar implementation and the permission is ok in another module. However, it fails in this module which defined a brand new entity.

function updatable_news_menu() {
    $items['updatable_news'] = array(
        'title' => 'Updatable news root',
        'page callback' => 'updatable_news_root',
        'access arguments' => true,
    );
}

I have to add new menu item with access should always be true. But it only succeed for administrator instead of anonymous user and logged in user.

'access arguments' must be an array. Like 'access arguments' => array('access administration pages')


hide a DIV on node edit form, but display on node creation I have a field that is part of a conditional related to several field collections. As such, it needs to be rendered when adding or editing a form. However, once the node has been created, I don't want users to be able to modify the value. So on the edit page, I want to hide the DIV surrounding it.

I thought I could trick it with CSS in Panels, but add and edit use the same page and the same CSS shows in each.

Whene you go to node create page, the body tag has class "page-node-add", but on edit node page - "page-node-edit".
So you can add CSS code:

.page-node-edit #your_div_id {display: none;}


DrupalDatabaseCache is causing performance issues I have devel query log / page execution time enabled on my site and most of the queries which are slowing down my site are related to DrupalDatebaseCache.

  DrupalDatabaseCache::set

Sample Query :

  UPDATE cache SET serialized=:db_update_placeholder_0,
  created=:db_update_placeholder_1, expire=:db_update_placeholder_2,
  data=:db_update_placeholder_3 WHERE ( (cid =
  :db_condition_placeholder_0) )

  INSERT INTO cache_menu (cid, serialized, created, expire, data) VALUES
  (:db_insert_placeholder_0, :db_insert_placeholder_1,
  :db_insert_placeholder_2, :db_insert_placeholder_3,
  :db_insert_placeholder_4)

Any clue what drupal is doing with caching and how to minimize it .
thanks

####Update####

I installed Memcache but still DrupalDatabaseCache calls are being made which is making the site slow .

If you concerned with performance then you want to maximise caching, not minimise it!

Caching is used to store data once expensive (time consuming) processes have been used to prepare it. Then future page requests simply return the cached data and don't have to do the slow processing again.

By default Drupal stores it's cache in the database but as you've spotted this isn't always that fast. Using a module like APC or memcache allows you to store the cache in the servers memory, as opposed to having to write it to the DB so this is much faster.

To make the most of Druapl's caching functions I would also recommend taking a read of lullabot's excellent article: A Beginner's Guide to Caching Data in Drupal 7


How to limit access to certain users for those who have "administer users" permission EDIT: I have found out how to solve the 'administer users permission needed' problem so I don't really need to know the answer for this. I will not delete the question however, since I would like to know the answer out of curiosity anyway.

Because of this I need to give the permission 'administer users' to everyone while still being able to manage access to individual users (to their view and edit pages as well as to their cancellation).

Therefore I need to restrict users with 'administer users' permission to be able to edit just certain users (based on their id and the id of the user that is to be viewed or edited). (the access function itself is not the problem I already have that one)

I thought about doing something like 'Administer Users by Role' plugin but as it seems there are just too many potential security issues there (the 'administer users permission' is not used only in access to user edit/view but e.g in access to user fields settings page as well.

Any ideas?

The administer users permission is a VERY powerful permission and you shouldn't give this permission anyone that you don't trust. Otherwise, the users with that permission can do all nasty things. For example:

They can manage fields on user accounts at admin/config/people/accounts/fields
They can manage permissions and grant/revoke users including themselves other permissions at admin/people/permissions
They can add/cancel/edit users including admins!

Conclusion: Never, ever give this permission to ANYONE!

There are a few modules that let users granularly administer other users. One of them is the Administer Users by Role. Although, its latest version for Drupal 7 requires to give this mighty permission to the users, but there's a patch, which I also contributed, at this issue page. With this patch, you don't need to give 'administer users' permission to the users and still allow them to administer other users.

There are also other related modules, but I cannot tell anything about them since I don't use them:

Subuser

  This module allows users to be given the permission to create subusers. The subusers may then be automatically assigned a role or roles. The parent of the subusers then has the ability to manager the users they have created.

Role Delegation

  This module allows site administrators to grant some roles the authority to assign selected roles to users, without them needing the administer permissions permission.


How do I load a library defined with hook_library() on node/edit pages? I've defined a library of JavaScript files and CSS files required for my module to function using hook_library().

How do I go about loading this library on node/edit pages?

I would call drupal_add_library() in a hook_form_alter() implementation, like this:

function MODULE_form_alter(&$form, &$form_state, $form_id) {
  if (isset($form['#node_edit_form']) && $form['#node_edit_form') {
    drupal_add_library('MODULE', 'LIBRARY');
  }
}

This should ensure the library is loaded whenever a node form is displayed.

And using hints from Berdir to use hook_form_BASE_FORM_ID_alter and from kiamlaluno to use #attached:

function MYMODULE_form_node_form_alter(&$form, &$form_state) {
  $form['#attached']['library'][] = array('MODULE', 'LIBRARY');
}


Multiple form buttons with AJAX, how to update form state storage data? I have a form built with the Form API that has multiple button form elements. I don't want any of these to submit the form normally, I want them to utilize #ajax and callbacks to update the display. I feel like I run into this on every so often and can't quite remember how to make it work.

When the form first loads, I want half of the buttons to be disabled. When one of the buttons is clicked, I want to be able to detect this in buildForm so I can set form defaults and remove the disable property so other buttons can now be used.

I thought I could set storage in the callback and read it back the next time the form is built:

// Relevant bit of the form...
$form['#prefix'] = '
';
$form['#suffix'] = '
';

$form['actions']['#type'] = 'actions';

$form['actions']['update'] = [
  '#type' => 'button',
  '#value' => $this->t('Start Form'),
  '#ajax' => [
    'wrapper' => 'my-form-wrapper',
    'callback' => [$this, 'update'],
    'method' => 'replace',
  ]
];

$form['actions']['reset'] = [
  '#type' => 'button',
  '#value' => $this->t('Reset Form'),
  '#ajax' => [
    'wrapper' => 'my-form-wrapper',
    'callback' => [$this, 'reset'],
    'method' => 'replace',
  ],
  '#disabled' => TRUE,
];

// The AJAX callback
public function update(array &$form, FormStateInterface $form_state) {
  $form_state->set('flag_1', TRUE);
  $form_state->set('flag_2', "Started!");
  $form_state->setRebuild();
}

The callback fires, and I see $form_state storage get updated with those arbitrary values, but when the form is rebuilt, I do not see them in $form_state anymore.

I looked at a few other similar form API AJAX questions, but did not have any luck getting unstuck.

Note: I do not want to have to juggle this with jQuery. I want to be able to update form data behind the scenes and rebuild the form appropriately with the relevant data.

Please try this, as @4k4 suggested you have to first build a normal form and ajaxify by using #ajax, and from the method defined inside #ajax you can return a $form and any fields inside the wrapper.

// Relevant bit of the form...
$form['#prefix'] = '
';
$form['#suffix'] = '
';

$form['actions']['#type'] = 'actions';

$form['actions']['update'] = [
  '#type' => 'button',
  '#value' => $this->t('Start Form'),
  '#submit' => ['::setAjaxSubmit'],
  '#ajax' => [
    'wrapper' => 'my-form-wrapper',
    'callback' => [$this, 'update'],
    'method' => 'replace',
  ]
];

$form['actions']['reset'] = [
  '#type' => 'button',
  '#value' => $this->t('Reset Form'),
  '#ajax' => [
    'wrapper' => 'my-form-wrapper',
    'callback' => [$this, 'reset'],
    'method' => 'replace',
  ],
  '#disabled' => TRUE,
];

// The AJAX callback
public function update($form, FormStateInterface $form_state) {
//return $form or part inside the ajax wrapper
return $form;
}

// The submit callback
public function setAjaxSubmit($form, FormStateInterface $form_state) {
  $form_state->set('flag_1', TRUE);
  $form_state->set('flag_2', "Started!");
  $form_state->setRebuild();
}


Inserting data to external DataBase i'm trying to insert data to a different data base that i created. I've read a lot in the forum, the support documents and other pages but i haven been able to figure it out the problem, can someone give me a hand? point me to a right direction?

first i modified the settings.php like this:

<?php
/** ORIGINAL DATA BASE CONNECTION
$databases = array (
  'default' =>
  array (
    'default' =>
    array (
      'database' => 'dbname',
      'username' => 'dbuser',
      'password' => 'dbpsw',
      'host' => 'dbhost',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
    ),
  ),
);
*/

/** DOUBLE DATA BASE CONNECTION  */
$databases = array();
$databases['default']['default'] = array(
   'database' => 'dbname',
      'username' => 'dbuser',
      'password' => 'dbpsw',
      'host' => 'dbhost',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
);
$databases['civilproconstru']['default'] = array(
   'database' => 'name',
      'username' => 'username',
      'password' => 'password',
      'host' => 'datahost',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
);
?>

And then in the module i'm creating i'm using this code: (i'm pasting the full module code, the insert is at the end, just in case the error is in the back)

<?php
/** START CONFIG MODULE
 * Implements hook_permission().
 */
function project_creator_permission() {
  return array(
    'access project_creator content' => array(
      'title' => t('Access content for the project_creator module'),
    )
  );
}

 /**
 * Agrega a lista de estructura hook_block_info().
 */
function project_creator_block_info() {
  $blocks['project_creator'] = array(
    // The name that will appear in the block list.
    'info' => t('Project Creator'),
    // Default setting.
    'cache' => DRUPAL_CACHE_PER_ROLE,
  );
  return $blocks;
}

/**
 * Agrega menu en toolbar para "role" contratante hook_menu().
 */
function project_creator_menu() {
  $items['admin/crear_proyecto'] = array(
    'title' => 'Crear Proyecto',
    'description' => 'Crear Proyecto',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('project_creator_insert'),
    'access callback' => 'project_creator_access',
  );

  return $items;
}

function project_creator_access() {
 global $user;
 if (in_array('contratante', array_values($user->roles))){
     return TRUE;
 }
}
 /**
 * END CONFIG MODULE.
 */

/** START PROJECT CREATOR FORM */

function project_creator_insert($form, &$form_state){

    $form['p_name'] = array(
    '#type' => 'textfield',
    '#title' => 'p_name',
    '#size' => 15
    );

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

db_set_active('civilproconstru'); /* OPEN DATA BASE*/
db_insert('project_info')
->fields(array(
'p_name' => $form_state['values']['p_name'],
))->execute();
drupal_set_message("succesfully saved");
db_set_active(); /*CLOSE DATA BASE*/

}
?>

At the end, it shows me the form but when i click save button it seems to be inserting the data but when i check the database it still empty. It doesnt give me any kind of errors on execution.
Thank u for the help...

You don't have any submit callback. You should do any process with the submitted data in a submit callback like that:

function project_creator_insert_submit($form, &$form_state) {
  db_set_active('civilproconstru'); /* OPEN DATA BASE*/
  db_insert('project_info')
    ->fields(array(
      'p_name' => $form_state['values']['p_name'],
    ))->execute();
  drupal_set_message("succesfully saved");
  db_set_active(); /*CLOSE DATA BASE*/
}


Change max length of signature field to more than 255 characters How can I change the max length of the drupal 7 signature field to more than 255 characters? I've already changed the sql data type from 255 to varchar(900), yet drupal still shows the error, as soon as a user wants to update his signature to more than 255 characters.

In a mysql database varchar can only store 255 characters.


Is it possible to set the user picture as the value of an image field from a node? Use case: On my site, I need a workflow that allows user pictures to be approved.  Users submit images using a special content type.  Of these images, they must designate one as their user picture.  I use the Rules module to manage the approval workflow.

I managed to get everything set up in Rules so that the picture they designate shows up in their profile appropriately.  However, many modules (such as Privatemsg) make use of Drupal's default user picture.  Is there a way to set the Drupal user picture value with the value from the uploaded field?

A quick grep through privatemsg shows that it is using theme('user_picture'...) so you should be able to copy user-picture.tpl.php from "drupalroot"/modules/user to your theme and edit it to your specifics...just flush caches :)


Export blocks to production site Possible Duplicate:
  Quickest way to reimport menus and blocks (D7)

I need a way to easily transfer the block configuration from my staging site over to the live site.

I've been working on implementing a new theme for my client and showing them my progress using a staging site, which is basically a clone of the live site. The staging site's blocks configuration is completely different from the live site.

I've heard about the Features module, but unless i'm mistaken, it doesn't work with Blocks. Maybe I need to use Chaos Tools?

I'm just trying to avoid having to manually place each block in its correct position when it's time to go live, which would be very time consuming. Using exportable blocks sounds like a good idea, but I am unsure if it is a safe procedure.

Yo will need to use the Features Extra module. It currently supports: vocabularies; nodequeues (definitions); block settings; custom blocks (boxes).


Additional fields for Ubercart uc_order_product I need to add fields to the Ubercart entity uc_order_product. I was looking into the function field_create_instance, but don`t know exactly where to use it. I believe I should attach the field I want to the uc_order_product entity using field_create_instance.

The 'uc_order_product' definition in uc_order.module doesn't have a fieldable => TRUE definition. May I add that definition from my custom module and tell uc_order_product is fieldable? This is uc_order_product entity definition in the uc_order.module.

'uc_order_product' => array(
  'label' => t('Order product'),
  'base table' => 'uc_order_products',
  'controller class' => 'UcOrderProductController',
  'metadata controller class' => 'UcOrderProductMetadataController',
  'entity keys' => array(
    'id' => 'order_product_id',
    'label' => t('Order product'),
  ),
  'bundles' => array(
    'uc_order_product' => array(
      'label' => t('Order product'),
    ),
  ),
  'view modes' => array(
    'full' => array(
      'label' => t('Normal view'),
    ),
    'cart' => array(
      'label' => t('Cart view'),
    ),
  ),
  // Entity API callbacks.
  'access callback'   => 'uc_order_order_product_access',
  'save callback'     => 'uc_order_product_entity_save',
  'deletion callback' => 'uc_order_product_delete',
)

Finally, I am trying to hook to this entity when it gets updated (hook_entity_update, hook_entity_presave) but they never get called on uc_order_product update. How can I hook to this entity when it is being saved, or when it has been saved? Thank you!

First of all, if you want alter the meta information of an entity, the hook_entity_info_alter in your custom module is the right way. More information in official page: hook_entity_info_alter

In this particular case, attributte 'fieldable' is not defined, so the function responsable to call the hook_entity_info and hook_entity_info_alter is the entity_get_info() in common.inc file. This function provide default values and the default value to 'fieldable' is FALSE. You only need change this value implementing hook_entity_info_alter.

 function YOUR_MODULE_entity_info_alter(&$entity_info){
   if(isset($entity_info['uc_order_product'])){
     $entity_info['uc_order_product']['fieldable'] = TRUE;
   }
 }

Second issue, This is a link to a previous question about how create fields programatically. The best answer suggests field_create_fieldand 'field_create_instance', but if you have a defined field (for example, an image type field created through the UI), you could use field_update_field and 'field_update_instance'. You can find more information about these functions in field.crud.inc in the field module folder.


comma separated cck multivalues in a view I've created a cck field and called it authors so the machine name is field_authors. To print this field in a view template, i'm doing this - print $fields['field_authors_value']->content;
In case is there 2 or 3 values it prints each value on separate line, and i want something like author1, author2, author3. (comma separated)

Tried to do this way in template.php:

function mytheme_content_view_multiple_field($items, $field, $values) {
  $output = '';
  switch($field['field_name']) {
    case 'field_authors_value':
      $output .= '
'. implode(', ', $items) .'
';
      break;

    default:
      foreach ($items as $item) {
        if (!empty($item) || $item == '0') {
      $output .= '
'. $item .'
';
    }
      }
      break;
  }
  return $output;
}

but it has no effect. What im doing wrong?

Per the following on drupal.org:
http://drupal.org/node/1018198#comment-3993646

  You can do this by copying "views-view-field.tpl.php" into your theme's directory, under
  a name the view will recognize it selectively. Put the following code in it:

    print preg_replace('/<\/div><div[^>]+>/i', ', ', $output);

In your case, I think it would be:

  views-view-field--VIEWNAME--field_authors_value.tpl.php


Views PHP Filter - Filter Results by Role I looked a lot of places and couldn't find a way to filter the results of a view based on the nodes a user could actually edit. So I used Views PHP Filter and some custom code to make it happen.

Comments and improvements welcome.

global $user;
$type = array();
$nid_list = array();
$perms = array();
foreach($user->roles as $role) {
  $role_perms = db_fetch_array(db_query("SELECT `role`.`name`, `permission`.`perm` FROM {role} INNER JOIN {permission} ON `role`.`rid` = `permission`.`rid` WHERE `role`.`name` = '%s'", $role));
  $perm_temp = explode(", ", $role_perms['perm']);
  $perms = array_merge($perms, $perm_temp);
}
foreach($perms as $perm) {
  $pos_edit = strpos($perm, "edit");
  $pos_content = strpos($perm, "content");
  $pos_products = strpos($perm, "products");
  if (($pos_edit !== false) && ($pos_content !== false)) {
    $perm = substr($perm,9,strlen($perm)-16);
    if (!in_array($perm, $type)) {
      $type[] = $perm;
    }
  } else if (($pos_edit !== false) && ($pos_products !== false)) {
     $perm = substr($perm,9,strlen($perm)-18);
     if (!in_array($perm, $type)) {
       $type[] = $perm;
     }
  }
}
foreach($type as $ctype) {
  $nids = db_query("SELECT `node`.`nid` FROM `node` WHERE `node`.`type` = '%s'", $ctype);
  while($row = db_fetch_array($nids)) {
    $nid_list[] = $row['nid'];
  }
}
asort($nid_list);
return $nid_list;

I would take the ORDER BY out of your last query and let views sort things itself. After all, you may want to sort the nids by date or something later on, so why do things twice?

And also change your query style to use the drupal syntax, like:

SELECT nid FROM {node}...


Drush error when attempting Drupal update: unable to copy/move I have a Drupal site running on localhost (Windows) that I'm trying to update from 8.6.7 to 8.6.15.

When using Drush to perform the update (drush up drupal -y), I encounter the following error:

Unable to copy C:\Users\USERNA~2\AppData\Local\Temp/drush_tmp_1556533742_5cc6d1ee1cacf/drupal-8.6.15 to
W:\htdocs\site-name\www/drupal-8.6.15.
Unable to move C:\Users\USERNA~2\AppData\Local\Temp/drush_tmp_1556533742_5cc6d1ee1cacf/drupal-8.6.15 to
W:\htdocs\site-name\www/drupal-8.6.15.
Updating project drupal failed. Attempting to roll back to previously installed version.
Backups were restored successfully.

I've tried:

clearing Drush's cache (drush cc drush)
updating Drush (via composer) (now running Drush 8.2.3)
clearing Drupal's caches

But the problem remains.

This problem does NOT occur when updating modules. Only Drupal itself.

I checked the C:\Users\USERNA~2\AppData\Local\Temp folder while drush was working, and I was able to confirm that the drush_tmp_1556533742_5cc6d1ee1cacf subfolder was indeed present for a time (containing the Drupal .tar.gz and its upacked folder). So there's no issue in writing in this folder.

Any idea what causes this and how to solve it?

Thanks in advance.

We can only guess at an answer. A likely scenario might be disk space, permissions, or some other conflict with Drush & filesystem, but that's speculation.

Run the same command with the --debug flag (drush up drupal -y --debug) to see a verbose dump of what Drush is doing and look for errors/warnings that occur as Drush is attempting a core update. Once you know the underlying filesystem issue you'll be able to resolve it.


Create an exposed filter block from a BLOCK display output I'm trying to show my views exposed filter as a block (so it's placeable in the block structure), from a block display. I understand if I was using a page display, I could just use "Advanced > Exposed Form" to show as block, but the option doesn't exist if the views' output is a block.

I've search everywhere, and I can't find any solution. Do you have any idea?

In Drupal 7+ ensure that in the "advanced settings->other" in your block view, Use ajax=YES.


How can I list all of the pages that display a certain view? In Drupal 7, is there a way either programmatically or through the UI to generate a list of all of the pages that display a particular view?

There is no way to do this through the UI and even to do it programmatically would be a tall order. Views can contain page, block, panel pane, and other types of display. Those displays can be embedded in pages via blocks, panels, or custom code.

If you have a specific view display in mind, e.g. a block, it would narrow the scope of the task, but the task would still be very difficult.


When creating a Chaos Tools content type plugin, what is a subtype and how are they used? I'm perfectly fine with creating Chaos Tools content types for use in Panels, but I've always used single => TRUE.

I've looked through the docs, but still can't quite seem to grok how to utilise subtypes.  None of the examples shipped with Chaos Tools seem to use them (they also all implement single => TRUE, and a quick grep of the Chaos Tools directory only shows the Custom Content type using subtypes, and it only appears to use it for including the export functionality (unless I'm reading it wrong - which is likely).

It's a good question, and some further information can be found in the ctools help file context-content.html

  The CTools pluggable content system provides various pieces of content
  as discrete bits of data that can be added to other applications, such
  as Panels or Dashboard via the UI. Whatever the content is added to
  stores the configuration for that individual piece of content, and
  provides this to the content.

  Each content type plugin will be contained in a .inc file, with
  subsidiary files, if necessary, in or near the same directory. Each
  content type consists of some information and one or more subtypes,
  which all use the same renderer. Subtypes are considered to be
  instances of the type. For example, the 'views' content type would
  have each view in the system as a subtype. Many content types will
  have exactly one subtype.

Also, in ctools_content_get_subtypes

  Get all of the individual subtypes provided by a given content type.
  This would be all of the blocks for the block type, or all of the
  views for the view type.

So in a sense, the subtypes are individual instances of that type, such as individual Views or Blocks, or custom content instances, that use the same rendering functions as the parent content type.

For example, you can see in ctools_content_process

// If a subtype plugin exists, try to use it. Otherwise assume single.
if (function_exists($function_base . 'content_types')) {
  $plugin['content types'] = $function_base . 'content_types';
}

In the example of the block content type, this function returns the content types, or sub types for that plugin.

/**
 * Return all block content types available.
 *
 * Modules wanting to make special adjustments the way that CTools handles their blocks
 * can implement an extension to the hook_block() family, where the function name is
 * of the form "$module . '_ctools_block_info'".
 */
function ctools_block_content_type_content_types() {
  $types = array();
  foreach (module_implements('block_info') as $module) {
    $module_blocks = module_invoke($module, 'block_info');
    if ($module_blocks) {
      foreach ($module_blocks as $delta => $block) {
        $info = _ctools_block_content_type_content_type($module, $delta, $block);
        // this check means modules can remove their blocks; particularly useful
        // if they offer the block some other way (like we do for views)
        if ($info) {
          $types["$module-$delta"] = $info;
        }
      }
    }
  }
  return $types;
}

Lastly one more example for good measure from the views_content content type plugin

/**
 * Return all content types available.
 */
function views_content_views_content_type_content_types($plugin) {
  $types = array();
  // It can be fairly intensive to calculate this, so let's cache this in the
  // cache_views table. The nice thing there is that if views ever change, that
  // table will always be cleared. Except for the occasional default view, so
  // we must use the Views caching functions in order to respect Views caching
  // settings.
  views_include('cache');
  $data = views_cache_get('views_content_all', TRUE);
  if (!empty($data->data)) {
    $types = $data->data;
  }

  if (empty($types)) {
    $views = views_get_all_views();

    foreach ($views as $view) {
      if (empty($view->disabled)) {
        $types[$view->name] = _views_content_views_content_type($view);
      }
    }

    views_cache_set('views_content_all', $types, TRUE);
  }

  return $types;
}

In this case _views_content_views_content_type returns

function _views_content_views_content_type($view) {
  $title = $view->get_human_name();

  $icon = 'icon_views_page_legacy.png';

  return array(
    'view' => $view->name,
    'title' => $title,
    'icon' => $icon,
    'description' => filter_xss_admin($view->description),
    'category' => t('Views'),
  );

}


How to embed a view in hook_page_build() I'm trying to render a view into a region in hook_page_build().  I'm using views_embed_view(), but I'm getting the errors:

  Warning: Invalid argument supplied for foreach() in element_children()
  (line 6428 of /var/www/.../includes/common.inc). Warning: Illegal
  string offset '#children' in drupal_render() (line 5893 of
  /var/www/.../includes/common.inc). Warning: Illegal string offset
  '#children' in drupal_render() (line 5903 of
  /var/www/.../includes/common.inc). Warning: Illegal string offset
  '#children' in drupal_render() (line 5941 of
  /var/www/.../includes/common.inc). Warning: Illegal string offset
  '#printed' in drupal_render() (line 5948 of
  /var/www/.../includes/common.inc).

I have a view named 'blogs' and a view named 'block_2'.  In my hook:

function mymod_page_build(&$page) {
    $page['sidebar_second']['blogs'] = views_embed_view('blogs', 'block_2');
}

I'm trying to move away from blocks and context, and just render content I'd otherwise use in blocks directly into their regions in hook_page_build().

The docs say hook_page_build()'s $page variable is for render arrays.

Less obvious from the docs without digging a little further but views_embed_view() returns a string of HTML markup.

So just assigning the result of views_embed_view() to the render array breaks it.

Instead you can use a #markup element.

Because it is the default element type you don't have to specify an element type or theme function or anything, so you can just do this:

/**
 * Implements hook_page_build().
 */
function MODULENAME_page_build(&$page) {
  $page['sidebar_second']['blogs']['#markup'] = views_embed_view('blogs', 'block_2');
}

If that is your entire code for this though (if you don't have some complex logic relating to when this view is being added) I would not recommend adding a block to a region in this manner.

There are lots of options already out there for adding blocs to regions without custom code. For example you could use one of these:

Drupal core block module
Context
Panels


How do I add edit/delete buttons to a custom module items list? I have a custom form on my development site for visitors to create requests, with 3 fields: name, contact, and request.

This is the code in RequestForm.php.

public function getFormId() {
  return 'request_form';
}

This is the form builder.

public function buildForm(array $form, FormStateInterface $form_state) {
  $form['name'] = [
    '#type' => 'textfield',
    '#title' => $this->t('имя'),
  ];
  $form['contact'] = [
    '#type' => 'textfield',
    '#title' => $this->t('контакт'),
  ];
  $form['reqtext'] = [
    '#type' => 'textarea',
    '#title' => $this->t('Текст заявки'),
  ];
  $form['actions']['#type'] = 'actions';
  $form['actions']['submit'] = [
    '#type' => 'submit',
    '#value' => $this->t('Отправить заявку'),
    '#button_type' => 'primary',
  ];
  return $form;
}

The validation handler isn't implemented; I just need to come up with the basics. The user data is stored in the database.

public function submitForm(array &$form, FormStateInterface
$form_state) {
  $name = $form_state->getValue('name');
  $contact = $form_state->getValue('contact');
  $reqtext = $form_state->getValue('reqtext');

  $connection = \Drupal::database();
  $result = $connection->insert('request')
    ->fields([
      'name' =>  $name,
      'contact' => $contact,
      'reqtext' =>  $reqtext ,
    ])
    ->execute();
}

The requests are saved in the database, and I need to view, edit, and delete them.
I created a route to list all of them, using the following code.

.routing.yml

request.list:
path: '/admin/request-list'
defaults:
    _controller: '\Drupal\request\Controller\RequestController::showdata'
    _title: 'Отобразить все заявки'
requirements:
    _role: 'administrator'

The route controller

class RequestController extends ControllerBase {
public function showdata() {
  $listall = \Drupal::database()->select('request', 'n');
  $listall->fields('n', array('requestid', 'name', 'contact',
'reqtext'));
  $result=$listall->execute()->fetchAll();

  // Create the row element.
  $rows = array();
  foreach ($result as $row => $content) {
    $rows[] = array(
      'data' => array($content->requestid, $content->name, $content-
>contact, $content->reqtext));
  }

  // Create the header.
  $header = array('requestid', 'name', 'contact', 'reqtext');

  $output = array(
    '#type' => 'table',
    #theme.
    '#header' => $header,
    '#rows' => $rows
  );
  return $output;
}

How and where  do I implement buttons to edit/delete a certain request?

I'm seeing something like a table:

Num Name    Contact        Request                     Options
1   Alex    +7898231231    I need a 10 litres of oil   Edit/Delete
2   John    +7231231231    I need a 50 litres of oil   Edit/Delete

I must be missing something, I guess. There is the "right" way to do this in Drupal 8.
Any help?

You can try code:

use Drupal\Core\Link;

[...]

// Create the row element.
$rows = array();
foreach ($result as $row => $content) {
  $rows[] = array('data' => array($content->requestid);
  $rows[] = array('data' => array($content->name);
  $rows[] = array('data' => array($content->contact);
  $rows[] = array('data' => array($content->reqtext);
  //Actions.
  $edit_link = Link::createFromRoute($this->t('Edit'), 'myrouter.edit_form'['id'=>$content->requestid], [
        'absolute' =>
          TRUE
      ]);

$delete_link = Link::createFromRoute($this->t('Delete'),'myrouter.delete_form',['id'=>$content->requestid], ['absolute' => TRUE]);

$build_link_action = [
      'action_edit' => [
      '#type' => 'html_tag',
      '#value' => $edit_link->toString(),
      '#tag' => 'div',
      '#attributes'=>['class'=>['action-edit']]
     ],
     'action_delete' => [
       '#type' => 'html_tag',
       '#value' => $delete_link->toString(),
       '#tag' => 'div',
       '#attributes'=>['class'=>['action-edit']]
       ]
      ];

 $rows[] = ['data' => \Drupal::service('renderer')->render($build_link_action)];
}

// Create the header.
$headers = array('requestid', 'name', 'contact', 'reqtext','options');

$output['results_table'] = [
  '#theme' => 'table',
  '#rows' => $rows,
  '#header' => $headers,
  '#empty' => $this->t('There are no items to display.')
];
return $output


#ajax on a managed_file custom form field is not working I have a custom Drupal 8 form using a managed_file field with an #ajax callback but the ajax callback is never called (example below). I assume that it's because the managed file field type is already using ajax. Is there a way that I can implement my own ajax callback within my custom module to fire after the managed file's own ajax completes?
 $form['file'] = array(
      '#title' => t('Image File'),
      '#type' => 'managed_file',
      '#required' => TRUE,
      '#upload_location' => 'private://',
      '#multiple' => FALSE,

      '#upload_validators'    => [
        'file_validate_is_image'      => array(),
        'file_validate_extensions'    => array('jpg png psd ai bmp eps jpeg pdf tif tiff'),
        'file_validate_size'          => array(56600000)
      ],

      '#ajax' => [
        'callback' => array($this, 'myAjaxCallback'),
        'event' => 'change',
        'wrapper' =>  'im-area',
        'progress' => array(
          'type' => 'throbber',
          'message' => t('Choose City'),
        ),
      ],
    );

I don't think you can attach multiple ajax callbacks to a form element. But you could override the callback by extending the core element:
/src/Element/MyManagedFile.php
<?php

namespace Drupal\mymodule\Element;

use Drupal\file\Element\ManagedFile;
use Drupal\Core\Ajax\AlertCommand;
use Drupal\Core\Form\FormStateInterface;
use Symfony\Component\HttpFoundation\Request;

/**
 * My Managed File Element.
 *
 * @FormElement("my_managed_file")
 */
class MyManagedFile extends ManagedFile {

 /**
 * {@inheritdoc}
 */
 public static function uploadAjaxCallback(&$form, FormStateInterface &$form_state, Request $request) {
    $response = parent::uploadAjaxCallback($form, $form_state, $request);
    $response->addCommand(new AlertCommand('Hello!!!'));
    return $response;
  }

}

And then use it in the custom form:
 $form['file'] = array(
      '#title' => t('Image File'),
      '#type' => 'my_managed_file',


Change max length of title in a custom block added via a template file A drupal 7 website has a custom block added via a template file. The block displays previews of article content type belonging to a certain rubric. It uses the following line to do so:
$block = module_invoke('views', 'block_view', 'given-block-name'); echo render($block['content']);

The articles displayed have their titles truncated at the length of 50 characters. I could not find the number 50 in the files on the hosting, so it should be somewhere in the database, and so somehow changeable via the admin panel. Yet I am having a very hard time finding where to change this number. I have changed the length of the teaser for the article content, but that apparently bears no influence on what is displayed in the given block.

Turns out the setting was hidden block display -> preview -> edit directly in preview.


Fatal error: Class name must be a valid object or a string A "Fatal error: Class name must be a valid object or a string […] common.inc" appears on every page on the backoffice.

We don't how to reproduce this because it happens suddenly. When I've done a var_dump() of $class, and $entity_type, this is the result I obtained:

    string 'user' (length=4)
    TaxonomyTermController
    string 'taxonomy_term' (length=13)
    string 'user' (length=4)

The debug code has been added to entity_get_controller().

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'];
    echo $class;
    var_dump($entity_type);
    $controllers[$entity_type] = new $class($entity_type);
  }

  return $controllers[$entity_type];
}

It seems that $type_info['controller class'] doesn't exist for "User".

This problem is solved when we flush the cache_bootstrap (via DELETE FROM cache_bootstrap) and cache (via DELETE FROM CACHE), but this is a temporary solution because it appears again.

It's a big problem for us. Any idea will be really appreciated.

The function entity_get_info() is responsible for gathering up this data about your entities. I would try to debug that one, and see what goes wrong.

You will want to have just cleared the cache when you do this, or you debug results will not be correct.

Can't think of a better answer to the question that is still generic enough to be useful for someone else.


Converting entity to JSON I am quite new to Drupal and Drupal 8.

I have created a custom module that creates a custom content type. I am attempting to extract those entities and display them as JSON or XML.

I have read through the Entities Api on loading, querying, and rendering entities but I am struggling to find view_mode_name types :

$build = $view_builder->view($entity, 'view_mode_name', $language->getId());

Would I be able to do something like :

$build = $view_builder->view($entity, 'xml', $language->getId());

or does this only produce a 'render array' ? If this is the case then should I be looking at the Serializer Api ? If so would anyone be able to guide me in the right direction on using this ?

Here is my code so far :

public function display() {
// use the debug component
Debug::enable();

// get node -> testimonial content types
$entity_ids = \Drupal::entityQuery('node')
->condition('type', 'testimonial')
->execute(); // fetch

$node_storage = \Drupal::entityManager()->getStorage('node');

$data = $node_storage->loadMultiple($entity_ids);

$view_builder = \Drupal::entityManager()->getViewBuilder('node');

// render multiple
return $view_builder->viewMultiple($data, 'xml');

}

View builders only display HTML/render arrays.

Look into the serialization/rest/hal modules if you want to extract the data of your entity, as you guessed already.

Note that REST in core only supports content entities at the moment, but I assume you have one of those.

Also, I'd recommend hal+json serialization, provided by the hal.module instead of the raw json seralization, as that can't deal with things like references properly.


How do I apply path alias patch? I am updating a site from Drupal 8.7 to Drupal 8.8, and after running a drush updb, I encountered this error:
[error]  TypeError: Argument 2 passed to Drupal\pathauto\AliasStorageHelper::__construct() must be an instance of Drupal\path_alias\AliasRepositoryInterface, instance of Drupal\Core\Path\AliasRepository given, called in drupal/core/lib/Drupal/Component/DependencyInjection/Container.php on line 289 in Drupal\pathauto\AliasStorageHelper->__construct() (line 79 of drupal/modules/contrib/pathauto/src/AliasStorageHelper.php) #0 drupal/core/lib/Drupal/Component/DependencyInjection/Container.php(289): Drupal\pathauto\AliasStorageHelper->__construct(Object(Drupal\Core\Config\ConfigFactory), Object(Drupal\Core\Path\AliasRepository), Object(Drupal\Core\Database\Driver\mysql\Connection), Object(Drupal\pathauto\VerboseMessenger), Object(Drupal\Core\StringTranslation\TranslationManager), Object(Drupal\Core\Entity\EntityTypeManager))

I found a similar issue in this link here and there seems to be a solution(patch) for it.
EDIT:
I ran a composer command attempting to fix the path alias error:
composer require 'drupal/pathauto:1.x-dev@dev'
Ran composer update, and drush updb.
The following is the error displayed by the console:
>  [error]  Argument 2 passed to Drupal\pathauto\AliasStorageHelper::__construct() must be an instance of Drupal\path_alias\AliasRepositoryInterface, instance of Drupal\Core\Path\AliasRepository given
>  [error]  Update failed: block_field_update_8001
> PHP Fatal error:  Uncaught ReflectionException: Class Drupal\path_alias\AliasRepository does not exist in /var/www/html/docroot/vendor/symfony/dependency-injection/ContainerBuilder.php:1174
> Stack trace:
> #0 /var/www/html/docroot/vendor/symfony/dependency-injection/ContainerBuilder.php(1174): ReflectionClass->__construct('Drupal\\path_ali...')
> #1 /var/www/html/docroot/vendor/symfony/dependency-injection/ContainerBuilder.php(634): Symfony\Component\DependencyInjection\ContainerBuilder->createService(Object(Symfony\Component\DependencyInjection\Definition), Array, true, 'path_alias.repo...')
> #2 /var/www/html/docroot/vendor/symfony/dependency-injection/ContainerBuilder.php(1281): Symfony\Component\DependencyInjection\ContainerBuilder->doGet('path_alias.repo...', 1, Array, true)
> #3 /var/www/html/docroot/vendor/symfony/dependency-injection/ContainerBuilder.php(1238): Symfony\Component\DependencyInjection\ContainerBuilder->doResolveServices(Object(Symfony\Component\DependencyInjection\Reference), Array, true)
> #4 /var/www/html/docroot/ in /var/www/html/docroot/vendor/symfony/dependency-injection/ContainerBuilder.php on line 1174
 [error]  Update aborted by: system_update_8803, block_field_update_8001
 [error]  Finished performing updates.

Is there anything else I can do with the pathauto module?

Do you mean of "apply a patch" on a drupal module?
You should use composer-patches, the github page cleary explain of setup it and use for a patch modules\core.
In your case it should be somethings like:
{
  "require": {
    "cweagans/composer-patches": "~1.0",
    "drupal/core-recommended": "^8.8",
  },
  "config": {
    "preferred-install": "source"
  },
  "extra": {
    "patches": {
      "drupal/pathauto": {
        "issue name": "https://www.drupal.org/files/issues/2020-04-27/3131286-3.patch"
      }
    }
  }
}

However, this issue is already "fixed", so it is already in the dev version of the module. Applying on the stable one could fail, so you'd just have to switch to the dev version of the module, aka
composer require 'drupal/pathauto:1.x-dev@dev'

Please note that is best to avoid on production dev version unless strictly necessary. In other words, if you switch to dev, you should update to the next release of pathauto asap it's released


drupal 7: How to create a pop-up window with close button, that shows automatically while loading front page I am struggling to create a pop-up window (webform, node or something else) with close button.

Modal forms can achieve this by click link. But anyone know how to make it shows without link?

You can use Lightbox2 module. This might help you or else you can also try Node pop-up module.


Pop-up calendar option does not display when I add Date field in webform I am using Date and Calendar module. When I add a component to webform, I selected the Date field > click Add. But I do not see the Pop-up calendar option. However, when I add a content type (structure > Add content > I see the Pop-up calendar option display for the date field).

How I can display the pop-up calendar option when I add Date component to webform?

The Popup Calendar option in Webform is entirely separate from the Date module, so it should always work regardless of whether you have installed Date module (or Date Popup module).

Make sure you've added a date component to your Webform, then under "Display" there is a checkbox for "Enable popup calendar". This option is enabled by default. Now a little calendar icon should appear next to your date component when viewing the node.


How to include CSS from a vendor directory? Is it possible to include CSS from a vendor directory? I need to include a CSS artifact from a Pattern Lab dependency.

Is it best to copy the artifact into the Drupal theme and just reference it that way?

It's probably best to copy it, yes. Drupal isn't set up to serve any assets from the vendor/ folder, and actively prevents it by default with an .htaccess file. Also, all assets are normally handled via "libraries", which are defined by a module and whose JS/CSS files must be in the module folder.

You could change the .htaccess and insert a direct style element with /vendor/.../xyz.css into the page, but at that point it's probably a lot cleaner and more secure to copy it.

If it changes often and you want to avoid manually copying/committing it every time, you might look at automating this with a build script (eg. with webpack).


Why EVA display of views is added to the manage display of content type? There are three related content types in my website: article, sub-article, number-article. there is an entity reference from number-article to the sub-article and an entity reference from sub-article to the article. There are two views that displays these relations and in each one there is an EVA display. in the manage display of sub-article content type I saw this:

content of numberarticle is set to all content types, so why a display if view is added to a content type and how does Drupal find out where it should be?!

From the EVA project page:

  "Eva" is short for "Entity Views Attachment;" it provides a Views display plugin that allows the output of a View to be attached to the content of any Drupal entity.

(...)

  The placement of the view in the entity's content can be reordered on the "Field Display" administration page for that entity, like other fields added using the Field UI module.

Apparently it did just what it claims it does.