Save a new value with entity_metadata_wrapper to an entity field which is an array I need to save a new value to a field on an entity and I was wondering if it was possible to use entity_metadata_wrapper or is it only possible to set an existing value?

When dealing with multi-value fields, the associated entity metadata wrapper object is an instance of EntityListWrapper (It may be a good idea to browse the API to look at the available methods. Also note this class implements the ArrayAccess interface)

So the simplest way to add new values to an EntityListWrapper is by using the "[]" operator:

$wrapper->field_example[] = $new_value;

This creates a new entry and assigns it the value. With this methods, the delta (the offset within the list of value) is created automatically. You can also set the offset yourself if you wish. Any of the three following methods are equivalent:

$wrapper->field_example[$delta] = $new_value;
$wrapper->field_example->offsetSet($delta, $new_value);
$wrapper->field_example->get($delta)->set($new_value);

In all three cases this will overwrite values if the delta already exists, and create a new entry if not.

You could also directly set an array of value on the field itself. Both of the methods are equivalent:

$value = array
  0 => array('property_example' => 'hello'),
  1 => array('property_example' => 'world')
);
$wrapper->field_example = $value;
$wrapper->field_example->set($value);

However this requires you to know the internal structure of the field you're assigning to as you're not using the field's metadata wrapper.

Finally you can empty a multi value field by setting it to an empty value. All three methods are equivalent :

$wrapper->field_example->set();
$wrapper->field_example = array();
$wrapper->field_example = NULL;


SOAP with custom form select I'm getting results from a SOAP call, but cannot display the values in a  select list on my custom module.
This is a part of my code:

foreach($sxml2->NewDataSet->DepCity as $item) {
    $fromName = $item->Name;
    echo '
' . $fromName . '
'; //It displays correctly

    $form['from'] = array(
        '#type' => 'select',
        '#title' => t('From'),
        '#options' => $fromName,
    );
}

$sxml2 is a simplexml load string result and it's display correctly.
When I echo the result from the loop ($fromName), I'm getting all the strings properly, but If I try to put that variable in a custom form select, it doesn't display any data.

How can I get the results in a Drupal form select?

EDIT:

I've tried with this, but it still doesn't display anything in that select.

echo '
';
print_r($sxml2); //The whole simpleXML object with arrays is displaying properly
echo '
';

$options = array();
foreach($sxml2->NewDataSet->DepCity as $item) {
  $options[$item->Name] = $item->Name;
  echo '
' . $item->Name . '
'; //It displays correctly

}

$form['from'] = array(
  '#type' => 'select',
  '#title' => t('From'),
  '#options' => $options, //It doesn't display the data
);

The #options property should be an array of key value pairs (the key is the <option>'s value attribute, the value is the content of that tag), so:

$options = array();
foreach($sxml2->NewDataSet->DepCity as $item) {
  $options[$item->Name] = $item->Name;
}

$form['from'] = array(
  '#type' => 'select',
  '#title' => t('From'),
  '#options' => $options,
);

That's just for demonstration, you may wish to use something other than a name for the option key - it's the sort of thing that would clash easily.


How to restrict a page to a group of people? I am trying to figure out how I can lock down a page (part of my site) to a list of users that I have in another MySQL DB.

Ideally I would like to call the DB and see if the user has access each time they login. Is there any modules that would do this? Or has anyone done anything similar before.

You can add the secondary database to Drupal by following this tutorial: https://www.drupal.org/node/18429

I would probably run a hook_node_view so that it's called before rendering the node and adding your custom logic there.


Add preprocess to content within body field I need to be able to wrap an anchor tag with rel="shadowbox" and href with the path to the image on all img tags that are inserted into the body field of a node. I think I can somehow do this with preprocess?

I realise that I can have a field of images and do it that way, though the client wants the images within the body text itself.

Any advice would be much appreciated.

There's a couple different ways one could go about this; I think the most elegant solution could be a text filter.

/**
 * Implements hook_filter_info().
 */
function MODULE_filter_info() {
  $filters = array();

  $filters['shadowbox'] = array(
    'title' => t('Image Shadowbox'),
    'description' => t('Wraps images in anchor tags.'),
    'process callback' => 'MODULE_shadowbox_cb',
  );

  return $filters;
}

Then, the callback:

/**
 * Image shadowbox callback.
 *
 * @param string $text
 *   The text to be parsed.
 * @param object $filter
 *   The filter, which includes context about which format is being used.
 *
 * @return string
 *   The replaced content.
 */
function MODULE_shadowbox_cb($text, $filter) {
  $ret_val = $text;
  // Logic goes here.
  return $ret_val;
}

You'll need to enable the filter:

/admin/config/content/formats/full_html
/admin/config/content/formats/filtered_html

Now, for the content of the callback; you could use a regular expression. https://stackoverflow.com/a/4456866/4619035 is an example for exactly this use case. The downside of regular expressions with HTML is that they're fragile, especially with potentially malformed code. A workaround would be to sequence the filter after anything that cleans up HTML.

Alternatively, use DOM to manipulate the content - https://stackoverflow.com/questions/18316527/php-dom-wrap-image-in-link-and-add-span-before-image-tag describes this approach well.


'drush' is appended to each path breaking its commands I don't normally use Drush on Windows, but tried it and noticed that it appends drush as a kind of root directory for any action, thus breaking said action.

For example, drush dd gives:

  The command could not be executed successfully (returned: 'Path/To/Composer/vendor/drush/drush/drush' is not recognized as an internal or external command, operable program or batch file. , code: 1)

The correct path is Path/To/Composer/vendor/drush/drush.

When running drush en mymodule, the debug information contains the following.

  [preflight] Alias paths: drupal\site\root/drush/sites,drupal/site/root/drush/sites

drupal/site/root/sites I think makes more sense.

The error is Command pm:enable was not found.

Maybe this is a coincidence and the two are unrelated, but how does one configure Drush directories?

The Drush version is 9.5.2.

I haven't used Drush under Windows, but something tells me that the problem could be solved by by editing the path to the Drush executable, perhaps in a Windows environment variable.


What can not be done by the Panels module without using the Panelizer module? Is there anything that can not be done by the Panels module without the Panelizer module?

I'm just starting to learn Panels module and I faced Panelizer.

Note: I installed and applied this module but the Edit in-place that was selected has gone. Is there any conflict?

To answer your question, as in the 'title' of your question, consider reviewing the article about Creating Specialized Layouts with Panelizer. Here is part of what is written in it, and which I think are key features of Panelizer that you can't do with only the Panels module:

  Many users of Panels have taken advantage of the Panel Nodes sub-module to create customized layouts for nodes. Panelizer does that and takes things a giant step further; by integrating with Drupal 7's entity system, it can create custom layouts for any entity item.

  Panelizer was initially created to allow for one node to be displayed differently than any other node on the system. This allows content creators to be just about as creative with the look and feel of each unique piece of content as they would like.

Some more suggestions about tutorials that you may want to checkout:

Manage Drupal Content Layout with Panelizer.
Architecting Landing pages using Panelizer.

Regarding the Edit-In-Place (IPE, or In-Place-Editor), refer to what's mentioned also in Working with Panelizer combining panels and node displays, i.e.:

  Panelizer fully supports the IPE (In Place Editor) meaning that panelized nodes can enable the alternative directly editable panel.

The question about "Enabled Panels In-Place Editor module but cant see the edit icon" may contain other interesting information about IPE, with topics related to:

Clearing the cache.
Renderer mode.
Permissions.


In a Quick Tabs module what does this display do in a TAB TYPE view? There are two options in my Quick Tabs settings:

display:Master
block:sid(depends on the view you have selected)

I want to know their individual effects on output.

I would recommend reading this post regarding purpose of Master Display in Views. It contains the standard settings for a view that take a effect when you create a new display in the view. If you don't have specific settings differing from master display in your other displays you could (and maybe should) use it in the Quicktab.


How do I add a meta tag when creating a node via REST API? So I have this code, using Guzzle POSTing to create node via Drupal REST API.
No error, but the field_meta_tags value is empty  on the node created (still using default [node:summary] for the meta description).

$node = array(
'title' => array(0 => array('value' => 'asd')),
'type' => array(0 => array('target_id' => 'page')),
'path' => array(0 => array('alias' => $pathalias)),
'field_meta_tags' => array(
  'title' => 'asd',
  'description' => 'asd',
  'keywords' => 'asd',
),
'body' => array(0 => array('value' => 'huehuehue')),
);

$response = $client->post($base_url . '/entity/node', array(
  'cookies' => $jar,
  'query' => array(
    '_format' => 'json',
  ),
  'headers' => array(
    'Accept' => 'application/json',
    'Content-Type' => 'application/json',
    'X-CSRF-Token' => $csrf_token,
  ),
  'json' => $node
));

I also try using array structure like this:

'field_meta_tags' => array(0 => array(
  'title' => 'asd',
  'description' => 'asd',
  'keywords' => 'asd,
)),

But still no luck.

What is the correct format to provide metatag value? Or is there another thing that I might need to check?

I copy/paste the following snippets from the readme file of the metatag module.
I can see that you are missing the serialize function in your solution.
Hopefully that helps you.

Programmatically assign meta tags to an entity
--------------------------------------------------------------------------------
There are two ways to assign an entity's meta tags in custom module. Both
scenarios require a "Metatag" field be added to the entity's field settings, the
field name "field_meta_tags" is used but this is completely arbitrary.

Option 1:

  $entity_type = 'node';
  $values = [
    'nid' => NULL,
    'type' => 'article',
    'title' => 'Testing metatag creation',
    'uid' => 1,
    'status' => TRUE,
    'field_meta_tags' => serialize([
      'title' => 'Some title',
      'description' => 'Some description.',
      'keywords' => 'Some,Keywords',
    ]),
  ];
  $node = \Drupal::entityTypeManager()->getStorage($entity_type)->create($values);
  $node->save();

Option 2:

  $node = Node::create(array(
    'type' => article,
    'langcode' => 'en',
    'status' => 1,
    'uid' => 1,
  ));
  $node->set('title', 'Testing metatag creation');
  $node->set('field_meta_tags', serialize([
    'title' => 'Some title',
    'description' => 'Some description.',
    'keywords' => 'Some,Keywords',
  ]));
  $node->save();

