Set default value to an input field drupal 7 - drupal-7

I began a project which uses Entity Registration. An authenticated user can register for him and some else for an event. I set some extra fields in the account creation (name and surname).
I also set name and surname for registering to an event. I'd like to avoid an authentificated user to fill twice a form with same information.
For this I created a module with a hook where I've been able to retrieve the user information.
function mymodule_form_alter(&$form, $form_state, $form_id) {
// retrieve name & surname
global $user;
$user_fields = user_load($user->uid);
$name = $user_fields->field_user_name['und']['0']['value'];
$surname = $user_fields->field_user_surname['und']['0']['value'];
// check the form_id
if($form_id=='registration_form'){
$form['field_new_name']= array('#default_value' => $name);
$form['field_new_surname']= array('#default_value' => $surname);
// $form['field_new_name']['#value'] = $name;
// $form['field_new_name']['widget'][0]['value']['#default_value'] = "joe";
}
}
I succeed retrieving the data but i fail to set the input to display this value in the input text field...
I also have a select menu to define who is registering :
<select id="edit-who-is-registering" name="who_is_registering" class="form-select required">
<option value="" selected="selected">- Select -</option>
<option value="registration_registrant_type_me">Myself</option>
<option value="registration_registrant_type_user">Other account</option>
<option value="registration_registrant_type_anon">Other person</option>
</select>
Here I don't know how I can test if the select input has the value "registration_registrant_type_me" in the hook i try to create. Ideally i'd like to hide the name and surname field with the setted value ...

For getting user info :
$user_fields = user_load($user->uid);
$name = $user_fields->field_user_name['und']['0']['value'];
$surname = $user_fields->field_user_name['und']['0']['value'];
then to display the value in the field (i was saved by kint) :
$form['field_new_name']['und'][0]['value']['#default_value'] = $name;
$form['field_new_surname']['und'][0]['value']['#default_value'] = $surname;

Related

Codeigniter foreach Select Menu 'Selected' Option

