Drupal 8 create field programmatically - drupal

I created a custom module for Drupal 8 that allows the users to choose a Content type in order to add some fields programmatically.
How I can create some fields (text type in this case) and attach they to a Content type with a custom module?
Some help?
Thanks.

Checkout Field API for Drupal 8
It has several functions implemented and hook_entity_bundle_field_info might be what you need, here is an example of textfield from the docs of that hook
function hook_entity_bundle_field_info(\Drupal\Core\Entity\EntityTypeInterface $entity_type, $bundle, array $base_field_definitions) {
// Add a property only to nodes of the 'article' bundle.
if ($entity_type->id() == 'node' && $bundle == 'article') {
$fields = array();
$fields['mymodule_text_more'] = BaseFieldDefinition::create('string')
->setLabel(t('More text'))
->setComputed(TRUE)
->setClass('\Drupal\mymodule\EntityComputedMoreText');
return $fields;
}
}
You might also need Field Storage, checkout hook_entity_field_storage_info

You need to create FieldType, FieldWidget and FieldFormatter(If necessary), there are good examples in Core/Field/Plugin/Field.
There is a good example here https://www.drupal.org/node/2620964

You can use this module to create fields programmatically for any entity type and multiple bundles at once from custom YAML or JSON files:
https://drupal.org/project/field_create
The simplest approach for your module is to add your fields in the hook_field_create_definitions(). Simply create this function:
function mymodule_field_create_definitions_alter(&$definitions) {}

Related

Filter Entity Reference View with dynamic arguments from Reference Field

I need to filter an "Entity Reference View" autocomplete widget by passing arguments from a "Reference Field" in my content type.
I researched on this and found that PHP Code type Contextual Filter is the most suggested way to achieving this but as PHP Code has now been removed from Drupal 8 Core, what are the alternatives to this common use case? (an earlier suggestion to use PHP Code: Drupal 7: how to filter view content (with entity reference field) based on current page content)
While editing the reference field, it seems that only hard-coded values be mentioned in "View arguments" field and there is no dynamical way of achieving this (e.g. from URL/query string etc).
It's hacky, but you can use a hook_form_alter. Here's an example passing the current NID as an argument:
/**
* Implements hook_form_alter().
*/
function MYMODULE_form_alter(&$form, FormStateInterface $form_state, $form_id)
{
if ($form_id == 'node_NODETYPE_edit_form') {
$node = $form_state->getFormObject()->getEntity();
$form['field_MY_REF_FIELD']['widget'][0]['target_id']['#selection_settings']['view']['arguments'][0] = $node->id();
}
}
For example.com/path?id=55
[current-page:query:id]
For example.com/path/55
[current-page:url:args:last]
For example.com/path/alias
[current-page:url:unaliased:args:last]

Displaying field collections loop in Content Type TPL file for drupal 7

I have a content type "about" created in Drupal 7. I have a field collection named "field_usf_projects" which is set to unlimited and contains 2 fields, "usf_title" and "usf_description". Now I want to run a for loop which retrieves the field_usf_projects and then displays 2 fields namely ("usf_title" and "usf_description") inside a ul - li structure.
I have gone through many links but cannot find a working solution. Please help me with this.
Thanks in advance.
Here is my solution, on hook_node_view you can use the entity wrapper to get the fields
function mymodule_node_view($node, $view_mode, $langcode) {
// Check if the node is type 'about'.
if ($node->type != 'about') {
return;
}
// Get the contents of the node using entity wrapper.
$node_wrapper = entity_metadata_wrapper('node', $node);
// Get the contents of the field collection.
$values = $node_wrapper->field_usf_projects;
// Loop field_usf_projects.
foreach ($values as $item) {
// Print the values of the fields.
var_dump($item->usf_title->value());
var_dump($item->usf_description->value());
}
}
Instead of dumping, you can add the markup for your
A nicer thing to do would be use the hook_preprocess_node to add the markup straight into the $variables, and print them via template.
https://api.drupal.org/api/drupal/modules!node!node.module/function/template_preprocess_node/7
I can tell you how I'm handling this, event it's a bit dirty and I'm risking to be crucified, but it works for me. If you are inside node template you have $node object. Print it with print_r or similar way and just follow the structure of output to get to your data. It will probably be something like:
$node->field_usf_title['und']...
If you don't have that $node object find node id and load the node with
$node = node_load($nid);
first.
I was finally fed up with Field collection. I cannot get any data. I have used Multifield which is way too much better than Field collection. Please see it at https://www.drupal.org/project/multifield
Let me know what is better multi field or Field Collection.
Thanks!

Hide cck field based on role