In both examples, the custom meta tag values will still be merged with the
values defined via the global defaults prior to being output - it is not
necessary to copy each value to the new record.


How to create URL alias for node edit page Pathauto can create URL alias for node view page, for example, URL from node/nid to project/nid (project is a name of content type), but the link to the edit page is not /project/nid/edit, but /node/nid/edit.

How could I create URL alias (like: /project/nid/edit) for node edit page in Drupal 8?

Use a src/Routing/RouteSubscriber.php file in your module.

namespace Drupal\example\Routing;

use Drupal\Core\Routing\RouteSubscriberBase;
use Symfony\Component\Routing\RouteCollection;

/**
 * Listens to the dynamic route events.
 */
class RouteSubscriber extends RouteSubscriberBase {

  /**
   * {@inheritdoc}
   */
  protected function alterRoutes(RouteCollection $collection) {
    if ($route = $collection->get('entity.node.edit_form')) {
      $route->setPath('/project/{node}/edit');
    }
  }

}

Use a example.services.yml file in your module (if the module is named example).

services:
  example.route_subscriber:
    class: Drupal\example\Routing\RouteSubscriber
    tags:
      - { name: event_subscriber }

https://www.drupal.org/docs/8/api/routing-system/altering-existing-routes-and-adding-new-routes-based-on-dynamic-ones


Finding data using MySQL queries in the Node tables Outside of the Drupal system I am trying to get user data based off of the user table and export this information into a CSV.

I'm not quite understanding how the Node table system works and where to get my data let alone how to Join it in MySQL manually.

I have my users table, the standard users table from Drupal. I'm trying to get data from quite a few tables for the user, a simple one line profile type data per user. Under a regular database structure setup it would be as simple as a few joins to the right xref ids and tables and you're good to go. It's not quite working here of course.

One of the tables in question is called field_data_field_sexo_meta. This holds the information if the user is Male or Female.

As you can see the field field_sexo_meta_value holds the information. But I do now know how to join this table to the user ID.

I've tried quite a few tables to get the user ID to link to this entity_id field but nothing as of yet has worked. For instance I've tried field_data_field_paciente which has these fields:

The last field there is the uid field, but this doesn't link anything either.

I've also tried linking to the column uid in the nodes table and a type = 'termometro' but also it doesn't link to anything and I get null on my joins.

So evidently I'm missing which table links the field_data_field tables to the users.

This is my current query:

SELECT
  u.uid,
  u.name,
  u.mail,
  ur.rid,
  n.field_su_nutricionista_es_uid,
  s.field_sexo_meta_value
FROM users AS u
  LEFT JOIN users_roles ur
    ON (ur.uid = u.uid)
  LEFT JOIN field_data_field_usted_es p
    ON (p.field_usted_es_uid = u.uid)
  LEFT JOIN field_data_field_su_nutricionista_es n
    ON (n.entity_id = p.entity_id)
  LEFT JOIN field_data_field_sexo_meta s
    ON (s.entity_id = p.entity_id)
WHERE ur.rid = 5
     OR ur.rid = 4
GROUP BY uid

The concept that you are missing is that field data can be on any Drupal entity, nodes, users, etc.  This means that when you JOIN, you need to add in some additional clauses.  In particular, you need to check the entity type in the field data, as the entity ID isn't unique across entity types.  You also need to check that the field value isn't deleted.  So, you would have something like

LEFT JOIN field_data_field_usted_es p
  ON p.entity_id = u.uid AND p.entity_type = 'user' AND p.deleted = 0

Those three columns are typically all on need to JOIN ON.  The rest of the columns would be what you return in the query, or use in a WHERE.

Most of the time, it is easiest to build up a query with Views, preview the SQL, and then use that as your starting point for a query outside of Drupal.

In your case, you could also use Views Data Export to generate your CSV inside Drupal itself.


Using Drupal's session inside a PHP script I need to pass parameters from a Drupal page to a PHP script.
There's no way to pass that directly and I need to use SESSIONS.
I've searched around and added this at the top of the script:

define('DRUPAL_ROOT', getcwd());
require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_SESSION);

With that I can use Drupal's session but I'm getting this error:

Warning: session_start(): Cannot send session cache limiter - headers already sent

It's not so bad since it's just a warning and I can use CSS to make it not visible to the user. But I was wondering if there is a cleaner way to do so.

In instances where I've had to do things like this I've done the following. It's worked for D6/D7 without any warnings for me.

  $current_path = getcwd(); //Current app path

  //Remove any HTTP headers/output
  header_remove();
  ob_clean();

  //Bootstrap Drupal w/ dir change
  //$drupal_root being the root Drupal install path
  define('DRUPAL_ROOT', $drupal_root);
  chdir($drupal_root);
  require_once "$drupal_root/includes/bootstrap.inc";

  /*Execute Code Dependant on Drupal Environment */

  chdir($current_path); //Return to existing app path


Is it possible to get rid of the Javascript code? All nodes (Drupal 7) contain the following code:

<script type="text/javascript" src="http://localhost:8080/myfeodor.de/misc/jquery.js?v=1.4.4"></script>
<script type="text/javascript" src="http://localhost:8080/myfeodor.de/misc/jquery.once.js?v=1.2"></script>
<script type="text/javascript" src="http://localhost:8080/myfeodor.de/misc/drupal.js?nxe6cr"></script>
<script type="text/javascript" src="http://localhost:8080/myfeodor.de/sites/default/files/languages/de_HizaMms-3Ux-y0M1w9o2_EvSFCBziqwcKzQq9_kzJ78.js?nxe6cr"></script>
<script type="text/javascript">
    <!--//--><![CDATA[//><!--
    jQuery.extend(Drupal.settings, {
        "basePath": "\/myfeodor.de\/",
        "pathPrefix": "",
        "ajaxPageState": {
            "theme": "my_garland",
            "theme_token": "WTVBB9vMIjxgWuVheFjYXjuvpo1TgahCH62PRBBFGrA",
                "js": {
                "misc\/jquery.js": 1,
                "misc\/jquery.once.js": 1,
                "misc\/drupal.js": 1,
                "public:\/\/languages\/de_HizaMms-3Ux-y0M1w9o2_EvSFCBziqwcKzQq9_kzJ78.js": 1
            },
            "css": {
                "modules\/system\/system.base.css": 1,
                "modules\/system\/system.menus.css": 1,
                "modules\/system\/system.messages.css": 1,
                "modules\/system\/system.theme.css": 1,
                "modules\/comment\/comment.css": 1,
                "modules\/field\/theme\/field.css": 1,
                "modules\/node\/node.css": 1,
                "modules\/search\/search.css": 1,
                "modules\/user\/user.css": 1,
                "sites\/all\/themes\/my_garland\/style.css": 1,
                "sites\/all\/themes\/my_garland\/print.css": 1,
                "sites\/all\/themes\/my_garland\/fix-ie.css": 1
            }
        }
    });
    //--><!]]>
</script>

The file de_HizaMms-3Ux-y0M1w9o2_EvSFCBziqwcKzQq9_kzJ78.js
contains an associative array where error messages are translated.
But this appears not to be necessary since the page works also with
scripting deactivated in the browser.

This is WAMP, but under Linux the same code appears.

This code is also present if one is only reading without being logged in.
Is is possible to avoid this scripting?

Drupal 6 has been Javascript-clean for readers.

At drupal.org user Jaypan propsed to implement a new module (named e.g. killjs) which would have to implement hook_js_alter()

<?php
function killjs_js_alter(&$javascript) {
  // Insert code to check whether JS should be killed or not.
  $javascript = array();
}
?>

This, however, would be very laborious for non-experts since it would be necessary to do a more or less complete analysis of the Drupal code base first. User leymannx proposed a solution which may be realized without developing a new module:

Javascript is deactivated only for a specific theme, here called custom_garland.
Copy file modules/system/html.tpl.php into the customized theme folder as /sites/all/themes/custom_garland/html.tpl.php.
In the copied file html.tpl.php delete the line <?php print $scripts; ?>.
Clear the drupal cache.
Select custom_garland as default theme.

Now for guests the page is clean of Javascript! In the backplane, Javascript is still active due to file maintenance-page.tpl.php. This means one can still adust the Garland/Bartik colors or drag blocks.

For me, the maintenance mode works with the above modified theme. Stefan Korn presented a refinement of this apporoach where JavaScript is fully activated for users which are logged in.


How to enable Node editing in full mode? Is there a way to expose selected node fields so that they are directly editable when the node is being viewed?

I want visitors of my site to be able to type some context into a text area, select relevant taxonomy terms etc. In other words, to do what you would normally be able to do in node-edit mode.
My node is also a Commerce product display. I need the users to input their data, also select their relevant product information and submit all on the same page.

I installed the Edit module, but I couldn't find how to expose the fields for editing.

How can I achieve what I am trying to do?

Yes there is a module which can enable this functionality - Editablefields.

Module page says itself --

  This module allows CCK fields to be edited on a node's display (e.g.
  at node/123), not just on the node edit pages (e.g. node/123/edit). It
  also works within views etc. Anywhere a 'formatter' can be selected,
  you can select editable (or click to edit).

I have used this module for edit fields at views not at node, but I am sure you can achieve your requirement.


How do I turn off notices and warnings? I am developing a site and am getting a few warning messages that cover the page. I want to deal with them later and turn them off for now so I can concentrate on theming.

I've tried going to Config>>Development>>Logging and turning them off from there, but although it says the save was successful refreshing the pages shows the 'All Messages' option is still selected and the messages still appear on the front end.

I searched how to do this in Drush and tried drush vset -y error_level 0 and drush vset error_level 0 and got the response "error_level was set to 0." but this too had no affect.

I've tried clearning my cache after each attempt as well.

Would anyone know how to achieve this?

If you don't want to add CSS you can comment out the $messages variable in your page.tpl.php file while you are developing.