I am creating a theme select option for an App. I want the user to choose from a select option which theme they want, light or dark.
I am storing theme names in the database like so:
I am then calling all themes in the Model and returning the array with this code:
public function getThemes() {
$query = $this->db->query('SELECT * FROM theme');
return $query->result_array();
}
I am using my Constructor to grab the data and Render it to my settings view like so: (I am sending a few things at the same time in $this->data that's why it is in an array but I cut that code out)
$this->data = [
'themes' => $this->model_setting->getThemes()
];
$this->render('backend/standart/administrator/setting/setting_general', $this->data);
In my HTML View I have the following HTML which successfully displays the correct 2 themes available:
<div class="col-sm-12">
<label>Select Your Desired Theme</label><br>
<select class="form-control" name="site_color_theme" id="site_color_theme">
<?php foreach ($themes as $theme): ?>
<option value="<?= $theme['theme']; ?>" ><?= $theme['name']; ?></option>
<?php endforeach; ?>
</select>
</div>
When I save the settings form I am updating my options table in the database with the theme name. The Html Body Class calls on this options table and finds the chosen theme and uses this to render a specific CSS Stylesheet.
The problem I am having is when I save my settings, the Select Option does not display the saved theme name to show that this is the active theme chosen.
How can I get the Select Option to display the chosen theme when the user visits the settings page to select another theme?
You should have active_theme column in the theme table
active_theme set to 1 when form dropdown site_color_theme is submitted (the rest theme records set to 0)
You should use Codeigniter Form Helper to do that : https://www.codeigniter.com/user_guide/helpers/form_helper.html#form_dropdown
// $themes = Theme list array [id => theme-name, id => theme-name]
// $active_theme = Record of "active_theme" with value equal to "1"
// $extra = Custom HTML attributes e.g. class="something" onclick="function(js)"
echo form_dropdown('site_color_theme', $themes, $active_theme, $extra);

ReactJS Set Selected Option based on Prop Text Match

I am trying to get query parameters from my url and use those values to set the selected option value on load. At the moment I have access to two values that match, which are the option text and the query parameter value.
My original thought is to add a variable within my loop that is set by an if statement that checks if the loop value matches the query props value, but I'm being given an error message about an unexpected token. What is possibly wrong with this setup and there is a better way to set up this evaluation and set "select" to the proper option on page load?
Here is the full error message ({selected} is where the error happens):
ERROR in ./public/components/app/activity-feed/search-form.js
Module build failed: SyntaxError: Unexpected token, expected ... (45:102)
43 | selected = 'selected';
44 | }
> 45 | return ( <option value={category.categoryHashId} {selected}>
Here is my react code where this.props.category is an array of ids/text for each category that is possible to query and this.props.categoryQuery is the text value that is currently a query parameter:
<select name="category" className="form-control filter-category">
{ this.props.category.map( (category) => { var selected; if(category.categoryName == this.props.categoryQuery){ selected = 'selected'; } return (
<option value={category.categoryHashId} {selected}>{category.categoryName}</option> ) } ) }
</select>
For example, this.props.categoryQuery is Blog and out of the 8 this.props.category.categoryName array values, Blog matches and a "selected" string is added
You cannot write a prop for an element the way you are doing: <tag {someValue}/>.
Instead, pass a value property to the select element and a defaultValue to the option elements:
const {
category,
categoryQuery
} = this.props;
const selectedCategory = category.find((val) => {
return val.categoryName === categoryQuery;
})
return (
<select
name="category"
className="form-control filter-category"
value={selectedCategory.categoryHashId}
>
{category.map((cat) => {
return (
<option
key={cat.categoryHashId}
defaultValue={cat.categoryHashId}
>
{cat.categoryName}
</option>
);
})}
</select>
);
Sidenote: You should not use the categoryName for identification/comparison/selection if you have a unique categoryHashId. When the user selects the category, use this instead of the name. You might want to review a bit your data structure for more efficiency.
I wrote this example to match your need, but if you use a hashId inside your categoryQuery you can skip the .find() step.

Angular - Cant update textarea after user input

Im having an issue with Anuglar. ng-bind doesnt update textarea once its value has been altered by user input.
Note: The reason im using ng-bind instead of ng-model is that I need ng-bind-html as the input is in html sanatized using ngSanitize.
Demo:
http://jsfiddle.net/Lvc0u55v/11682/
Here is how to see what im talking about: Select anyvalue from dropdown and textarea is updated. But select New Value and put some text in the textarea. Then change the select box to any value and textarea never changes again!
Code:
[SCRIPT]
$scope.msg_templates = []; //array of {id, title, msg} filled with required stuff
$scope.msg_templates[0] = {id:'0', title:'{New Value}', msg:''}; //first item is to enter new value
$scope.msg_templates[1] = {id:'1', title:'TTT', msg:'TTT'};
$scope.msg_templates[2] = {id:'2', title:'XXX', msg:'XXX'};
.
.
//set default value
$scope.msg_sel = '';
$scope.msg_field = '';
//change msg function
$scope.change_msg_sel = function()
{
if($scope.msg_sel==null){
$scope.msg_field = '';
return false;
}
$scope.msg_field = $scope.msg_sel.msg;
};
[HTML]
<select ng-model="msg_sel" ng-change="change_msg_sel()" ng-options="v.title for v in msg_templates">
<option value="">Please Select -</option>
</select>
<textarea ng-bind-html="msg_field"></textarea>
Solve the problem myself, just manually override the field's value inside $scope.change_msg_sel using the good-ol-always-working-vintage-JS!
document.getElementById('msg_field').value=$scope.msg_field;
(so much for the amazing angular!!)

Get selected option in ngOptions with protractor

How can I get the object associated to the selected option inside within a dropdown (select)?
Here's my html:
<select ng-model="selSeason" ng-options="season as season.name for season in seasons"></select>
Every season is an object with several properties and I'd need to get the object associated to the selected object (and not only its text or value).
I know ng-repeat has something like (to select name of the 5th season):
element(by.repeater('season in seasons').row(4).column('name'));
Is there something similar for by.options() selector?
Thanks
You can use by.options with evaluate():
var seasonNames = element.all(by.options('season in seasons')).evaluate("season.name");
seasonNames.then(function (values) {
console.log(values); // array of season names is printed
});
You can also filter out the selected option with filter():
var selectedSeasonName = element.all(by.options('season in seasons')).filter(function (option) {
return option.getAttribute("selected").then(function (selected) {
return selected;
});
}).first().evaluate("season.name");
selectedSeasonName.then(function (value) {
console.log(value); // selected season name is printed
});
What you are looking for is the custom by.selectedOption locator.
element(by.selectedOption('model_name'))
For a better description, read this: https://technpol.wordpress.com/2013/12/01/protractor-and-dropdowns-validation/
I ended up evaluating not the selected option but the ng-model associated to the select:
HTML
<select ng-model="selSeason" ng-options="season as season.name for season in seasons"></select>
JS
element(by.model('selSeason')).evaluate('selSeason').then(function(season){
console.log(season.name);
});
Your binding looks good, you can read all the properties easily by using your ng-model variable 'selSeason', see this example
<select ng-model="user"
ng-options="x as x.name for x in users track by x.id"
class="form-control"
ng-required="true">
<option value="">-- Choose User --</option>
</select>
var id = $scope.user.id;
var name = $scope.user.name;
var role = $scope.user.role
For more detail check this

angularjs : select with different (key, value) not working properly

I am trying to load angular "select" with the following code
<select class="span11" ng-model="user.countryOfResidence" ng-options="c.option as c.value for c in countries" required>
Its loads the data into the select but the default selected value is empty.
my countries array is
$scope.countries = [{option:'TL', value:'TIMOR-LESTE'},
{option:'TK', value:'TOKELAU'},
{option:'TJ', value:'TAJIKISTAN'},
{option:'TH', value:'THAILAND'},
{option:'TG', value:'TOGO'},];
if i change 'TL' to 'TIMOR-LESTE', (same string for "option" and "value") it works fine. Can any one kindly tell me what is the problem with my code.
user object is
$scope.user = {
countryOfResidence : $scope.countries[0].value
};
A select populated with ng-options will set the ng-model field to what is specified as the value, not the option
In the example you've given, you're setting user.countryOfResidence to countries[0].value, which in this case is 'TIMOR-LESTE', but the value key is 'TL', so it won't select it by default.
For better readability, I always like to structure my select options with 'label' and 'value' keys, like so:
// Controller
$scope.countries = [
{value:'TL', label:'TIMOR-LESTE'},
{value:'TK', label:'TOKELAU'},
{value:'TJ', label:'TAJIKISTAN'},
{value:'TH', label:'THAILAND'},
{value:'TG', label:'TOGO'}
];
$scope.user = {
countryOfResidence: $scope.countries[0].value
};
};
// View
<select class="span11" ng-model="user.countryOfResidence" ng-options="c.value as c.label for c in countries" required=""></select>

Resources