drupal_set_title not working in module form - drupal

I´m trying to learn Drupal 8. So now, I´m "building" forms.
I created a module.
INSIDE mymodule\src\Form
I have form1.php
namespace Drupal\mymodule\Form;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
class form1 extends FormBase {
public function getFormId() {
return 'myform1';
}
public function buildForm(array $form, FormStateInterface $form_state) {
$form['name'] = array(
'#type' => 'textfield',
'#title' => t('Your name'),
'#maxlength' => 30,
);
$form['Lastname'] = array(
'#type' => 'textfield',
'#title' => t('Your lastname'),
);
$form['submit'] = array(
'#type' => 'submit',
'#value' => t('Submit'),
);
return $form;
}
And WORKS...
But when I want to put a title to the page, in my case and linked to my_module.routing.yml, 127.0.0.1/form1 using
...
public function buildForm(array $form, FormStateInterface $form_state) {
drupal_set_title(t('This is a Title'));
$form['name'] = array(
'#type' => 'textfield',
'#title' => t('Your name'),
'#maxlength' => 30,
);
...
I receive the following ERROR:
ERROR:
Fatal error: Call to undefined function Drupal\mymodule\Form\drupal_set_title() in C:\xampp\htdocs\drupalwebsite\modules\custom\mymodule\src\Form\form1.php on line 16
An the line 16 is:
drupal_set_title(t('This is a Title'));
So the problem is with the title. I tried to resolve it but I could not.
Anyone know why?
Thanks a lot

According to https://www.drupal.org/node/2067859, drupal_set_title() was removed in D8. Have you tried the alternate method that's mentioned in that link, like this:
$form['#title'] = $this->t('This is a Title');

Related

Render form in a Twig Template in drupal8

Im curently using drupal 8 and I have created form using form api,
The below code under Module directory
// module/src/Form/ContributeForm
class ContributeForm extends FormBase {
public function getFormId() {
return 'amazing_forms_contribute_form';
}
public function buildForm(array $form, FormStateInterface $form_state)
{
$form['title'] = array(
'#type' => 'textfield',
'#title' => t('Title'),
'#required' => TRUE,
);
$form['video'] = array(
'#type' => 'textfield',
'#title' => t('Youtube video'),
);
$form['video'] = array(
'#type' => 'textfield',
'#title' => t('Youtube video'),
);
$form['develop'] = array(
'#type' => 'checkbox',
'#title' => t('I would like to be involved in developing this
material'),
);
$form['submit'] = array(
'#type' => 'submit',
'#value' => t('Submit'),
);
return $form;
}
public function validateForm(array &$form, FormStateInterface $form_state) {
}
public function submitForm(array &$form, FormStateInterface $form_state) {
}
}
Now I need to render above vairables in twig template like below
//themes/page.html.twig
<body>
{{form.title}}
{{form.video}}
{{form.video}}
</body>
the twig will be under theme folder.Is it possible to get variable in page.html.twig file??
The best way to render and custom your form via Twig, you'd use $form['#theme'] value in your form. Example below:
module_name/scr/Form/your_form.php
public function buildForm(array $form, FormStateInterface $form_state){
.....
.....
$form['#theme'] = 'your_form_theme';
return $form;
}
module_name/form.module
function form_theme() {
$themes['your_form_theme'] = ['render element' => 'form'];
return $themes;
}
What is left is creating your custom twig and insert you form fields.
module_name/templates/your-form-theme.html.twig
<body>
{{form.field_1}}
{{form.field_2}}
{{form.field_3}}
</body>
Hope it helps you!
You can create a page by using the controller. From that, you can get the form elements.
Create a module_nameController.php file inside src/Controller folder. In that file create a class that should be extended to Controllerbase. In that file, by using form builder function you can get the form elements.

how to create multi step custom form back button in Drupal 7?

i make custom form with 2 steps, i want if user click on back button on step 2 form redirect to step 1 and show the data which the user has entered at the beginning. and this is my code
function example_form($form, &$form_state) {
if (!empty($form_state['step_num'])) {
return example_step_two($form, $form_state);
}
$form_state['step_num'] = 1;
$form['title'] = array(
'#type' => 'textfield',
'#title' => t('Title'),
'#required' => TRUE,
);
$form['next'] = array(
'#type' => 'submit',
'#value' => 'Next',
'#submit' => array('example_form_submit'),
);
return $form;
}
and this is my submit function
function orders_order_form_submit($form, &$form_state) {
$form_state['page_values']['1'] = $form_state['values'];
if (!empty($form_state['page_values'][2])) {
$form_state['values'] = $form_state['page_values'][2];
}
$form_state['step_number'] = 2;
$form_state['rebuild'] = TRUE;
}
and this is step two of my form
function example_form_step_two($form, &$form_state){
$form['title2'] = array(
'#type' => 'textfield',
'#title' => t('Title2'),
'#required' => TRUE,
);
$form['back'] = array(
'#type' => 'submit',
'#value' => t('Back'),
'#submit' => array('example_form_step_two_back'),
);
$form['submit'] = array(
'#type' => 'submit',
'#value' => 'Submit',
'#submit' => array('example_form_step_two_submit'),
);
return $form;
}
and this is the problem function for back button
function example_form_step_two_back($form, &$form_state){
$form_state['rebuild'] = TRUE;
}
Looks like you need to test if 'step_num' is 2 in example_form(), not if it's not empty:
if ($form_state['step_num'] == 2) {
return example_step_two($form, $form_state);
}
Then in example_form_step_two_back(), you need to add:
$form_state['step_num'] = 1;
To display the previously user-entered value of 'title', you have to add a '#default_value' element to it which is set if that value exists.

Ajax not working in drupal 8 custom form

I'm trying to use ajax in drupal 8 custom form. But it not work.
I've custom form, in which textfield is display with some value once the user click on the checkbox. Here is my code:-
public function buildForm(array $form, FormStateInterface $form_state) {
$form['del_name'] = array(
'#type' => 'checkbox',
'#title' => $this->t('Delete users, by name'),
'#ajax' => array(
'callback' => array($this, 'my_user_callback'),
'wrapper' => 'del-name',
),
);
$form['name_placeholder'] = array(
'#type' => 'hidden',
'#prefix' => '<div id="del-name">',
'#suffix' => '</div>',
'#tree' => TRUE,
);
if (!empty($form_state->getValue('del_name')) && $form_state->getValue('del_name')) {
/*
* $process_data = some stuff
*/
$form['name_placeholder']['user_role'] = array(
'#title' => $this->t('Users role'),
'#type' => 'textfield',
'#default_value' => $process_data
);
}
}
function my_user_callback(array &$form, FormStateInterface $form_state) {
return array(
'#type' => 'ajax',
'#commands' => array(
ajax_command_replace('#del-name', render($form['name_placeholder'])),
)
);
}
Problem is that, textfield not appear when checkbox is checked.
try this:
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\HtmlCommand;
function my_user_callback(array &$form, FormStateInterface $form_state {
$response = new AjaxResponse();
$response->addCommand(new HtmlCommand(
'#wrapper-element-id',
$array_of_form_elements
));
return $response;
);

how to load database content to dropdown options (select)

i'm still working on my own drupal 7 module, and i'm having some trouble. I'm trying to load database content to dropdown option (select), i have read and write the same code from drupal example, but my database still not loading, only empty option.
what i'm asking is there anything wrong on my code or is there any faster way to load database to dropdown option other than the drupal example???
here the code i'm working on
function prod_entry_load($entry = array()) {
$select = db_select('aa_1122','aa');
$select->fields('aa');
foreach ($entry as $field => $value) {
$select->condition($field, $value);
}
return $select->execute()->fetchAll();
}
function prod(){
return drupal_get_form('prod_form');
}
function prod_form($form_state){
$form = array(
'#prefix' => '<div id="updateform">',
'#suffix' => '</div>',
);
$entries = prod_entry_load();
$keyed_entries = array();
if (empty($entries)) {
$form['no_values'] = array(
'#value' => t("No entries exist in the table dbtng_example table."),
);
return $form;
}
foreach ($entries as $entry) {
$options[$entry->no] = t("#no: #name ", array('#no' => $entry->no, '#name' => $entry->name));
$keyed_entries[$entry->no] = $entry;
}
$default_entry = !empty($form_state['values']['no']) ? $keyed_entries[$form_state['values']['no']] : $entries[0];
$form_state['entries'] = $keyed_entries;
$form['no'] = array(
'#type' => 'select',
'#title' => t('Choose'),
'#default_value' => $default_entry->no,
'#ajax' => array(
'wrapper' => 'updateform',
'callback' => 'prod_form_update_callback',
),
);
$form['submit'] = array(
'#type' => 'submit',
'#value' => 'Submit',
'#ajax' => array(
'callback' => 'ajax_alert',
),
);
return $form;
}
function prod_form_update_callback($form, $form_state) {
$entry = $form_state['entries'][$form_state['values']['no']];
foreach (array('name') as $item) {
$form[$item]['#value'] = $entry->$item;
}
return $form;
}
You've just forgotten to add the #options key to your select element, the code should read like this:
$form['no'] = array(
'#type' => 'select',
'#title' => t('Choose'),
'#default_value' => $default_entry->no,
'#options' => $options, // This is the bit that was missing
'#ajax' => array(
'wrapper' => 'updateform',
'callback' => 'prod_form_update_callback',
),
);
You could shorten your query/options code slightly using a combination of string concatenation in MySQL and the db fetchAllKeyed() method:
$query = db_select('aa_1122', 'aa')->fields('aa', array('no'));
$query->addExpression("CONCAT(no, ': ', name)", 'display');
$options = $query->execute()->fetchAllKeyed();

How To Create New Content Type Programmatically in Drupal 7?

I'm building a module (my_module) in Drupal 7.
It has some functionality and also will create new content type.
In my_module.install I implemented the hook_install (my_module_install).
Can I use more one implementation of hook_install to create new content type (my_cck_install) in this module?
If (yes), how should I do this?
Else: have I do this in another module? :-)
You can't use more than one implementation of hook_install in the same module; in PHP you can't have 2 function with the same name which rules this out.
You would just need to add your new content type in the same hook_install anyway (have a look at how the standard installation profile does it at /profiles/standard/standard.install). This is how I always add new content types from the install file (using the example of a testimonials module):
function testimonial_install() {
// Make sure a testimonial content type doesn't already exist
if (!in_array('testimonial', node_type_get_names())) {
$type = array(
'type' => 'testimonial',
'name' => st('Testimonial'),
'base' => 'node_content',
'custom' => 1,
'modified' => 1,
'locked' => 0,
'title_label' => 'Customer / Client Name'
);
$type = node_type_set_defaults($type);
node_type_save($type);
node_add_body_field($type);
}
}
The following code will create a content type called "Event" with a machine name of 'event' and a title field -
//CREATE NEW CONTENT TYPE
function orderform_node_info() {
return array(
'event' => array(
'name' => t('Event'),
'base' => 'event',
'description' => t('A event content type'),
'has_title' => TRUE
),
);
}
function event_form($node,$form_state) {
$form['title'] = array(
'#type' => 'textfield',
'#title' => t('event Title'),
'#default_value' => !empty($node->title) ? $node->title : '',
'#required' => TRUE,
'#weight' => -5
);
return $form;
}
//END CONTENT TYPE
you should place it in your .module file... if you want do add additional fields to it, let me know and I'll patch you up with the code... good luck!
/**
* Implements hook_node_info()
*/
function mymodule_node_info() {
return array(
'news' => array(
'name' => t('News'),
'base' => 'news',
'description' => t('You can add News here'),
'has_title' => TRUE,
'title_label' => t('News title')
)
);
}
/**
* Implement hook_form()
*/
function mymodule_form($node, $form_state) {
return node_content_form($node, $form_state);
}
Add the implementation to mymodule.install is as follows:
/**
* Implements hook_install().
*/
function mymodule_install() {
node_types_rebuild();
$types = node_type_get_types();|
node_add_body_field($types['news']);
}
You can get a detailed description with code from here
/*
* Implementation in hook node info in .Module file
*/
function test_node_info() {
return array(
'product' => array(
'name' => t('Product'),
'base' => 'product',
'description' => t('Product Title'),
)
);
}
/**
* Implement hook_form()
*/
function product_form($node, $form_state) {
return node_content_form($node, $form_state);
}
/**
* Implements hook_install() in .install file.
*/
function test_install() {
node_types_rebuild();
$types = node_type_get_types();
node_add_body_field($types['product']);
//New way to implement to add fields in your content type
foreach (_test_installed_fields() as $field) {
field_create_field($field);
}
foreach (_test_installed_instances() as $fieldinstance) {
$fieldinstance['entity_type'] = 'node';
$fieldinstance['bundle'] = 'product';
field_create_instance($fieldinstance);
}
}
/*
* Define your fields
*/
function _test_installed_fields() {
$t = get_t();
return array(
'product_title123' => array(
'field_name' => 'product_title123',
'label' => $t('Product Title'),
'type' => 'text'
),
'description123' => array(
'field_name' => 'description123',
'label' => $t('Description'),
'type' => 'text'
),
);
}
/*
* Define your instance of fields
*/
function _test_installed_instances() {
$t = get_t();
return array(
'product_title123' => array(
'field_name' => 'product_title123',
'type' => 'text',
'label' => $t('Product Title'),
'widget' => array(
'type' => 'text_textfield'
),
'display' => array(
'example_node_list' => array(
'label' => $t('Product Title'),
'type' => 'text'
)
)
),
'description123' => array(
'field_name' => 'description123',
'type' => 'text',
'label' => $t('Description'),
'widget' => array(
'type' => 'text_textarea_with_summary'
),
'display' => array(
'example_node_list' => array(
'label' => $t('Description'),
'type' => 'text'
)
)
),
);
}
/**
* Implements hook_uninstall().
*/
function test_uninstall() {
$ournewtype = 'product';
$sql = 'SELECT nid FROM {node} n WHERE n.type = :type';
$result = db_query($sql, array(':type' => $ournewtype));
$nodeids = array();
foreach ($result as $row) {
$nodeids[] = $row->nid;
}
node_delete_multiple($nodeids);
node_type_delete($ournewtype);
}
That's it.

Resources