How to change option name in Drupal 8 form element? - forms

I have sort link 'Best' in exposed form. I want after user click this link, link title changes to 'New'
I'm try this, but it don't work:
function helper_form_views_exposed_form_alter(array &$form, FormStateInterface $form_state, $form_id) {
if($form['#id']== 'views-exposed-form-pozdravleniya-taxonomy-term-page-1') {
$form['sort_by']['#title'] = '';
$form['sort_by']['#options']['created'] = '';
if ($form['sort_by']['#value'] == 'count') {
$form['sort_by']['#options']['count'] = 'New';
}
}
}
Also I'm try this, it don't work too:
function helper_form_views_exposed_form_alter(array &$form, FormStateInterface $form_state, $form_id) {
if($form['#id']== 'views-exposed-form-pozdravleniya-taxonomy-term-page-1') {
$form['sort_by']['#title'] = '';
$form['sort_by']['#options']['created'] = '';
if ($form_state->getValue('sort_by') == 'count') {
$form['sort_by']['#options']['count'] = 'New';
}
}
}
Screenshot form dump

Try with
$form_state->getUserInput()['sort_by']

Related

How to customise the ghost-text (drag item name) with AgGrid

As per title, is there a way to customise the "ghost text" with the (unmanaged) row-dragging implementation in AgGrid via the API?
I found workaround using valueGetter property to change this text.
Example configuration of column:
private dragDropColumn= {
rowDrag: true,
...
valueGetter: (params) => {
return params.data.myVariableFromRow;
}
}
Hope this helps
You can now use colDef.rowDragText to set a callback function to set the dragged text.
https://www.ag-grid.com/javascript-grid-row-dragging/#custom-row-drag-text
onRowDragEnter event,
you could search for the ghost element
and then append your custom class to it.
document.querySelectorAll('.ag-dnd-ghost')[0]
.classlist.add('my-custom-ghost-element');
Dont forget to follow the hierarchy of classes, otherwise you would end up using !important in the custom class :-)
// For updating text
search for the element with className ag-dnd-ghost-label
document.querySelectorAll('.ag-dnd-ghost-label')[0]
.innerHTML = 'your_custom_text';
Ghost element is added only during drag, once drag is ended, its removed from dom by Ag-Grid.
Hope this helps
I've researched this and there is nothing built in to ag-grid. I accomplished this by attaching to the onRowDragMove and onRowDragMove events.
I set a class variable 'isRowDragging' to only do this once while dragging.
I use the Angular Renderer2 class (this.ui) to find and update the Element of the ghost label.
All of this is available with vanilla javascript or other supported ag-grid frameworks.
this.gridOptions.onRowDragMove = (params: RowDragMoveEvent) => {
const overNode = params.overNode;
const movingNode = params.node;
if (!this.isRowDragging) {
this.isRowDragging = true;
if (!movingNode.isSelected()) {
if (params.event && params.event.ctrlKey) {
movingNode.setSelected(true);
}
if (params.event && !params.event.ctrlKey) {
movingNode.setSelected(true, true);
}
}
let labelText: string = '';
const selectedNodes = this.gridOptions.api.getSelectedNodes();
if (selectedNodes.length === 1) {
labelText = selectedNodes[0].data.Name;
}
else {
const guids: string[] = [];
let folderCount: number = 0;
let docCount: number = 0;
selectedNodes.forEach((node: RowNode) => {
guids.push((node.data.FolderGuid || node.data.DocumentGuid).toLowerCase());
if (node.data.FolderGuid !== undefined) {
folderCount++;
}
else {
docCount++;
}
});
if (folderCount === 1) {
labelText = '1 folder';
}
else if (folderCount > 1) {
labelText = folderCount + ' folders';
}
if (docCount === 1) {
labelText += (labelText !== '' ? ', ' : '') + '1 document';
}
else if (docCount > 1) {
labelText += (labelText !== '' ? ', ' : '') + docCount + ' documents';
}
}
console.log(this.ui.find(document.body, '.ag-dnd-ghost').outerHTML);
this.ui.find(document.body, '.ag-dnd-ghost-label').innerHTML = labelText;
}
}
this.gridOptions.onRowDragEnd = (event: RowDragEndEvent) => {
this.isRowDragging = false;
}
I am using ag-grid with react and using cellRendererFramework property of ColDef to use custom react component, my value getter returns object, so when I start dragging I am getting [object object], I added toString method to returning object and did the trick, below is my sample code
const col1 = {
rowDrag: true,
...
valueGetter: (params) => {
const {id, name} = params.data;
return {id, name, toString: () => name}; // so when dragging it will display name property
}
}

Why user comment is not in email order confirmation html opencart 2?