How can I check a Rules condition to see if the Statuses sender and recipient are the same? I am using "Execute custom PHP" as a condition in a Rule which is being triggered when a new Status is saved. Here is the PHP I am using, it keeps causing "Trying to get property of non-object" errors whenever I create a new status:

if($sender->uid == $recipient-id){
return TRUE;
} else {
return FALSE;
}

Basically what I am trying to do is detect cases when the sender is sending a status message to himself so I can use an appropriate Rules action, and also the opposite:

if($sender->uid != $recipient-id){
return TRUE;
} else {
return FALSE;
}

I have tried a number of different variable combinations but I can't work out what I am doing wrong. Any suggestions?

This should do what you want.

if($status->sender == $status->recipient) {
  drupal_set_message('A match');
}
else{
  drupal_set_message('Not a match');
}

Rules Code

{ "rules_status_test" : {
    "LABEL" : "Status Test",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "php", "rules", "fbss_rules" ],
    "ON" : { "statuses_save" : [] },
    "IF" : [
      { "php_eval" : { "code" : "if($status-\u003Esender == $status-\u003Erecipient) {\r\n  drupal_set_message(\u0027A match\u0027);\r\n}\r\nelse{\r\n  drupal_set_message(\u0027Not a match\u0027);\r\n}" } }
    ],
    "DO" : []
  }
}


views webform submission username I would like to have webform submission username using views.
Add fields > webform submissions: user
The result is uid (user id number)

How can I have username login name instead of uid ?

'Username' as a field is not available to webform as it is not stored in the webform submission.

You need to add a Relationship to the User using the UID and then the User Name will be available to you in the fields section.

See more about relationships in this video


Return Table and Form in page callback I have a problem returning table and form in page callback at the same time it only works if one of them only returned.

function _table_maps(){
$query = db_select('maps','m');

$result = $query->fields('m')
                ->extend('TableSort')
                ->extend('PagerDefault')
                ->limit(50)
                ->execute();

$header = array('Title','Longitude','Latitude','Description');

$rows = array();
while($data = $result->fetchAssoc())
{
    $rows[] = array(
        $data['maps_title'],
        $data['maps_long'],
        $data['maps_lat'],
        $data['maps_desc']
    );
}

$output = theme_table(
            array(
                "header" => $header,
                "rows" => $rows,
                "attributes" => array(),
                "sticky" => true,
                "caption" => "",
                "colgroups" => array(),
                "empty" => t("Table has no row!")
                )
            ).theme("pager");

return $output;

}

function aieadmin_map_form($form_state){

$form['title'] = array(
    '#type' => 'textfield',
    '#title' => t('Title'),
    '#size' => 30,
    '#maxlength' => 64,
    '#description' => t('Enter the Title For the Location'),
);

$form['long'] = array(
    '#type' => 'textfield',
    '#title' => t('Longitude'),
    '#size' => 30,
    '#maxlength' => 64,
    '#description' => t('Enter the Longitude For the Location'),
);

$form['lat'] = array(
    '#type' => 'textfield',
    '#title' => t('Latitude'),
    '#size' => 30,
    '#maxlength' => 64,
    '#description' => t('Enter the Latitude For the Location'),
);

$form['description'] = array(
    '#type' => 'textarea',
    '#title' => t('Describe it'),
    '#cols' => 60,
    '#rows' => 5,
    '#description' => t('Location description.'),
);

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

return $form;
}

/*******Page Callbacks********/

function aieadmin_callback_mod(){
$page = _table_maps();
$page .= drupal_get_form('aieadmin_map_form');
return $page;
}

try this in the form

$custom_table = _table_maps();

$form['some_information'] = array(
  '#markup' => $custom_table,
  '#prefix' => '
',
  '#suffix' => '
',
);


Make a node field read only after the node has been created I'm building a Drupal 8 module which will create several content types (with several fields) when the module is installed. The content types, field storages field instances, form displays & view displays are created with yml files in mymodule/config/install.

More details on the content types and fields:

Let there are two node types, A and B.
B has field called reference which is required, can have 1 value and the reference is to a node of type A. So basically B always has exactly one parent of type A.

What I want to do is to make the reference field read-only after the node is created.

In Drupal 7 I did this with Form API and hook_node_validate basically as follows:

I first checked if the form submission was for a new node or an existing node
If it was an existing node, I loaded the node (which is the node before the form submission at hand) and compared the value of the form submission to the value found on the actual node.
If the values were not the same, I returned an error.

Now, in Drupal 8 we have the Validation API which is really good thing because it kicks in with also other mechanisms than form submits. I'm only wondering how to implement the read-only locking described above.

Should I create a Constraint Plugin which would do similar loading of the previous version like I explained above and add that constraint with hook_entity_bundle_field_info_alter() or is there some other way?

Edit: Just to clarify, I'm interested to make the reference field non-editable on data level so that the value can't be changed even if updating the node programmatically. In other words, just making the field read-only on UI level on node edit form is not enough.

After educating myself on the Validation API, here's an example how to add the constraint to validate that the value of an entity reference field has not been changed.

Note: As pointed out by Ivan Jaros, this constraint is not validated if some module is programmatically saving entities without validating the entities first via Validation API.

Add a new constraint plugin.

/**
 * @file
 * Contains \Drupal\example\Plugin\Validation\Constraint\ValueNotChangedConstraint.
 */

namespace Drupal\example\Plugin\Validation\Constraint;

use Symfony\Component\Validator\Constraint;

/**
 * Constraint for checking that the value has not been changed.
 *
 * @Constraint(
 *   id = "ValueNotChanged",
 *   label = @Translation("Value has not changed", context = "Validation"),
 *   type = { "string", "entity:node" }
 * )
 */
class ValueNotChangedConstraint extends Constraint {

  /**
   * Message shown when the validation fails.
   *
   * @var string
   */
  public $message = 'Reference value can not be changed.';

}

Add validator for this constraint.

/**
 * @file
 * Contains \Drupal\example\Plugin\Validation\Constraint\ValueNotChangedConstraintValidator.
 */

namespace Drupal\example\Plugin\Validation\Constraint;

use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\Validator\Violation\ConstraintViolationBuilderInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\Field\EntityReferenceFieldItemListInterface;
use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;

/**
 * Validates the ValueNotChangedConstraint.
 */
class ValueNotChangedConstraintValidator extends ConstraintValidator implements ContainerInjectionInterface {

  protected $entityTypeManager;

  /**
   * Constructor.
   *
   * @param EntityTypeManagerInterface $entity_type_manager
   *   EntityTypeManager service for loading entities.
   */
  public function __construct(EntityTypeManagerInterface $entity_type_manager) {
    $this->entityTypeManager  = $entity_type_manager;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    // Instantiates this class.
    return new static(
      // Load the service required to construct this class.
      $container->get('entity_type.manager')
    );
  }

  /**
   * Validator 2.5 and upwards compatible execution context.
   *
   * @var \Symfony\Component\Validator\Context\ExecutionContextInterface
   */
  protected $context;

  /**
   * {@inheritdoc}
   */
  public function validate($data, Constraint $constraint) {
    $violation = $this->validateValueNotChanged($data, $constraint);
    if ($violation instanceof ConstraintViolationBuilderInterface) {
      $violation->addViolation();
    }
    return;
  }

  /**
   * Validates that the value is the same than previously.
   *
   * @param EntityReferenceFieldItemListInterface $data
   *   List of referenced entities.
   * @param Constraint $constraint
   *   Our constraint.
   *
   * @return \Symfony\Component\Validator\Violation\ConstraintViolationBuilderInterface
   */
  protected function validateValueNotChanged(EntityReferenceFieldItemListInterface $data, Constraint $constraint) {
    // Get the field name of the field we're validating.
    $field_name = $data->getFieldDefinition()->get('field_name');

    // Get the entity the field belongs to.
    $parent_id = $data->getEntity()->id();

    // Entities that are about to be created don't have an ID at this point.
    // We're only interested in existing entities.
    if ($parent_id) {

      // Load the parent node from the database. The new updates are not saved
      // yet so this will be the "old" version of the entity.
      $parent = $this->entityTypeManager->getStorage('node')->load($parent_id);

      // Get the old value we want to compare against.
      $old_value = $parent->get($field_name);

      // Compare the field item lists.
      if (!$old_value->equals($data)) {
        return $this->context->buildViolation($constraint->message);
      }
    }
  }

}

Add the constraint to the desired field with hook_entity_bundle_field_info_alter().

/**
 * Implemeantion of hook_entity_bundle_field_info_alter().
 *
 * Adds constraint to field_example_reference field.
 */
function example_entity_bundle_field_info_alter(&$fields, \Drupal\Core\Entity\EntityTypeInterface $entity_type, $bundle){
  switch ($bundle) {
    case 'our_content_type':
      $fields['field_example_reference']->addConstraint('ValueNotChanged');
      break;
  }
}


View filtered by taxonomy term - is there a better way? I am using Drupal 7.14 and I'm wrestling with filtering my content type based on taxonomy terms. I have a solution but I'm sure there must be a better way!

I have a content type called News. It has a taxonomy field so I can categorize the postings to it. I currently have 4 different taxonomy terms.

I also have a view that shows a page with all the News item teasers and links to the full article.

I have a menu on the side of the News page with links to each of the categories. Clicking on one of these links will show a page of teasers for that particular taxonomy term.

I have implemented the above as follows:
In my News view I have added a display page for each of the taxonomy terms. On the same form I changed the "Page Settings" to set the path to the path of the taxonomy term (this overrides the default taxonomy view for the term). I also change the "Filter Criteria" and add a filter for the particular taxonomy term.

I then built a menu using the taxonomy term paths and made it appear on the News content type pages. Each item in the menu points at its taxonomy term path. When the user clicks on a menu item it correctly shows the view filtered for that category. Note: it does not show the default taxonomy term page because I set the path to the taxonomy term in my view and this takes priority.

I have also overridden the template for my view by adding a custom template file called views-view-fields--news.tpl.php. This template is used for the full view and each of the filtered views.

The above does work but is there a better cleaner way? It is quite tedious to add a new category as I need to manually update the view to add a new display for the new category and I then need to update the menu of categories.

Many Thanks.

