In ember, how to change values of checkboxes based on another - ember.js

I have four checkbox and I want to check automatically checkbox with id = 2 if checkbox with id = 4 is checked.
I did the following but did not get the output. Could someone help me with this.
{#each category in checkboxList}}
{{input id = category.CHECKBOX_ID type="checkbox" checked=category.IS_CHECKED}}
{{#if category.CHECKBOX_ID == 4 && category.IS_CHECKED == true}}
{{action 'CheckSize'}}
{{/if}}
The checkboxList is
[
{"IS_CHECKED":false,"CHECKBOX_ID":1},
{"IS_CHECKED":false,"CHECKBOX_ID":2},
{"IS_CHECKED":true,"CHECKBOX_ID":3},
{"IS_CHECKED":false,"CHECKBOX_ID":4}
]

You'll want to manage the state of the checkboxes separately.
Here is an example I did for another SO question that had a similar problem to solve:
https://ember-twiddle.com/468a737efbbf447966dd83ac734f62ad
The gist of it is
we use a single action in response to a click of any checkbox:
#action
toggleChecked(id) {
const newTree = check(this.options, id);
this.set('options', newTree);
}
In this example (taken from the ember-twiddle), all of the logic is extracted to a pure-function named check.
Check itself is pretty involved, but because the application logic is different between that example and the problem you've run in to, I'll just show the entry point function:
export function check(tree, id, transform = toggle) {
if (tree === undefined) return undefined;
if (Array.isArray(tree)) {
return tree.map(t => check(t, id, transform));
}
if (tree.id === id || id === 'all') {
return checkNode(tree, id, transform);
}
if (tree.children) {
return checkChildren(tree, id, transform);
}
return tree;
}
This is just an example of how you can immutably modify the representation of all checkboxes by using a pure function. Your logic may vary.
Hope this helps :)

Related

Drupal 8: How to customize the block content on specific page

I'm able to change the block content by using the hook as below. But, I would like to change the block content (for eg: system_main_block) only if it appears on specific page. But, I'm not sure how to get the page id or title in the hooks below. Appreciate help.
function yourmodule_block_view_alter(array &$build, \Drupal\Core\Block\BlockPluginInterface $block)
{
if ($block->getBaseId() === 'system_powered_by_block') {
$build['#pre_render'][] = '_yourmodule_block_poweredby_prerender';
}
}
function _yourmodule_block_poweredby_prerender(array $build) {
$build['content']['#markup'] = Markup::create('Your text');
return $build;
}
You can check the route name like this:
function yourmodule_block_view_alter(array &$build, \Drupal\Core\Block\BlockPluginInterface $block) {
if ($block->getBaseId() === 'system_powered_by_block' && \Drupal::routeMatch()->getRouteName() === '<your_route_name>') {
$build['#pre_render'][] = '_yourmodule_block_poweredby_prerender';
}
}

How to get a list of checked boxes in grails

In grails, I am trying to get a list of checked check boxes.
I have the list of check boxes, but my issues are two:
1) when I click on a single item in the list and click submit - I only get the value "on". If I click more than one check box item, I get something like this:
[Ljava.lang.String;#5a37f9f7
2). I do not get a list or the name of the item checked.
Here is my code for the check boxes in the gsp:
<g:form action="submitForm">
<ul class="columns3">
<g:each in="${name}" var="fileName" >
<g:checkBox value="${false}" name="${ 'fileName'}" /> ${fileName.replaceFirst(~/\.[^\.]+$/, '')}<br>
</g:each>
</ul>
<br>
<br>
<g:submitButton name="Submit"/>
</g:form>
and here is the controller code (groovy):
class Read_dirController {
def index() {
def list = []
def dir = new File("/home/ironmantis/Documents/business/test_files")
dir.eachFileRecurse (FileType.FILES) { file ->
list << file
}
list.each {
println it.name.replaceFirst(~/\.[^\.]+$/, '')
}
render(view: "index", model: [name:list.name])
params.list('fileName')
}
def displayForm() { }
def submitForm(String fileName) {
render fileName
//render(view: "tests_checked", fileName)
}
}
I tried to bind an id to the check boxes, but I keep getting an exception error.
Any help you can give I truly appreciate it; I am new to grails.
ironmantis7x
You can use the beautiful command object for this. For this ,first make a class RequestCO having the boolean fields.
class RequestCO {
boolean isChecked;
String name;
}
And
class RequestParentCO {
List<RequestCO> requestCOs = [].withLazyDefault { new RequestCO() }
}
Now you just simply bind all your request to RequestParentCO in your action:
def submitForm(RequestParentCO parentCO) {
println parentCO.requestCOs.findAll { it.isChecked }
}
This will give you all the checked checkboxes results.
GSP
<g:form action="process">
<ul class="columns3">
<g:each in="${["one", "two", "three"]}" var="fileName" status="i">
<g:hiddenField name="requestCOs[${i}].name" value="${fileName}"/>
<g:checkBox name="requestCOs[${i}].isChecked"/> ${fileName}<br>
</g:each>
</ul>
<g:submitButton name="Submit"/>
This way,
def submitForm() {
def values = request.getParameterValues("fileName")
//here values contains string array which are selected in checkbox
}
you can use request.getParameterValues("fileName") method, this will give selected checkbox in string array

React/Jasmine/Karma/Phantom Unit Test: findDOMNode and renderIntoDocument not working as expected

I'm trying to write a simple unit test and can't seem to figure it out. I want to test a bootstrap modal to ensure it displays the correct contents when I pass certain object properties to it. Here's what my modal code looks like:
import React, { Component, PropTypes } from 'react';
import { Button, Modal } from 'react-bootstrap';
class ModalBox extends Component {
render() {
const { modalBox } = this.props;
let content;
if (modalBox.contentBody) {
content = modalBox.contentBody;
} else {
content = (
<span>
<Modal.Header closeButton onHide={this.close.bind(this)}>
<Modal.Title>{modalBox.title}</Modal.Title>
</Modal.Header>
<Modal.Body>
{modalBox.message}
</Modal.Body>
{modalBox.isConfirm &&
<Modal.Footer>
<Button onClick={modalBox.onCancel} className="modal-button cancel">{modalBox.cancelText || 'Cancel'}</Button>
<Button onClick={modalBox.onConfirm} className="modal-button confirm">{modalBox.confirmText || 'Confirm'}</Button>
</Modal.Footer>
}
</span>
);
}
return (
<Modal show={typeof modalBox != 'undefined'} onHide={this.close.bind(this)} dialogClassName={modalBox.dialogClassName || ''} backdrop={modalBox.backdrop || true}>
{content}
</Modal>
);
}
}
So for a test, I want to make sure that if I pass the prop modalBox containing the contentBody field that it just returns the contentBody for the modal body. Here's an example of what I'm trying to test:
it("renders only contentBody when provided", () => {
let modalBoxObj = {
contentBody: <div className="test-content-body">This is a test.</div>
};
let element = React.createElement(ModalBox, {modalBox: modalBoxObj});
let component = TestUtils.renderIntoDocument(element);
let modalWrapper = TestUtils.scryRenderedDOMComponentsWithClass(component, 'modal');
// modalWrapper returns an empty array, so this returns "Expected 0 to be 1"
expect(modalWrapper.length).toBe(1);
let testBody = TestUtils.scryRenderedDOMComponentsWithClass(component, 'test-content-body');
// testBody returns an empty array, so this returns "Expected 0 to be 1"
expect(testBody.length).toBe(1);
// this returns "TypeError: 'undefined' is not an object (evaluating 'testBody[0].innerHTML')"
expect(testBody[0].innerHTML).toEqual("This is a test.");
}
I've also tried doing shallow rendering with TestUtils.createRenderer and trying that approach, but had no luck with it. Based on the examples I've seen online and previous testing experience with react <0.14, I feel this test should work. I just don't know what I'm missing or misunderstanding. In the past, I did something like below and just looked at the componentNode object to find elements and such, but componentNode is returning null.
let component = TestUtils.renderIntoDocument(element);
let componentNode = findDOMNode(component);
Thanks for your help!
The solution ended up being to add a ref to the ModalBox component. Once added, we were able to target the node like this:
let component = TestUtils.renderIntoDocument(<ModalBox modalBox={modalBoxObj} />);
let componentNode = findDOMNode(component.refs.modalBox._modal);

Simple boolean conditional from AJAX (ember.js)

I'm trying to do something which must be really simple to accomplish in Ember.
I want to show a button in my template based on the boolean state of a property:
{{#if canFavoriteTag}}
{{d-button action="favoriteTag" label="tagging.favorite" icon="star-o" class="admin-tag favorite-tag"}}
{{else}}
{{d-button action="unFavoriteTag" label="tagging.unfavorite" icon="star-o" class="admin-tag favorite-tag tag-unfavorite"}}
{{/if}}
I have created a property called canFavoriteTag with a function which I want to return true or false to the template based on whether the user can favorite the tag or not:
export default Ember.Controller.extend(BulkTopicSelection, {
canFavoriteTag: function() {
const self = this;
var ticker = this.get('tag.id');
console.log('checking can fav stock:' + ticker);
Discourse.ajax("/stock/get_users_favorite_stocks", {
type: "GET",
}).then(function(data) {
var favable = true;
for (var i = data.stock.length - 1; i >= 0; i--) {
var stock = jQuery.parseJSON(data.stock[i]);
if(ticker.toLowerCase() == stock.symbol.toLowerCase()) { console.log(ticker + ' is a favorite stock: ' + stock.symbol.toLowerCase()); favable = false; }
}
console.log(favable);
return favable;
});
}.property('canFavoriteTag') <-- unsure about this?
...
When the page loads, the wrong button shows (always the "false" one).. I see in the console that the favable variable gets set to false when the ajax call completes, but the button never changes. How do I get it to show the right button based on the function? Do I need to use a promise? If so, how?

Grails: How does that the UPDATE function work?

I got rid of the original UPDATE gsp Grails offers.
I put it in the first row of my list.gsp table and change all the values of the table to g:textfield so they can be edited without going to the save.gsp
But now I'm trying to make it work, and I can't.
I added a update button in the last column of the row, of every row.
When I change the values of the g:textfields and click the update button it tells me
Density #ID updated
but the values do not change.
I think I am doing something wrong with def update in the controller.
Here is the code:
def update = {
log.info "Entering Action ${actionUri}"
def densityInstance = Density.get(params.id)
if (densityInstance) {
if(params?.Rcommodity) {
println "${params.Rcommodity}"
}
if (params.version) {
def version = params.version.toLong()
if (densityInstance.version > version) {
densityInstance.errors.rejectValue("version", "default.optimistic.locking.failure", [message(code: 'density.label', default: 'Density')] as Object[], "Another user has updated this Density while you were editing")
render(view: "list", model: [densityInstance: densityInstance])
return
}
}
densityInstance.properties = params
if (!densityInstance.hasErrors() && densityInstance.save(flush: true)) {
flash.message = "${message(code: 'default.updated.message', args: [message(code: 'density.label', default: 'Density'), densityInstance.id])}"
redirect(action: "list", id: densityInstance.id)
}
else {
redirect(action: "list", id: densityInstance.id)
}
}
else {
flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'density.label', default: 'Density'), params.id])}"
redirect(action: "list")
}
}
The Rcommodity is the name of the textfields created, I put a println to see if the value was right, now I don't know how to make the value of the textfield be the one entered, it gives me the same value it had before but it gives me the message saying that it was updated.
The controller is DensityController and the domain is density
Any help would be greatly appreciated. Thanks :D
Looks from the flash message being printed as though the instance is being updated (though the "#ID" bit looks odd - have you replaced the actual id?).
It might be that
densityInstance.properties = params
is not actually be matching any instance properties, so none are actually being changed before the save. Are you sure you've named your gsp input fields to match the names of your Density class fields? Is Rcommodity a property of Density, for example?
Might help to add the form bit of your gsp page, as well as the Density domain class.