I noticed that in opencart 2.3.0.2 the order confirmation for admin contains the comments from the user, and the email that the user gets doesn't.
The user gets only the text version with the comment, not the HTML version with the comment.
In 2012 2013 the problem was that the comment wasn't passed at all into the emails.
https://github.com/opencart/opencart/pull/94
https://github.com/opencart-ce/opencart-ce/issues/12
It seems the problem was solved only partially.
The solution is:
Edit:
catalog/model/checkout/order.php
Put this code:
$data['ip'] = $order_info['ip'];
$data['order_status'] = $order_status;
if ($comment && $notify) {
$data['comment'] = nl2br($comment);
} else {
$data['comment'] = '';
}
if ($comment) {
if ($order_info['comment']) {
$data['comment'] = nl2br($comment) . '<br/><br/><strong>Comment:</strong><br/>' . $order_info['comment'];
} else {
$data['comment'] = nl2br($comment);
}
} else {
if ($order_info['comment']) {
$data['comment'] = $order_info['comment'];
} else {
$data['comment'] = '';
}
}
instead of:
$data['ip'] = $order_info['ip'];
$data['order_status'] = $order_status;
if ($comment && $notify) {
$data['comment'] = nl2br($comment);
} else {
$data['comment'] = '';
}
Or you can install this mod https://www.opencart.com/index.php?route=marketplace/extension/info&extension_id=32499&filter_search=add%20comment&filter_category_id=8&filter_license=0

Silverstripe 3.1.x getting values from Parent

I would like to get a generic function working for getting Data in Template of a Page and if the property is not set, getting it from the Parent or Parents Parent and so on. With generic I mean independent of Relations like db, HasOne, HasMany, ManyMany. Let's say I have this for ManyMany but would like to detect if it's a Object, HasManyList or ManyManyList or a value. Is anything like this built in or how would you go about?
function ManyManyUpUntilHit($ComponentName){
$Component = $this->getManyManyComponents($ComponentName);
if($Component && $Component->exists())
return $Component;
$Parent = $this->Parent();
if(is_object($Parent) && $Parent->ID != 0){
return $Parent->ManyManyUpUntilHit($ComponentName);
} else {
return null;
}
}
in template:
$ManyManyUpUntilHit(Teaser)
There is no in built method to do this in Silverstripe. You will need to write your own function to do this.
Here is an example to get a page's has_one, has_many or many_many resource by parameter, or go up the site tree until a resource is found, or we hit a root page:
function getComponentRecursive($componentName) {
// has_one
if ($this->has_one($componentName)) {
$component = $this->getComponent($componentName);
if (isset($component) && $component->ID)
{
return $component;
}
}
// has_many
if ($this->has_many($componentName)) {
$components = $this->getComponents($componentName);
if (isset($components) && $components->count())
{
return $components;
}
}
// many_many
if ($this->many_many($componentName)) {
$components = $this->getManyManyComponents($componentName);
if (isset($components) && $components->count())
{
return $components;
}
}
if ($this->ParentID != 0)
{
return $this->Parent()->getComponentRecursive($componentName);
}
return false;
}

how to save a collection form in symfony 1.4

I have created a collection form in symfony 1.4 and Propel 1.5 and everything displays properly but I cannot get the form to save to the database.
The form is used to edit multiple users at once.
I found this question and I implemented the suggestion of extending my collectionForm class with sfFormPropel, but when I do that I run out of memory. I cannot find what is being pulled from the database that would fill up the processes memory.
In my new save function I am not even doing anything.
Any ideas?
class ContactCollectionForm extends sfFormPropel
{
public function getModelName()
{
return 'ContactCollectionForm';
}
public function retrieveSubObject($fieldname, $model)
{
switch($fieldname)
{
default:
break;
}
return array();
}
public function save($con = null)
{
}
public function configure()
{
$user = $this->getOption('user');
$embedded = $this->getOption('embedded');
$custom = $this->getOption('custom');
$contact_list = $this->getOption('contact_list');
$cf = $custom['form'];
if(!array_key_exists(0, $cf['fields']['field']))
$cf['fields']['field'] = array($cf['fields']['field']);
$use_fields = array();
for($i=0;$i<count($contact_list);$i++)
{
foreach($cf['fields']['field'] as $field)
{
if($field['type'] == 'object')
{
// embed object form (ala: PersonData, Coordinate etc...)
$model = $field['model'];
$model_form = $model.'Form';
$sub_object = $contact_list[$i];
$sub_form = new $model_form($sub_object, array('user' => $user, 'embedded' => true, 'custom' => $field['fields']));
$this->embedForm($field['name'], $sub_form);
array_push($use_fields, $field['name']);
} // end field type == object
else
{
// standard form field
$this->setWidget($field['name'], CustomWidgetExtender::createSfWidget($field, $user, $this));
$this->widgetSchema->setLabel($field['name'], $field['label']);
if(trim($field['default']) != '')
$this->setDefault($field['name'], $field['default']);
// add field name to use_fields array
array_push($use_fields, $field['name']);
} // end field type != object
}
}
}
}
I ended up doing a rough hack by processing each form manually rather than trying to shoehorn this type of form into the symfony 1.x form framework.