Create a view with an exposed filter for each News category.
Under its settings, in Admin, there is a Filter identifier which can be changed. This goes after ? in the URL.
Build your menu to link to the new view and add the category after the filter identifier.

The benefit of this is you can do it with any view so your tpl will work. And users can change category quickly using the dropdown menu. Or you can hide the exposed filter with CSS and make them use the menu.


Allow users to use embedded HTML tags in custom blocks I'm using CKEditor in Drupal 8 and the client wants to write HTML that contains embedded tags like so

<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">

</button>

Unfortunately, Drupal ends up mangling the code to something like this

<button aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation" class="navbar-toggler" data-target="#navbarSupportedContent" data-toggle="collapse" type="button"></button>

&nbsp;

<button aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation" class="navbar-toggler" data-target="#navbarSupportedContent" data-toggle="collapse" type="button"></button>

I think this is in an attempt to prevent XSS but I'm not totally sure.

Should I be able to allow the user to embed tags? If so, how could I go about doing this?

The W3C specs (https://www.w3.org/TR/2011/WD-html5-20110525/the-button-element.html#the-button-element) show that a button allows phrasing content (https://www.w3.org/TR/2011/WD-html5-20110525/content-models.html#phrasing-content), e.g. a <span> to be placed inside a <button>, but not a <div>, so your WYSIWYG editor is correctly rearranging the elements.

Perhaps you could rework your code to allow for a <span> to be used inside the <button> and style that instead.


Change published date to 12 hour time Right now my nodes say published by "author name 19:02". How can I change it to display 12 hour time 7:02?

It uses the default date format of the site, which is medium. You can configure that at admin/settings/date-time and choose a format which uses am/pm.

You can also implement hook_preprocess_node() in your theme or module and then override the 'submitted' variable set by template_preprocess_node(). That allows you to use a different date format just there.


Roles, Groups or What? We use Drupal as the basis for a student information website. We have 3 intakes of students a year and I would like to be able to allocate students various rights based on roles, primarily if they are

a current student,
an applying student,
or an alumni.

But I would also like to be able to identify them by what class they did.

Should I create a new role for each new intake?
Should I use groups?
Is there an alternative method I should use?

Best and simple way is to assigning Roles.

Users, roles and permissions


Dynamic results label for Views with Taxonomy Filters I'm using Drupal 8 Views with Better Exposed Filters to filter a custom content type by two custom taxonomy vocabularies.

Results are filtered by:

Content: Published (=Yes),
Content: Content type (in Custom-Type),
Content: Taxonomy Vocabulary1 (exposed),
Content: Taxonomy Vocabulary2 (exposed),

The filters are working as desired, and the "No results behavior" generates a label on the results (technically, it's a Global: Text area, not a label) that says:

  No results found

When there are results, the client requires a similarly-formatted label on the results that will say something like this:

  Viewing 12 of 42 results for: [Vocabulary1 Term] with [Vocabulary2 Term]

Can I accomplish this with Views UI, or should I handle it in the Twig template? Theme suggestions say that the Twig template in use is field--paragraph--field-views--views-reference.html.twig.

NOTE: As a pager, I'm using Infinite Scroll to reveal 12 new results at a time. At the bottom of each screen full of results, there's a button that says:

  Load More [Custom-Type]s

Infinite Scroll options are very similar to what I want:

  The following tokens are supported:

  @next_page_count -- the next page record count

  @total -- the total amount of results returned from the view

Instead of showing the @next_page_count, I really need the current page count (which will increment by 12 results each time the button is pressed, and by the remainder for the last screenful.) And instead of rendering this text on the button, the client wants it back at the top of the results.

Your question doesn't seem to be related to Better Exposed Filters, BEF only format the actual form elements of the exposed form, not the display of the view results.

You can use the Result summary option you can add to the Header or Footer area in Views. It's under the Global Category, here are the listed tokens:

You may use HTML code in this field. The following tokens are supported:

@start -- the initial record number in the set
@end -- the last record number in the set
@total -- the total records in the set
@label -- the human-readable name of the view
@per_page -- the number of items per page
@current_page -- the current page number
@current_record_count -- the current page record count
@page_count -- the total page count

You can also use the Text area option that comes with some more options, including the arguments from Contextual and Exposed filters (if you turn on the Use replacement tokens from the first row):

view

[view:base-field] - Base field: The base field used for this view.
[view:base-table] - Base table: The base table used for this view.
[view:current-page] - Current page: The current page of results the view is on.
[view:description] - Description: The description of the view.
[view:id] - ID: The machine-readable ID of the view.
[view:items-per-page] - Items per page: The number of items per page.
[view:label] - Label: The label of the view.
[view:page-count] - Page count: The total page count.
[view:title] - Title: The title of current display of the view.
[view:total-rows] - Total rows: The total amount of results returned from the view. The current display will be used.
[view:url] - URL: The URL of the view.

In your case you're filtering by Taxonomy Entity Reference field (that information is directly in the node). But the ER fields only store the ID number of the referenced entity (TID in your case) and not anything else, which mean the Taxonomy term name isn't saved inside the node.

There is some magic done in Views for Taxonomy that makes it seem like the term data is available but those are targeted specific parts. Generally speaking you have to add a Relationship for that ER field in order to pull in data about the referenced entities.

So in you case you need to add the Relatinship for the Color and Size (how ever you have them called), and then add the Taxonomy: Name field for both cases.

Now when you open the Use replacement tokens from the first row option you will see the tokens for those fields that show term Names more directly, something like {{ name_1 }} == Taxonomy term: Name.

You will probably want to use some twig logic when to show it, check for Exposed filter being used.


What are the performance implications of running a frequent simplenews cron task to send emails? In the Simplenews docs there is the following tip:

  The Elysia Cron module (http://drupal.org/project/elysia_cron) can be
  used to start the simplenews cron hook more often than others, so that
  newsletter are sent faster without decreasing site performance due to
  long-running cron hooks.

This is great because it will clear the mail spool without waiting for several cron runs to occur. However what are the performance implications of running this cron task on an ongoing basis with a short interval of say 30 minutes? Especially if a newsletter only gets sent once a month. i.e. My simplenews cron task in running every 30 minutes with nothing to do.

Once every 30 minutes will most likely not cause any issues. I've never used that module before so I can't saw with 100% certainty. If you where to change the frequency from 30 minutes to 1 minute I might start to worry as that could increase your server load.


Entity Form Anonymous Users I am working on entity forms in drupal 7, I want anonymous users to be able to post content and then create an account, the problem is that by the time they create an account, any previous submission is already attached to "anonymous user".

I want to change the code so that when anonymous user posts, their content can be attached to the latest created users

Below is my code so far but it is not working.

if (empty($user->uid))  {
  $result = db_query('SELECT u.uid FROM {user} u ORDER BY u.uid DESC LIMIT :d',array(":d"=>1));
  while ($record = db_fetch_object($result)) {
    $uid = $record->uid; // last created user id .
  }
  $entityform->uid = $uid;
}

You should rather use the following code, but there is a problem I will describe.

if (empty($user->uid))  {
  $entityform->uid = db_next_id(db_query('SELECT MAX(uid) FROM {users}')->fetchField());
}

The problem with that code is that it will use the user ID of the next user account that is being created, which could not be the user who created the entity. This is true when:

The anonymous user creates an entity instance
After the code I shown is executed, a new user creates an account
The anonymous user who created the entity instance creates an account

I would rather do the following:

When an anonymous user creates an entity instance, asks for an email address
Save the email address as part of the entity

When a user account is created, and the user logs in the very first time:

Search for any entity instance where the email address is equal to the email address used for the user account
Change the user ID with the user ID associated to that email address

Instead of the email address, you could ask anything else, as long as it is clear to the user that the entered value is requested when s/he creates an account to assign to her/his account any entity s/he creates. As the email address is required to create a user account, I would ask the email address to the anonymous users who creates entities.


Commerce Kickstart subtheme? Hi I'd like to alter some of the CSS on the Commerce Kickstart theme, but when I try to create a sub theme by following these instructions https://drupal.org/node/819170 I end up with an unformatted theme. This isn't what I want, I want to alter the current Kickstart theme but from the sites/all/themes subfolder.

I've created a subtheme based on omega, omega_kickstart, but these leave me with no css formatting at all.

I've copied the profiles\commerce_kickstart\themes\omega_kickstart folder to my sites/all/themes, renamed the info file etc.. this left me with partial formatting.

one thing I noticed from the dom entries is css come from various folders, i.e.
alpha, omega.

anyone know how to create a successful subtheme here?

I followed all 10 steps at this article in detail to get a fully functional boilerplate subtheme for the Commerce Kickstart Theme in just a couple of minutes.

In case the article goes offline, you can find a mirror here.

Info :

  How to subtheme the Omega Kickstart Theme

  Posted by sja1 on August 4, 2013 at 12:31pm

  Hi guys, first off thanks
  for the all the work you've put into make Commerce Kickstart such an
  oustanding platform. I wanted to create this issue in order to help
  those who are having trouble creating a subtheme of the commerce
  kickstart theme. There is good documentation for subtheming omega, but
  I had a harder time finding information on subtheming a subtheme of
  omega (Commerce Kickstart is a subtheme of Omega Kickstart, which is a
  subtheme of Omega). With some trial and error I have come up with the
  following procedure which is working for me, and thought I'd present
  it to the community for others to benefit from and hopefully improve
  upon. All comments welcome.

  Steps to subtheme Commerce Kickstart theme

  [ For the detailed 10 steps, go to one of the two provided links ]


Get the site base url in template.php How do i get the base url in template.php?

None of the below works.

global $base_url;
global $base_path;
global $base_root;

You can use the base_path() function which should always work.

To be honest though it just returns $GLOBALS['base_path'] so your global $base_path statement should work fine.


How can I set a message if db_delete deleted one or more rows In drupal 6 my code worked like this:

if (db_query("DELETE FROM {,ymodule_fields} WHERE conid = %d", $conid)) {
  drupal_set_message(t("Deleted fields."));
}

Now I'm supposed to use db_delete.

Will this code work?  I know db_delete returns a DeleteQuery object so I'm assuming it's going to evaluate to true every time.  I can't test my module yet because I'm doing a lot of work updating the code that creates cck fields to use core fields.  Is DeleteQuery a PDO that has the rowCount method?

if (db_delete('mymodule_fields')
  ->condition('conid', $conid)
  ->execute()) {
  drupal_set_message(t("Deleted Fields."));
}

Sure, db_delete() returns an object so you can continue working with the object, but the last method called (the method whose return value your conditional is really checking) in your statement is Query::execute, which returns boolean TRUE or FALSE indicating whether the query worked. So, ultimately the whole statement:

db_delete('drealty_fields')
  ->condition('conid', $conid)
  ->execute();

Should return TRUE or FALSE since you're ultimately executing the Query::execute method. The workflow is just that you call db_delete(), which returns an object, Query::condition, returns an object, then Query::execute returns boolean, but your conditional is just getting and checking the return value of the last method called - execute - rather than the return value of db_delete(). Essentially, the db_delete() return value was already operated on by continuing with a condition, and the condition's return value is inconsequential because it was operated on by execute, thus the execute's return value is the only one really getting sent back to the if statement. Make sense?

So, in essence each of these examples should give the same results:

$query = db_delete('drealty_fields');
$query->condition('conid', $conid);
$success = $query->execute();
if ($success) {
  // Do something.
}

$query = db_delete('drealty_fields');
$query->condition('conid', $conid);
if ($query->execute()) {
  // Do something.
}

if (db_delete('drealty_field's)->condition('conid', $conid)->execute()) {
  // Do something.
}


How can I make the Book Navigation also show the Summary of the Child Page? Currently the Book module will create a navigation of links to each of it's children pages. I need that navigation to also include a teaser or summary from the child page.

This is for Drupal 7.

--- Potentially not the best solution -----

I haven't tried this but looking at api.drupal.org I think you should be looking at overriding  template_preprocess_book_navigation the variables processed in this preprocess are used in book-navigation.tpl.php ( u are interested in changing output of $tree which is an unordered list by default) I think you can override the preprocess for book_navigation and use a different callback for $variables['tree'] instead of book_children. Your new callback would be based on book_children but additionally load teaser for those child pages.

I myself would like to see a better solution for this coz sometimes core design decisions are not what we need and would like to know if there are better solutions other than overriding theme engine and replacing a call to a core function with a custom one ( in this case book_children ) Let me know if you find a better solution or if this works.

Needless to say this will affect output of all book pages where book-navigation.tpl.php is used.

Cheers


Services and translated nodes I have a website where three languages are present. I am requesting nodes through the Services API endpoint and that part is working well.

When requesting a node via JSON, how does the API let me know the requested node ID is associated to translated nodes?

I know the translated nodes do contain a "tnid" record of the original node, but the original node doesn't have anything to indicate that there are translated nodes.

To know if there are translations available for particular node, You need to call the below function to get the available translation nodes.

$translations = translation_node_get_translations($node->tnid);

Ref : Function translation_node_get_translations

So what you can do is, You can call this function when you are returning node from service API along with translated nodes.

Hope this will help.

Thanks


How do call the template for a module block My goal is create a custom block that uses a twig template that you can pass info to via the theme function like so.

  public function build() {
    return array(
      '#type' => 'markup',
      '#markup' => $this->siteContent(),
    );
  }

  public function siteContent() {

    $source_text = some_function_returning_html_from_user();

    return array(
      '#theme' => 'scadfashblock',
      '#source_text' => $source_text,
    );
  }

I got the above code from a tutorial trying to render a template file for a custom page. The problem is this code throws an error saying that an array can't be returned this way, it must be a string.

I even tried doing it the drupal 7 way...

  public function build() {
    return array(
      '#type' => 'markup',
      '#markup' => $this->siteContent(),
    );
  }

  private function siteContent() {

    $output = array();
    $output['source_text'] = some_function_returning_html_from_user();

    return theme('scadfashblock', $output);
  }

This throws an error:

  Call to undefined function Drupal\<module>\Plugin\Block\theme()

The markup render #type takes a string for its #markup element property, not a render array. However you do not need to wrap your custom theme/template with the markup type.

  public function build() {
    return array(
      '#theme' => 'scadfashblock',
      '#source_text' => $this->siteContent(),
    );
  }

  public function siteContent() {
    return some_function_returning_html_from_user();
  }

Then implement scadfashblock in hook_theme, provide a template_preprocess_scadfashblock and a templates/scadfashblock.html.twig with your markup.


Add field to existing content entity I am trying to add a hidden field to all nodes in my module (for any node type even new ones being created later on). Would this be the correct code?

$field_storage = FieldStorageConfig::loadByName('node', $field_name);

if(empty($field_storage)){
  $field_storage = entity_create('field_storage_config', array(
    'field_name' => $field_name,
    'entity_type' => 'node',
    'type' => 'string',
  ));
  $field_storage->save();
}

 // Add the field, if needed.
$field = FieldConfig::loadByName('node', $node_type, $field_name);

if (empty($field)) {
  $field = entity_create('field_config', array(
    'entity_type' => 'node',
    'field_name' => $field_name,
    'field_storage' => $field_storage,
    'bundle' => $node_type,
    'label' => $label,
  ));
  $field->save();
}

I am just not sure which hook I should put it in. Most are giving me different errors…
Also I want the field to be updated when the title field of a node is changed, which hooks would be the best to get the new title the user types? Or ist there some kind of event one could subscribe to?

Edit:

Your small edit changes this question more than you might think.

You have two ways to solve this.

1) Implement hook_node_type_insert() and create your field config there. You need to be aware of a few things, like config sync, so you need to check $node_type->isSyncing() before making any changes. Note that core stopped doing this for the body field. We do no longer add it automatically to all node types, only when one is created in the UI, as it had undesired side effects.

2) If you really want your field to always exist, no matter the node type, you can add it as a base field, which means it will work similar to the node title for example. See entity_schema_test_entity_base_field_info() for an example or see how content_translation now works which is also using this approach. Be aware that this changes how the schema for your field is then created, it will be part of the node_field_data table and you need to run update.php after installing your module to update the table.

Old answer:

The only hook that you could use for this is hook_install(), so that the field is created when the module is installed.

However, what you really want is to export them as default configuration of your module, I recently explained that in detail here: How to extend the basic user object upon installation?.

I'm going to actively ignore the second question because it has nothing to do with the first one. Create a separate question for that.


Contact form module for different users I am looking for a contact form module for different users logged in to the website.

E.g.,

1) a website that has different authors

