Aurelia Binding errors ( on browser console) - aurelia

I am using below snippet in html
value.two-way="lstName.IsBlocked ? 'Blocked' : Value2 + ' %'"
on console it shows error as
Uncaught Error: Binding expression
"lstName.IsBlocked?'Blocked':Value2+' %'" cannot be assigned to.
at b.a.assign (aurelia.js?v=1.0009:59)
at a.updateSource (aurelia.js?v=1.0009:61)
at a.call (aurelia.js?v=1.0009:61)
at a.v [as callSubscribers] (aurelia.js?v=1.0009:58)
at a.notify (aurelia.js?v=1.0009:60) `
What can be the reason for this ?
Thanks in advance!

Since you're using a two-way binding, the binding expression needs to be assignable.
As the error says: "lstName.IsBlocked?'Blocked':Value2+' %'" cannot be assigned to.. If your bound property changes from the view, it would have to be able to write back to the expression and update the source value in your view model. You can't really write to an inline if.
Change two-way to to-view and it should work.
EDIT:
Since you need the expression to be writable, you could use a ValueConverter to solve the problem (assuming Value2 is what you want to write to):
export class BlockedValueConverter {
toView(value, isBlocked) {
return isBlocked ? 'Blocked' : value + ' %';
}
fromView(value) {
return value;
}
}
Then in your html (don't forget to require the valueConverter or use globalResources):
value.two-way="Value2 | blocked:lstName.IsBlocked"

Related

custom boolean attributes not binding

Custom boolean attributes do not bind like built in. checked.bind='1===2' will not include the checked attribute in the tag. myboolatt.bind='1===2' WILL include the myboolatt in the tag. I did myboolatt.bind='1===2 | boolconverter' to log out the value and it says false.
So what am I doing wrong? It seems Aurelia is inconsistent on binding expressions. Another instance is I can do this title=${$index<12} inside a repeat and I get what is expected. So I thought this would work - myboolatt.bind=${$index<12}. That doesn't even compile.
Believe me I have read the all the doc (doesn't mean I didn't miss something) and many posts including the long running discussions between the Aurelia team concerning boolean attributes.
I have wrapped expressions in "" and in ${} and in both but just can't get it to work.
It feels like I am missing 1 vital piece of information that will magically explain these inconsistencies and slay my frustration. One of the reasons I like Aurelia so much (on top of convention based) is that I have actually just guessed at a few things - thinking this is how I would do it - and ding-dang if they didn't just work.
I really feel like this should just work. So again I ask - what am I doing wrong?
Thanks
If you are using .bind, you bind it to the att variable in your js/ts file, and you should not use any dollar signs or brackets.
For example, myboolatt.bind=${$index<12} should be myboolatt.bind="$index<12". The use of the dollar sign in index has nothing to do with the bindings. This is just a variable provided by Aurelia.
When you want to use variables without bind you use ${variable}.
The checked attribute not being present, I in the tag I'm guessing is because it's evaluated to false, and the checked attribute is not a true/false attribute. A input that's checked will look like <input type="checkbox" checked/>
It was not Aurelia binding. I initially created bool attributes but did not have a need to bind. They were just empty classes. Then I needed binding so I added the necessary methods. What ended up causing the confusion was using myboolatt sends no argument into valueChanged where myboolatt.bind sends T or F. Not being a regular js'er this threw me a bit and I see there are a number of ways to handle. Anyway here are the attributes and usage. Hope it helps someone else.
Thanks
function private_ValueChanged(self, att, value) {
if (value === false) self.element.removeAttribute(att);
else self.element.setAttribute(att, '');
}
export class toggleCustomAttribute {
static inject = [Element];
constructor(element) { this.element = element; }
valueChanged(newValue, oldValue) { private_ValueChanged(this, 'toggle', newValue);
}
export class radioCustomAttribute {
static inject = [Element];
constructor(element) { this.element = element; }
valueChanged(newValue, oldValue) { private_ValueChanged(this, 'radio', newValue); }
}
<ff-button repeat.for="keymen of keyChangeMenu" radio.bind="$index<12" class='ff-button' click.delegate="keyChangeClick($event.target)" id.bind="$index+'_key'" >
${keymen[0]}<sup>${keymen[1]}</sup>
</ff-button>

Assertion Failed: Expected the primary data returned by the serializer for a `queryRecord` response to be a single object but instead it was an array

I have just got this error a few days ago. Whenever I try to run
this.store.queryRecord('user', {filter:{username : params.username}});
It shows error: Assertion Failed: Expected the primary data returned by the serializer for a queryRecord response to be a single object but instead it was an array.
What is the problem here?
You backend should return one object not array.
Found a way to avoid this problem. Instead of queryRecord ( which seems to be changed by ember-data developer team ), I use store.query like this:
this.store.query('user', {filter:{username : params.username}}).then(function(user){return user.get('firstObject')});
I encountered similar situation , had 2 routes
this.get('/clients', function() {return {data: [allClientsDataJson]};});
this.get('/clients:id', function() {return {data: [oneClientDataJson]};});
But after using queryRecord i got same error. Thing was that second route was never called and first one was called in both causes. So instead of single result there was array with all results in second call.
After knowing only first one is always called i edited it to :
this.get('/clients', function(db, request) {
if(!Ember.isEmpty(request.queryParams)) { return oneClientDataJson
} else { return allClientsDataJson }

An interesting Restlet Attribute behavior

Using Restlet 2.1 for Java EE, I am discovering an interesting problem with its ability to handle attributes.
Suppose you have code like the following:
cmp.getDefaultHost().attach("/testpath/{attr}",SomeServerResource.class);
and on your browser you provide the following URL:
http://localhost:8100/testpath/command
then, of course, the attr attribute gets set to "command".
Unfortunately, suppose you want the attribute to be something like command/test, as in the following URL:
http://localhost:8100/testpath/command/test
or if you want to dynamically add things with different levels, like:
http://localhost:800/testpath/command/test/subsystems/network/security
in both cases the attr attribute is still set to "command"!
Is there some way in a restlet application to make an attribute that can retain the "slash", so that one can, for example, make the attr attribute be set to "command/test"? I would like to be able to just grab everything after testpath and have the entire string be the attribute.
Is this possible? Someone please advise.
For the same case I usually change the type of the variable :
Route route = cmp.getDefaultHost().attach("/testpath/{attr}",SomeServerResource.class);
route.getTemplate().getVariables().get("attr") = new Variable(Variable.TYPE_URI_PATH);
You can do this by using url encoding.
I made the following attachment in my router:
router.attach("/test/{cmd}", TestResource.class);
My test resource class looks like this, with a little help from Apache Commons Codec URLCodec
#Override
protected Representation get() {
try {
String raw = ResourceWrapper.get(this, "cmd");
String decoded = new String(URLCodec.decodeUrl(raw.getBytes()));
return ResourceWrapper.wrap(raw + " " + decoded);
} catch(Exception e) { throw new RuntimeException(e); }
}
Note my resource wrapper class is simply utility methods. The get returns the string of the url param, and the wrap returns a StringRepresentation.
Now if I do something like this:
http://127.0.0.1/test/haha/awesome
I get a 404.
Instead, I do this:
http://127.0.0.1/test/haha%2fawesome
I have URLEncoded the folder path. This results in my browser saying:
haha%2fawesome haha/awesome
The first is the raw string, the second is the result. I don't know if this is suitable for your needs as it's a simplistic example, but as long as you URLEncode your attribute, you can decode it on the other end.

Linqpad - Outputting into anchor to use title

I have a db that stores exception messages.
I would like to create a query that gets these exceptions but instead of dumping huge amounts of text i would prefer it to be "on demand".
I figured putting the exception into an anchor tag like so and then reading the message when needed by mousing over it would work... apparently not.
var logsForErrors = (from error in Logs
select new {
error = LINQPad.Util.RawHtml("<a title='"+ error.Exception+"'></a>"),
errorDate = error.Date,
errorMessage = error.Message
}).Take(10);
logsForErrors.Dump();
This is throwing an exception (lol) - "Cannot parse custom HTML: "
Encoding the exception message
...RawHtml("<a title='"+ Uri.EscapeDataString(error.Exception)+"'></a>")
Message Could not translate expression 'RawHtml((("h__TransparentIdentifier0.error.Exception)) +
"'>"))' into SQL and could not treat it as a local expression.
will generate a new error
Any ideas? - I am open to alternative solutions to this also.
I just want a container for the message instead of it just dumping right into the output as it it so huge!.
Thanks,
Kohan
Have you tried using the "Results to DataGrids" mode in the recent betas? It might do just what you need without having to write anything else.
Edit: your error was probably due to emitting HTML without escaping the text. The easiest solution is to call Util.RawHtml with an XElement instead of a string. You could write an extension method that does what you want like this:
public static class Extensions
{
public static object Tooltipize (this string data)
{
if (string.IsNullOrEmpty (data) || data.Length < 20) return data;
return Util.RawHtml (new XElement ("span", new XAttribute ("title", data), data.Substring (0, 20)));
}
}
Put this into My Extensions and you can use it from any query.

Yii model is validating but data could not be saved

I have a yii application. Data is validated properly. the $model->validate() returns true but data is not being saved. Is there any way that I know about the error. It does nothing. neither prints error nor any warning.
if (isset($_POST['Invoice'])) {
$model->validate();
$model->attributes = $_POST['Invoice'];
if (!$model->validate()) {
die(CVarDumper::dump($model->errors,10,true));
}
if ($model->save()) {
die("Data saved");
$this->redirect(array('view', 'id' => $model->id));
} else {
CVarDumper::dump($model->attributes,10,true);
CVarDumper::dump($model->errors,10,true);
}
}
if you override beforeSave or afterFind method in your model,
public function beforeSave() {
return true; //don't forget this
}
public function afterFind() {
return true; //don't forget this
}
make sure you return true for those function
If save() is returning true and there are no errors as such in your database and queries. Only thing, thats possible is you haven't marked some of the column safe for mass assignment via "$model->attributes".
Make sure the column you are trying to save are marked safe in the "rules" function in your model. You can mark columns safe via adding the following rule in "rules" function in the model.
array ( "column_name1, column_name2 ....." , "safe" )
I've just ran into something similar to this. Everything was validating correctly, and $model->save() was returning true, but no data was saved in the database.
The problem and solution was that I was creating the $model object like so:
$model = ClassName::model();
but you need to create the object like so:
$model = new ClassName;
If you have this problem, you replace this:
$model->save(false)
This solves your problem.
If you use $model->save(); the filters is running that is not good for you.
Fire up some logging and see what going on...
I got the same error when I was using reCaptcha. I just did this and it worked:
$model->scenario = NULL;
Make sure you do this AFTER validation.
I had the same issue, my mistake was with the post name in the controller, where I used $model->save. I had given wrong - if(isset($_POST['postname']))
If I am not wrong, you are doing an AR save() in the $model->save() method. You do not get any error, but the data is not saved as well.
If this is the case you would like to do a:
die(CVarDumper::dump($arObj->errors,10,true));
after the $arObj->save(); call. Most of the time this happens because of the Database rejecting the values provided for insert or update.
Also do not override your model constructor:
function __construct() { } // don't do this
The issue for me was that I had a property for the column name in the ActiveRecord class, so it wasn't saving.
You should not declare properties for column names as I guess the magic methods __get() and __set() are used to save data, I guess by checking if there are column changes when you click the save() method to avoid useless SQL queries. In my case, because the column was a user-declared property, it wasn't in the columns list and therefore changes to it were not detected.
Hope this helps other people