Yii form model validation- either one is required

I have two fields on the form ( forgotpassword form ) username and email Id . User should enter one of them . I mean to retrieve the password user can enter user name or the email id . Could some one point me the validation rule for this ?
Is there any inbuilt rule I can use ?
( Sorry if it is already discussed or if I missed)
Thanks for your help
Regards
Kiran
I was trying to solve same problem today. What I've got is the code below.
public function rules()
{
return array(
// array('username, email', 'required'), // Remove these fields from required!!
array('email', 'email'),
array('username, email', 'my_equired'), // do it below any validation of username and email field
);
}
public function my_required($attribute_name, $params)
{
if (empty($this->username)
&& empty($this->email)
) {
$this->addError($attribute_name, Yii::t('user', 'At least 1 of the field must be filled up properly'));
return false;
}
return true;
}
General idea is to move 'required' validation to custom my_required() method which can check if any of field is filled up.
I see this post is from 2011 however I couldn't find any other solution for it. I Hope it will work for you or other in the future.
Enjoy.
Something like this is a bit more generic and can be reused.
public function rules() {
return array(
array('username','either','other'=>'email'),
);
}
public function either($attribute_name, $params)
{
$field1 = $this->getAttributeLabel($attribute_name);
$field2 = $this->getAttributeLabel($params['other']);
if (empty($this->$attribute_name) && empty($this->$params['other'])) {
$this->addError($attribute_name, Yii::t('user', "either {$field1} or {$field2} is required."));
return false;
}
return true;
}
Yii2
namespace common\components;
use yii\validators\Validator;
class EitherValidator extends Validator
{
/**
* #inheritdoc
*/
public function validateAttributes($model, $attributes = null)
{
$labels = [];
$values = [];
$attributes = $this->attributes;
foreach($attributes as $attribute) {
$labels[] = $model->getAttributeLabel($attribute);
if(!empty($model->$attribute)) {
$values[] = $model->$attribute;
}
}
if (empty($values)) {
$labels = '«' . implode('» or «', $labels) . '»';
foreach($attributes as $attribute) {
$this->addError($model, $attribute, "Fill {$labels}.");
}
return false;
}
return true;
}
}
in model:
public function rules()
{
return [
[['attribute1', 'attribute2', 'attribute3', ...], EitherValidator::className()],
];
}
I don't think there is a predefined rule that would work in that case, but it would be easy enough to define your own where for username and password fields the rule was "if empty($username . $password) { return error }" - you might want to check for a min length or other field-level requirements as well.
This works for me:
['clientGroupId', 'required', 'when' => function($model) {
return empty($model->clientId);
}, 'message' => 'Client group or client selection is required'],
You can use private property inside model class for preventing displays errors two times (do not assign error to model's attribute, but only add to model without specifying it):
class CustomModel extends CFormModel
{
public $username;
public $email;
private $_addOtherOneOfTwoValidationError = true;
public function rules()
{
return array(
array('username, email', 'requiredOneOfTwo'),
);
}
public function requiredOneOfTwo($attribute, $params)
{
if(empty($this->username) && empty($this->email))
{
// if error is not already added to model, add it!
if($this->_addOtherOneOfTwoValidationError)
{
$this->addErrors(array('Please enter your username or emailId.'));
// after first error adding, make error addition impossible
$this->_addOtherOneOfTwoValidationError = false;
}
return false;
}
return true;
}
}
don't forget "skipOnEmpty" attr. It cost me some hours.
protected function customRules()
{
return [
[['name', 'surname', 'phone'], 'compositeRequired', 'skipOnEmpty' => false,],
];
}
public function compositeRequired($attribute_name, $params)
{
if (empty($this->name)
&& empty($this->surname)
&& empty($this->phone)
) {
$this->addError($attribute_name, Yii::t('error', 'At least 1 of the field must be filled up properly'));
return false;
}
return true;
}
Yii 1
It can be optimized of course but may help someone
class OneOfThemRequiredValidator extends \CValidator
{
public function validateAttribute($object, $attribute)
{
$all_empty = true;
foreach($this->attributes as $_attribute) {
if (!$this->isEmpty($object->{$_attribute})) {
$all_empty = false;
break;
}
}
if ($all_empty) {
$message = "Either of the following attributes are required: ";
$attributes_labels = array_map(function($a) use ($object) {
return $object->getAttributeLabel($a);
}, $this->attributes);
$this->addError($object, $_attribute, $message . implode(',',
$attributes_labels));
}
}
}
yii1
public function rules(): array
{
return [
[
'id', // attribute for error
'requiredOneOf', // validator func
'id', // to params array
'name', // to params array
],
];
}
public function requiredOneOf($attribute, $params): void
{
$arr = array_filter($params, function ($key) {
return isset($this->$key);
});
if (empty($arr)) {
$this->addError(
$attribute,
Yii::t('yii', 'Required one of: [{attributes}]', [
'{attributes}' => implode(', ', $params),
])
);
}
}