2) the user clicks on the author's page there is a contact form for that specific author on their page

Any suggestions?

You should be able to use the core contact form for this.

Basic documentation about setting it up can be found in the user contributed documentation on Drupal.org.

The contact form let you have a site contact form (sent to the default user), and a contact form tied to each individual user. When you enable the latter option, a tab "Contact" will appear when someone visit's that user's page (provided they're permitted to see it).

Individual users may disable other's access to their contact form, but the administrator may override this.

The core contact form can be configured through options and permissions.  It is very flexible, but it may take some tuning to get the exact behavior you want.


How to add id to a block For example I have the code:

function contact_block_view($delta = '') {
$block = array();
switch ($delta) {
  case 'contact_block':
  $block['content'] = drupal_get_form('contact_form');
break;
}
return $block;
}

How to set inside this block the id or class attributes?

You will not be able to add an id or class attribute to the block in your hook_block_view implementation. At this stage you are not yet dealing with the markup of the block itself but only the markup for its content. In order to set the id or class of the block markup, you will need to use hook_preprocess_block() or hook_process_block() to add a usable variables to the block.tpl.php template. Then you will need to actually use the variables in the template itself.

Fortunately, the default block.tpl.php file already provides variables for both the id  and class attributes of your block ($block_html_id and $classes). Actually, template_preprocess_block already sets the id to 'block-' . $variables['block']->module . '-' . $variables['block']->delta. So in your case, using the default template, your block will have block-contact-contact-block as id. But it can be changed if needed. In any preprocessor functions, you can add and remove CSS classes by manipulating $classes_array variables. Both are illustrated in the following code.

function MODULE_preprocess_block(&$variables) {
  if ($variables['block']->module == 'contact' && $variables['block']->delta == 'contact_block') {
    $variables['block_html_id'] = drupal_html_id('your-id-here');
    $variables['classes_array'][] = drupal_html_class('your-class-here');
  }
}


Register a module theme implementations I have created a simple module to display frequently asked questions (FAQ). The output (faq content) can be customize in mymodule-template.tpl.php file located in a module directory.

I'd like to create an additional template file suggestion for the theme directory e.g: sites/all/themes/mytheme/templates/mymodule-template.tpl.php

So, the main goal is to add two template file suggestions.

[my module path]/mymodule-template.tpl.php
[active theme path]/templates/mymodule-template.tpl.php

To achieve #1 I have implemented this hook.

/**
 * Implements hook_theme()
 * @return
 *  An array with the name of template file and variables
 */
function simple_faq_theme($existing, $type, $theme, $path) {
    // get faq content
    $records     = get_faq_content();   // categories, questions, answers
    $description = get_faq_info('intro');   // faq description

    return array(
        'faq_template'  => array(
          'template'    => 'simple_faq',
          'variables'   => array('records' => $records, 'description' => $description),
        )
    );
}

/**
 * FAQ Page content
 *
 * @return
 *  HTML created by template file
 */
function simple_faq_page() {
    return theme('faq_template');
}

It works, but I can't figure out how to create an additional suggestion, which allows users to theme the output without changing anything within module files.

Any idea?

Your hook_theme implementation is not being done in the usual way.
It should only have default values for the variables, like this:

/**
 * Implements hook_theme()
 * @return
 *  An array with the name of template file and variables
 */
function simple_faq_theme($existing, $type, $theme, $path) {
  return array(
    'faq_template' => array(
      'template' => 'simple_faq',
      'variables' => array('records' => array(), 'description' => ''),
    )
  );
}

Then when you call the theme function is where you send the actual values in, like this:

/**
 * FAQ Page content
 *
 * @return
 *  HTML created by template file
 */
 function simple_faq_page() {
   // Get faq content.
   // Categories, questions, answers.
   $records = get_faq_content();
   // faq description.
   $description = get_faq_info('intro');
   return theme('faq_template', array('records' => $records, 'description' => $description));
 }

As far as I know you can't give 2 values for the template file, however what you want to do should already be possible.
All you have to do is tell it where the original template file is in your module, then drupal will automatically find ones that are in any themes (the defining module doesn't have to set up anything for the theme).


Creating simple user groups with a term in Drupal 7 I need to tag my users as belonging to a 'workplace'. And then display a page with workplace details and a list of associated users.

I have setup a vocabulary in Taxonomy called 'workplace' and I can easily tag a user. I need to know how to create a block that will show on a taxonomy / term / id page and show tagged users.

I imagine I will have to make part of the user details public as well as by default they won't be?

Any help much appreciated - even a hint as to where to start ...

Since users are field able you can now attach a taxonomy term reference field to users.
Create a view that list all users where the tid of the term reference is a select value. You could also get the value from a url arg.
The view itself should show the user data you want to display, maybe as a list or whatever fits you better.
In the views header you could display the info about taxonomy term. Right now this will require some views knowledge and some custom code, as you need to create what views calls an area handler, to display the info. You could also do this in a preprocess function instead.


Get logged in user's username as twig variable Is there a way to get the currently logged in user's username as a variable to use in any twig template?

You would have to target a specific one. All twig templates is not possible because of caching. Many page elements don't get rebuilt on every request and they will display the wrong user.

And if you try to remove caching from all elements, your site would be very slow.

If you add this to a specific twig template, then you can adjust the cache context of this render element:

function MYTHEME_preprocess_HOOK(&$variables) {
  $variables['currentusername'] = \Drupal::currentUser()->getUsername();
  $variables['#cache']['contexts'][] = 'user';
}

Where HOOK is your template type.


themeing os user edit profile page I am doing theming of user edit profile page

Now i have three fields here

Password, currentpassword, confirm password

What are their field items

i have tried

    <?php print render($user_profile['account']['pass']['pass1']); ?>
<?php print render($user_profile['account']['pass']['pass2']);

Which is not working

Also i am not sure about third filed

Anybody can tell me

Thanks

You should use:

<?php print render($user_profile['account']['pass']); ?>

The password field is only split into 2 in a #process function, and you can't access the separate fields before the element is rendered. To do that you would need to provide a #theme property for the element itself, and write a function/template that returns the desired markup.


Pathauto and Token to get the first child term I am trying to create URL path aliases patterns with Tokens and Pathauto.

My main issue is how to I get the child of a parent of a taxonomy term? So my url is something like this.

[child-term:name]/[node:name]

In tokens help page I can see a lot [term:parent] references but not child ones. I am sure is something simple but in the vast amount of tokens I cannot seem to find it.

You can do quite advanced things with hook_pathauto_alias_alter to replace complex aliases patterns with just PHP code.

Here's how to use it:

/**
 * Implements hook_pathauto_alias_alter().
 */
function MYMODULE_pathauto_alias_alter(&$alias, array &$context) {
  // Make sure we're dealing with nodes
  if (isset($context['module']) && $context['module'] == 'node') {
    // If this is a "my_content_type" content type
    if ($context['type'] == 'my_content_type') {
      $node = $context['data']['node'];

      // do stuff with $node, such as getting the taxonomy term
      // and loading the term.. then getting the children terms etc..

      // then assign a string value to $alias
      $alias = pathauto_cleanstring($child_term->name) . '/' . pathauto_cleanstring($node->title); // for example...

      // Clean the alias
      $function = 'pathauto_clean_alias';
      if (function_exists($function)) {
        $alias = $function($alias);
      }

      // Now just make sure the alias generated is unique to this node.
      $function = 'pathauto_alias_uniquify';
      if (function_exists($function)) {
        $source = 'node/'.$node->nid;
        $lang = $node->language;

        $function($alias, $source, $lang);
      }
    }
  }
}


How to print "node title" in comment.html.twig template? i am styling my comments in comment.html.twig template and need to show "node title" of the node to which the comments belong.
I've tried a number of options, and the only one that works relatively is below:
function enar_preprocess_comment(&$variables){
   $node = \Drupal::request()->attributes->get('node');
   $variables['nodetitle'] = $node->getTitle();
}

However, if I click "reply" in the comments, I get this error.
Error: Call to a member function getTitle() on null in mytheme_preprocess_comment()

My question is, how to print "node title" in comment.html.twig template?

Because the comment reply page/route does not belong to a Node entity
$node = \Drupal::request()->attributes->get('node');

returns null.
Instead, access the node object with
$node = $variables['commented_entity'];


An exposed filter works only with certain taxonomy terms (weird to me) I have a "commercial property" and "residencial property" node types.
One for offices, cellars, etc and the other to houses, apartments, etc

They share some fields (price, address, etc) and also a field that I called "Kind of property" that is a taxonomy dictionary:

Kind of property:

Office
Cellar
House
Apartment
Estate

I have a View that works like a "Property search" and I have exposed the field "Kind of property". I created a menu for each one, so the visitor can go to "Sales - Apartments" and the View will show all the available apartments that are on sale.

This is the example URL for Apartments on sale: http://www.asir.com.co/inmuebles/buscar?asignacion[]=Venta&field_tipo_de_inmueble_tid=18

See that "asignacion" is a field that I use to mark the property if it is for sale or for rent (in this case Venta means Sale)

And also see that "field_tipo_de_inmueble_tid" point to the taxonomy term that is on the field "Kind of property".

The issue that I'm having is that field_tipo_de_inmueble_tid=18 works good, and also field_tipo_de_inmueble_tid=19 workds good, but if field_tipo_de_inmueble_tid=20 then it dosen't work and the view result is empty. (18 = Apartments, 19 = Houses, 20 = Estates, wich are the taxonomy terms).

I checked the nodes and there are nodes created that are using the termin id 20, but the View is not showing them so don't know how to troubleshoot this, any idea?

Thanks a lot for your time!

Found my mistake. I rechecked every value on the View filters, and the city filter had a value on it, so I left empty the city and now the property is showing ok, because that property is not on the city that was the default.


Views - "Add no results behavior" not doing what I would like it to I've selected a "Add no results behavior" option for my Views page which consists of a search form. The problem with the "Add no results behavior" feature is that it displays by default, even before I've attempted to do a search. How do I change this so that it only displays AFTER the user has attempted to do a search (for which there are no results)?

Assuming you're using Views 3, on the Views config page under Exposed form, change Exposed form style from Basic to Input required. Optionally change the other related settings on this page. Apply the settings and save the View and it should be ok.


Internal server error on admin/modules/list/confirm I have recently decided to move one of the sites to another hosting provider, and now started to receive this 500 error when submitting changes to admin/modules. The new hosting has different environment where all sites might have their core and contributed modules connected to the central repository; now, in admin/modules all 850 local repository modules can be seen as they were in sites/all/modules. In server logs this error reflect as:

  mod_fcgid: stderr: PHP Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 87437 bytes) in /opt/drupal7/includes/cache.inc on line 463, referer: admin/modules

  mod_fcgid: stderr: PHP Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 71 bytes) in /opt/drupal7/includes/form.inc on line 1820

  mod_fcgid: stderr: PHP Fatal error:  Allowed memory size of 134217728 bytes exhausted (tried to allocate 8208 bytes) in /opt/drupal7/modules/field/field.crud.inc on line 711, referer: admin/modules?render=overlay

  mod_fcgid: stderr: PHP Fatal error:  Allowed memory size of 134217728 bytes exhausted (tried to allocate 32 bytes) in /opt/drupal7/includes/file.inc on line 200, referer: admin/modules