Im looking for a way to hide a cck field for every one except for one specific role.
I know that there is a module, Content Permission module, that takes good care of this. But I have taken over a very big site with many content types, with lots of related cck fields being defined. So installing Content Permission module is not a good idea because of the great amount of settings it would require.
It's a drupal 6 installation.
You may use hook_nodeapi in a custom module:
/**
* Implements hook_nodeapi().
*/
function yourmodule_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {
switch ($op) {
case 'view':
if (! user_access('show restricted content')) {
unset ($node->content['field_restrictedcontent']);
}
break;
}
}
/**
* Implements hook_perm().
*/
function yourmodule_perm () {
return array(
'show restricted content',
);
}
Nevertheless, be aware that this is somewhat a hack: I think you should reconsider using Content Permission module for your site, and make the effort needed to configure it for your node types. It's a one time job and it may protect you from compatibilities issues with other modules in your site.
You need to use any of the permissions module and reconfigure each of those fields in question. With code, you have to check user roles for each of those fields!

Drupal Exposed Views Filter custom date

I have a date filter that I have exposed on my view. I want to make the interface more user friendly and tighten up the look of it. Instead of selecting a date I would like to select from the following options.
The last day
The last week
The last year
All
This would then filter on the date field. Is this possible? How would you go about doing this?
The proper way to do it is to alter the form in a custom module using hook_form_alter:
function YOURMODULE_form_alter(&$form, $form_state, $form_id) {
if ($form_id == 'views_exposed_form') {
$view = &$form_state['view'];
$display = &$form_state['display'];
if ($view->name == 'YOURVIEWNAME' && $display->id == 'YOURDISPLAYID') {
//Alter $form here, use dpm($form) to inspect it.
}
}
}
$form is an array describing the form, using Drupal Form API. You can inspect this array using dpm from the Devel module.
It is possbile, but you will need to write your own module for that.
That module would use the method called "Form Alter" to change the form. Try starting here http://drupal.org/node/157253

how to customise search results of apachesolr (drupal 6)

can somebody help me how to customize the search result of a apache solr search. i was only able to access these variables [comment_count] => [created] => [id] => [name] => [nid] => [title] => [type] => [uid] => [url] => [score] => [body].
how can i access other variable like status, vote .... from the index ( i don't want to access the database for retrieving these values, i want to get it from the index itself)
i need to display no of votes for that specific node in the result snippet
i need to understand
1. how to index votes field
2. how to show the vote, status... in result snippet.
Votes are a poor choice for indexing for a couple of reasons:
Votes can change quickly
When a vote is made, the node is not updated. As such, apachesolr won't know to re-index the node to pick up the change.
If by 'status' you mean the node->status value, then the answer is that it will always be 1. Unpublished nodes are never indexed.
Now, if you want to add something else to the index, you want hook_apachesolr_update_index(&$document, $node) - this hook gets called as each node is being indexed, and you can add fields to $document from $node to get the values into the solr index. However, you want to use the pre-defined field prefixes - look at schema.xml to find the list.
Below is example of code to add fields for sorting, and for output.
/**
* Implementation of hook_apachesolr_update_index()
* Here we're adding custom fields to index, so that they available for sorting. To make this work, it's required to re-index content.
*/
function somemodule_apachesolr_update_index(&$document, $node) {
if ($node->type == 'product') {
$document->addField('sm_default_qty', $node->default_qty);
$document->addField('sm_sell_price', $node->sell_price);
$document->addField('sm_model', $node->model);
foreach ($node->field_images AS $image) {
//$imagecached_filepath = imagecache_create_path('product', $image['filepath']);
$document->addField('sm_field_images', $image['filepath']);
}
}
}
/**
* Implementation of hook_apachesolr_modify_query()
* Here we point what additional fields we need to get from solr
*/
function somemodule_apachesolr_modify_query(&$query, &$params, $caller) {
$params['fl'] .= ',sm_default_qty,sm_field_images,sm_sell_price,sm_model';
}
If you want to totally customize output, you should do following:
1) Copy search-results.tpl.php and search-result.tpl.php from /modules/search to your theme's folder.
2) Use the $result object as needed within search-result.tpl.php
3) Don't forget to clear the theme registry by visiting admin/build/themes
Or as mentioned about, you can override using preprocessor hooks.
Regards, Slava
Another option is to create a view(s) of your liking with input argument nid, then create the following preprocess in your template.php file:
function MYTHEME_preprocess_search_result(&$vars) {
$vars['myView'] = views_embed_view('myView', 'default', $vars['result']['node']->nid);
}
Matching the view name 'myView' with the variable name makes sense to me. Then you can use the variable $myView in your search-results.tpl.php file.
Here's a video by the makers of the Solr Search Integration module with an overview on how to customise what nodes and fields are indexed, and what Solr spits out as a search result...
For Drupal 6:
http://sf2010.drupal.org/conference/sessions/apache-solr-search-mastery.html
And Drupal 7:
http://www.acquia.com/resources/acquia-tv/conference/apache-solr-search-mastery
It all looks very customisable!

Resources