The site has a 128 MB memory limit; it is more than on previous hosting, but now some of the enabled modules (like OpenLayers) sometime also issue memory errors (like those above, but on site they work without any 500 errors).

What can be the reason of this errors? Is there any additional information that can help find what to fix?

You need to check your PHP memory limit on php.ini.
If you use Linux, go to /etc/php.ini to find it out.


Node/add within a block? Is it possible to have a block that shows the node create page for a content type, and which would disappear once the node has been created?

You can use Panels to display a node create form anywhere you like. With a bit of extra config, you could probably make it disappear when a node exists. Panels allows you to set visibility rules to determine whether to show content.


How can I export all my blog posts as CSV? I'm migrating my website from Drupal to WordPress, and the only content I have left to migrate over are all my blog posts.

From my research, the easiest way to do this would be to export my blog posts from drupal as a CSV and then import the CSV file to my Wordpress site.

However, I'm having trouble figuring out how to export ALL my blogposts. The only thing I've managed to find (from myPhP Admin) is 'content_type_blog.' However, that only gives me the 'front page tease' and not the whole blog post.

Where can I find ONLY my blog posts to export?

If I was going to try to create a CSV of my sites content I would try to use the Views Data Export module and filter on your blog content type and include all the fields you want.

  This module is designed to provide a way to export large amounts of
  data from views. It provides a display plugin that can rendered
  progressively in a batch. Style plugins are included that support
  exporting in the following types:

  CSV
  Microsoft XLS
  Microsoft DOC
  Basic TXT
  XML


Providing Archive feature in a website We are considering to migrate an exiting website to Drupal: www.rkmission-shivanahalli.org The website has simple static content which I believe is not a big deal to migrate to Drupal.

However, there is one requirement which is pretty unconventional and not many websites have it. The archives feature. What we have been doing is, since currently the website is only collection of html files, we pick the whole web folder of current edition and place it into archives folder of the website and link the new website to the index.html page of that archived folder. We also have a link to get back to the current edition from the archives section.

Please see this link for more details, the archives page of current edition: http://www.rkmission-shivanahalli.org/archives.html

One of the edition from archives page will have a link like: http://www.rkmission-shivanahalli.org/Archives/AUG_2006/index.html.

Now I am not very sure how to achieve this using Drupal. Is there any direct way to do this? Or, any modules which does it on my behalf? Or, do I have to modify any source files etc.?

Thank you for any suggestions.

PS: This is a mirror of the question already asked in Drupal forums:
http://drupal.org/node/1884930

AFAIK the features provided by the Demonstration site (Sandbox / Snapshot) module are the closest as per your requirements. It has the feature that allows you to take snapshots of your site, use it as sandbox and later (if you want) restore it back to any of the previous saved state.

This module allows you to take snapshots of your site. Whenever you need to reset your site to the state of a saved snapshot a click of your mouse will do so.
With cron enabled, a site can be automatically reset to a chosen snapshot in a definable interval.

Backup/archive of uploaded files and restore upon reset. To allow sandboxes for file related modules.
Journal module integration to show recent changes in snapshots.
Demo Reset security improvements to allow to demonstrate administrative functionalities more easily.

There is also a Demonstration Site Install Profile which allows restoration of the Demonstration Site module's database dumps during site installation.


Trying to change the body in presave nodeapi - not working I'm trying to make a small modification in the body a node when it's saved:

function radicalislam_utils_nodeapi(&$node, $op) {
      if ($op == 'presave')
             $node->body = 'test';
}

but what I'm getting is strange. when I view the node, i really see only "test" as the body. but when i go edit the post, i see all that previously on the body and "test" appended in the end...

Why is that?

If the body of a node differs from its teaser, it will show both when editing
(it'll append the real body to the teaser, which is why it looks like you're still seeing the old version of the body).

In other words: make sure your body and your teaser are both altered before saving.


How do I disable a form? I want to disable a form in Drupal 8.

In D7 you could've done it in an alter hook like this.

$form['form'] = ['#value' => 'the form you are looking for is gone!']

What can I do in Drupal 8?

What I tried so far:

function hook_form_FORM_ID_alter () {
  $form[] = []; // $form[] or $form both will not work.
  $form['dunnoWhatToWriteHere'] = [
    '#type' => 'markup',
    '#markup' => t('The form is gone),
  ];
}

What I suggested is that I would overwrite the $form array with an blank one but as I run my xdebug drupal seems to just ignore it because the $form array in its native status exists although I tried to overwrite it with a blank one.

Do I also have to call a Formbuilder?

 $form = [];
 $form['error'] = [
   '#type' => 'html_tag',
   '#tag' => 'p',
   '#value' => t('The form is gone'),
 ];

That one worked for me :)

What I suggested is that I would overwrite the $form array with an
  blank one but as I run my xdebug drupal seems to just ignore it
  because the $form array in its native status exists although I tried
  to overwrite it with a blank one.

What you describe does look like caching. Drupal returns what is cached, without running the code to build the form again.

You don't give much information, but you did tell in the comments, the form is part of a rendered page. If the form would be a page on it's own, then this is about access. If you only want control if a part of the page is displayed, then this is about blocks. The first thing to try is to configure the visibility of the form  block. If you can't configure it in ui, then there are several ways to put custom code in block or page level to remove the block. This depends when and where the block should be displayed.


How do I Pass a Nid to a webform and create a token for a different field on that node? Use Case:
I have a content type called "Team" which contains an email address.  I have a view that creates a link to create a webform to contact the Team member and prepopulate the email address in a hidden field.

The Team member does not have a user profile.
I do not want to pass the email to the webform url since that would expose it.
I do understand how to pass a value to a webform.
I want to avoid maintaining a custom module.

Issue:
I hoped I could pass the Nid of the content entity and use an entity token to "lookup" the email as a default, hidden field and use that to generate the webform.  I'm sure I'm missing something fundamental (please don't down the question ...)

Question:
If I can get a token such as [current-page:query:nid] from the URL, how do I use that to get the email field [node:field-email] for say Nid=5?  Should token chaining something like [current-page:query:nid:field-email] work?  I can't seem to find good documentation on token reference chaining - that would be very helpful.

Installed D7.33, Token, Entity Token, Entity Reference.

I have viewed several similar cases that do not apply:
https://drupal.stackexchange.com/questions/95774/how-to-pass-a-token-to-webform-from-a-node-relationship
referencing/linking to an entityform and passing nid/other field information through the URL
Creating a token for the image field file path with node reference nid
https://drupal.stackexchange.com/questions/95774/how-to-pass-a-token-to-webform-from-a-node-relationship

Note: I found this module, but not sure if it is necessary: https://www.drupal.org/project/aet

How many teams are there?

If not too many, you could set up categories in your site contact form in admin/structure/contact that represent each team then pass the team name to the contact form, thus not exposing the email address.


Add CSS just to the main content and not to include comments I'm theming using the Omega HTML5 starterkit theme on Drupal 7, and I want to add CSS just to the main content region in nodes but not to the comments.

How do I do that? What is the class (or ID) for that?

In my own Omega subtheme, which is quite standard, page content with comments has this structure (closing tags omitted for brevity):

   (node body)

    (another node field I'm displaying)

So a CSS selector of:

node > content

would get you all the fields in the content, but not the comments. Or if you just want to style the body, you could choose it specifically.

Note that the content class is used a number of different places in a page. Alternatively you might want to set up  some default CSS for most of the node and style the #comments or .comment-wrapper separately.

This is not profound: I just poked around with Firebug to figure it out.


Autocomplete entity reference - Required to select entity I'm having problems with a required field that is an entity reference. This is my case:

I have a content type advertisement that has an entity reference product, what is an autocomplete widget. The entity reference is a required field (so when it's empty you have to fill something in).

When you start to type in the text field you get a list of suggestions to select from. But you can also type some text and DON'T select a suggestion, the form will submit and the content will be created. I don't want that. I would like to create an error that when you don't select one from the list you receive an error.

What happens when you don't select a suggestion: the advertisement is created but the product is empty!

Is there a way that I can create an error when you don't select one from the list?

Are you sure you are using the Autocomplete widget or are you using the Autocomplete (Tags Style)? I believe tags style allows for an entity to be created like taxonomy term.


Drupal UserLoginForm vs UserAuthenticationController login function - which to override? I have a drupal site where I am customizing the login by validating credentials against an OAuth2 provider, implementing the OAuth2 password flow, basically what this module does, except I am using D8 and this is for D7

https://www.drupal.org/project/oauth2_authentication

I upgraded that module to D8.  It works by adding a replacing the validateAuthentication function in the #validate array of the form with an implementation that validates against the external OAuth provider.  I upgraded all that to D8, but then I noticed in D8 that the login method of the UserAuthenticationController is also called to validate credentials.

So I have a couple questions

These two things both do basically the same thing.  Both pieces of code (UserLoginForm and UserAuthenticationController) validate against the user table in the DB.  Why are both doing essentially the same thing?  Are they both actually being called?
I realize it would be a cleaner implementation (and more Drupal 8-like) to override the UserAuthenticationController.  If my module registers the /user/login route to a different controller (provided by my module) will this override the default mapping to the UserAuthenticationController?

Thanks in advance.  I am new to drupal so any help would be appreciated.

UserAuthenticationController is a service that can be used by e.g. apps and decoupled websites.

Either one or the other is used, not both.

But both use the user.auth service, which receives username and password and returns a user ID in case of a match.

So if you want to override a single place to do that, that's what you want to do. Implement a service provider in your module and switch out the class of that service definition.


Drupal 7 LoginToboggan username or email or custom field I have a Drupal 7 site and the client wants the user to be able to login using: email or username or a custom_field that's unique to each user.  I've scoured for solutions but can't find any.   Any help would be appreciated.  I'm using Logintoboggan to handle username or email, but can't find anything to validate and allow authentication for a custom field.

Thanks!

You can do that by using this contrib module: https://www.drupal.org/project/login_custom_field

It will allow you to log in using a (custom user field and password) along side with (username and password). Also, you can enable LoginToboggan module to allow using (email and password) as a 3rd option.


Using a field in many content types? Usual or completely wrong? A basic question: Is there anything wrong with using a defined field in many content types?
For example: body, image_field?
Are there any problems to be expected when I do this?
My guess is: No. No problems. But: is that right?

Deciding if what your question is about is right or wrong, is something you'd have to decide for yourself. However by reusing field you're actually using one of the typical Drupal facilities to define fields.
In the context of "reusability", one would think that it is a good practise to reuse whatever can be reused.
The challenge (problem?) is that when changes are needed to a reused field, it'll be more difficult to do so for reused fields as compared to a field that is not reused at all.
To get a feeling of this, do some experiments with the Features module, for 2 scenarios: (a) changes to a reused field and (b) changes to a field that is not reused anywhere. Just look at the size of the features created in both scenarios.
My approach is becoming more and more to NOT reuse fields, to not complicate things when later on (design) changes are needed (to ensure maintainability as much as I can). This approach is also partially based on what I've learned from what's further detailed below, which applies to any release of Drupal ... (though I'm curious myself to see how things will evolve related to Relativity for Drupal 8).
Relativity model
There is an (illuminating) article "Relativity Model for Drupal", especially the related page about "Wrapping Information Architecture and Documentation". Here is a quote from it:

To create an Event content type in Drupal is a simple task. But there's a nuance to that task that is overlooked very often. That nuance is the machine name. But why is the machine name of a content type such an important step?

It gives the content type an explicit name of your choosing and allows database indexing to act on that machine name while being queried.
All fields contained within that content type will share the same machine name before the field name. This allows the Views module to clearly gather field data in a very defined manner using the indexed machine name.
Fields that are entity references out to other content types also begin with the same machine name followed by their own machine name. This allows simple and visual identification for origination and destination of data relationship.

It also contains an interesting example of what seems to be a great naming convention.
Remark (cfr comment from Kevin): The most difficult part is knowing when you would reuse a field vs when you won't. The big obstacle is shared field settings - changing certain settings affects all fields, when you probably only want to affect that instance.


How to add diffent makers on the image How to add a marker in different part of the image (please look at the attached photo),

There is a module Imagefield marker which is not working. is there any other similar module?

Thank for the help.

ImageCache Actions is the right module which you're looking for. Enable Imagecache Actions and Image Effects Text module

Go and edit the image style at admin/config/media/image-styles and select effect Text.


ExtensionDiscovery::scanDirectory() takes too long I have been debugging a bit an issue on our platform and I notice that our scanDirectory takes, from time to time, way to long, more than 100seconds.
I have been looking at the default.settings.php and I noticed
/**
 * The default list of directories that will be ignored by Drupal's file API.
 *
 * By default ignore node_modules and bower_components folders to avoid issues
 * with common frontend tools and recursive scanning of directories looking for
 * extensions.
 *
 * @see file_scan_directory()
 * @see \Drupal\Core\Extension\ExtensionDiscovery::scanDirectory()
 */
$settings['file_scan_ignore_directories'] = [
  'node_modules',
  'bower_components',
  'vendor',
];

I found that out that our sites/default directory is the one to blame.
Can I just add it here? Or should I include the subdirectories(fx sites/default/files)?
I am really surprised about this one. Been working with drupal years now and I see this first time!

If you need the file_scan_ignore_directories setting changed, you should add the $settings['file_scan_ignore_directories'] assignment in your settings.php, not default.settings.php lest it's overwritten when you update Drupal core.
Regarding what path strings to add to $settings['file_scan_ignore_directories'], that's up to you. As the comment block states, that setting affects all calls to ExtensionDiscovery::scanDirectory() and FileSystem::scanDirectory() (if a nomask option isn't specified).
Add the most inclusive path that you know will never contain extensions or files to be scanned/discovered.


Unable to delete feature content type after uninstalling feature Issue
Uninstalling a feature which creates a content type hides the "Delete" link on the admin/structure/types.
Issue on Drupal.org

Solution

Using a hook_uninstall() in FEATURE_NAME.install file and changing the status of the content type, so the system thinks it is an unlocked, custom content type.

I posted this also on d.org.

<?php
/**
 * Implements hook_uninstall().
 */
function FEATURE_NAME_uninstall() {

  // List custom content types added by this feature
  $custom_ctypes = array(
    'blog',
  );

  // Go through each and unlock the content type
  foreach ($custom_ctypes as $ctype) {
    db_query("UPDATE {node_type} SET `custom` = 1, locked = 0 WHERE type = :ctype", array(':ctype' => $ctype));
  }

  // Clean Drupal cache; this is necessary for the "Delete" link to appear
  // next to the content type created by the feature.
  drupal_flush_all_caches();

}

This will make the "Delete" button appear for that content type, so you can delete it from the admin.

Hope this helps someone!


how to add multiple tables in hook_schema() in .install file while creating custom module? Is it possible to add multiple tables in hook_schema() while creating a custom module? I have created a custom module with the help of Drupal entities. Will it be possible to store two different table in the modulename.install file?

You definitely can!
In your hook_schema implementation, your first array key is the table name. You can add as many as tables in this array:

Ex:

function quotes_schema(){
  $schema = array();
  $schema['quotes'] = array(
    'description' => 'Base table for Quotes. Contains all submitted data from initial page.',
    'primary key' => array('qid'),
    'fields' => array(
      ...
     ),
  $schema['quotes_access'] = array(
    'description' => 'Access tokens to quotes.',
    'primary key' => array('qid'),
    'fields' => array(
      ...
     ),

    ...
  return $schema;
}

This will create both quotes and quotes_keys tables.


How to exclude a module from being uninstalled during import? On my local I have installed my custom module which depends on a contrib module.
I have removed both modules from the core.extensions.yml and added the following to settings.local.php.
$settings['config_exclude_modules'] = ['contrib_module', 'mymodule'];

But when I execute drush cim, both of the modules get uninstalled.
But I can read this specifically.

When syncing configuration, if an excluded module is already
installed, it will not be uninstalled by the configuration
synchronisation, and dependent configuration will remain   intact.

Do I need to execute some command after adding it to the settings.php? Why it is not working.

This will only work with drush 10. So drush should be updated to version 10.
With drush version lower than 10, it will work only from the UI.


How to join another table via altering view query as exposed filter Hi I have created a view and exposed the view with node title. Searching is done on title and its working fine. But I have a requirement that when some one searches through title, the search text should also be matched to body field and if the content is found in any of the field it should display result. Like if the search text is not in title but found in body it should display the result as found.Please help

Add a filter from the Global group as a combined filter. Then assure the View has both the title and body fields avaiable in the View (they can be hidden from the View if you want).

Then set the combined filter to use the title and body fields when a search is done.

Then your single exposed filter will show results from your query criteria from either of the fields.


Programmatically disabling menu item I have been trying to disable a menu item "standard.front_page" using the following code:

db_query("UPDATE {menu_tree} SET enabled = 0 WHERE id LIKE 'standard.front_page';");
db_query("DELETE FROM {cache_menu};");

It works fine till I do a cache rebuild using drush cr. Once I do a cache rebuild the menu item again comes back.

Can anyone please suggest a good way of doing the above?

You can retrieve the Drupal menu link & cache services to programmatically change the menu link status. Something like this example function:

function menu_state_toggle($menu_id, $enabled = TRUE) {
  $menu_link_manager = \Drupal::service('plugin.manager.menu.link');
  $front_page_link = $menu_link_manager->getDefinition($menu_id);
  $front_page_link['enabled'] = $enabled ? 1 : 0;
  $menu_link_manager->updateDefinition($menu_id, $front_page_link);
  $cache = \Drupal::cache('menu');
  $cache->deleteAll();
}

menu_state_toggle('standard.front_page', FALSE);


How can I add a custom form menu link to the administrative menu programmatically? How can I add a custom form menu link to the administrative menu programmatically?

I am trying to add this form as admin menu link like content, structure and module.

Create a new menu using hook_menu. Like this

$items['admin/config/my_form'] = array(
    'title' => 'My Form',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('form_id'),
    'access callback' => TRUE, // Give access as per your need.
    'type' => MENU_NORMAL_ITEM,
);

Using this your form will be created with the link / menu item under configuration menu.

Thanks.


How do you populate an image field in a field collection programmatically? I'm trying to do a large import that's more complex than feeds can play nicely with, so I'm in the process of writing a custom import script. Everything works except loading images that are associated through a field collection. I have a field collection that contains node and taxonomy references just fine, but I've had no luck on the image field.

I have a field on the node called field_signature_media which references a field collection that can be a variety of media types. In the field collection I have field_signature_image for handling the images.

Attempt One: using entity_metadata_wrapper:

    // Image file created in earlier part of the process and loaded into $file
    // The node that's being worked on has been created in $node
    // Create the field collection
    $fc_item = entity_create('field_collection_item', array('field_name' => 'field_signature_media'));
    $fc_item->setHostEntity('node', $node);
    $fc_wrapper = entity_metadata_wrapper('field_collection_item', $fc_item);

    $field = array('alt' => '',
          'title' => '',
          'fid' => $file->fid,
          'display' => 1,
          'width' => $file->image_dimensions['width'],
          'height' => $file->image_dimensions['height'],
          'image_field_caption' => array
              (
                  'value' => '',
                  'format' => 'full_html',
              ),
    );

    $fc_wrapper->field_signature_image->set($field);
    $fc_wrapper->save(true);  // <-- at this point it enters infinite recursion.
    field_attach_update('node', $node);

Attempt Two without the wrapper:

    $fc_item = entity_create('field_collection_item', array('field_name' => 'field_signature_media'));
    $fc_item->field_signature_image[LANGUAGE_NONE][] =
                        array('alt' => '',
                              'title' => '',
                              'fid' => $file->fid,
                              'display' => 1,
                              'width' => $file->image_dimensions['width'],
                              'height' => $file->image_dimensions['height'],
                              'image_field_caption' => array
                                  (
                                      'value' => '',
                                      'format' => 'full_html',
                                  ),
                        );
    $fc_item->setHostEntity('node', $node);
    $fc_item->save(TRUE);
    field_attach_update('node', $node); // <-- At this point field_collection cannot find an array it was expecting.

Attempt Three with wrapper and not creating field data by hand:

    $fc_item = entity_create('field_collection_item', array('field_name' => 'field_signature_media'));
    $fc_item->setHostEntity('node', $node);
    $fc_wrapper = entity_metadata_wrapper('field_collection_item', $fc_item);
    $fc_wrapper->field_signature_image->set($file->fid);
    $fc_wrapper->save(true);  // <-- at this point it enters infinite recursion.
    field_attach_update('node', $node);

There should be no difference between setting the field on a node versus a field collection item.

This should work

$fc_wrapper->field_signature_image->file->set($file);

This should also work

$fc_wrapper->field_signature_image = (array) $file;

assuming $file is a valid file object.  When I have trouble with adding files, it is usually because I have a property missing.  In that case, I will make a node and field collection item via the UI, and then dpm() to see what us missing.  Half the time, it is $file->display, and the rest is usually $file->description.  My guess is that $file->description is your problem.

What I don't recall is whether using File Entity changes this.  Both line above are based on import scripts I have where this module is disabled.


Should magic quotes be on/off for Drupal 7? Should magic quotes be on or off?

Off. Currently it's non standard to set them on, and here you have somebody with problems created by magic quotes on.


Views page access callback How can I change the access callback for a page view (Views module)? I tried hook_menu_alter but realized that views uses the same hook to add the menu items defined by it - as a result of which, I am unable to have access to them.

Any way out?

Views allows you to set the acess within the UI, you can restrict based on roles or permission.

Usually that should be enought but if you need to set a custom access callback you can use hook_menu_alter but you will also need to make sure your module is called after the views hook_menu_alter, you can change the weight of your module in the database or you can use hook_module_implements_alter to make sure your module is called after the views module for the menu alter hook.


How to print add/remove link for user relationships module? I want to print Add/Remove friend link fro user relationship module on user profile page. I am trying this using below code but its causing white screen.

//add link
global $user;
$account = user_load(arg(1));
$actions = _user_relationships_ui_actions_between($user, $account);
if (count($actions)) {
  print theme('item_list', $actions);
}

Please help me.

Install Devel module and add dpm statements in a progressive fashion. For instance: After you load the account, add : dmp (arg(1)) (and no other statements following). Inspect the dpm output for correctness and go onto the next statement, ie. dpm($account(arg(1)) and so forth.