Post comments into a specific status - angularjs

As the title says, I'm trying to post a comment into a specific user status. So far, I can post comments and save them into firebase but those comments are displayed in all the statuses and of course it's because they are not referenced to that specific user status.
How can I achieve that?
Someone told me that each comment should have a property with the ID of the status or user to be able to make the query. But that's that I dont know how to do.
This is my firebase structure:
Firebase:
-users
-- 444198db-1052-4d8d-a1cd-c7e613fbe7c9
--- Status
--- StatusDate
-comments
-- K-nRDUXT07BllsO7T99
--- comment
--- commentDate
Here is my code to save the comments into the comments node in firebase:
$scope.addComment = function(){
console.log("Adding Comment");
var comment = $scope.comment;
console.log(comment);
var refcomment = new Firebase("https://firebaseurl/comments/");
refcomment.push({
comment: comment,
commentDate: Firebase.ServerValue.TIMESTAMP
});
}
And here the code to show the comments (ng-repeat):
refcomments = new Firebase("https://firebaseurl/comments/");
$scope.comments = $firebaseArray(refcomments);
HTML:
<div ng-controller="ComentariosCtrl">
<div class="input-group">
<input type="text" class="form-control" placeholder="Comment Here..." ng-model="comment">
<span class="input-group-btn">
<button class="btn btn-default" type="button" ng-click="addComment()">Post!</button>
</span>
</div><!-- /input-group -->
<div class="cmt">
<div class="panel" ng-repeat="comentarios in comments">
<hr >
<p>{{comentarios.comment}}</p>
</div>
</div><!--FIN DE COMENTARIOS -->
</div>
Any ideas?
Thanks in advance

It's not clear what 'posting a comment into a specific user status' means exactly but here are a couple of thoughts (and I hope I'm on the right track)
In your example, there's no way to 'relate' the user to the comment. There's about 100 different ways to do it but one flattened structure that could be easily queried for a users comments is:
users
user_id_0001
user_name: "Bill"
user_status: "some status"
status_date: "some status_date"
user_id_0002
user_name: "Ted"
user_status: "some status"
status_date: "some status_date"
comments
comment_id_0001
made_by_user_id: "user_id_0001"
comment: "Hey Ted!"
comment_id_0002
made_by_user_id: "user_id_002"
comment: "Hey Bill! Let's go on a most excellent adventure"
The comments node could then be queried for made_by_user_id = "user_id_0001" which would retrieve all of Bill's comments. Remember in Firebase the flatter the better. Excellent!
Another, less flexible option is to store a users comments within their own users node
users
user_id_0002
user_name: "Ted"
user_status: "some status"
status_date: "some status_date"
comments
comment_id_0001:
comment: "Just call me Neo"
timestamp: "some timestamp"
comment_id_0002:
comment: "I feel like I'm in the Matrix"
timestamp: "some timestamp"
comment_id_0003:
comment: "You trying to tell me.. that I can dodge bullets?"
timestamp: "some timestamp"
Now if you want to retrive all of a users comments, they are just within their own users node at /users/user_id_0002/comments
It really depends on your usage of the data.
The key is to disassociate your data from the node name it's stored in. Using the push() function will generate a unique id can help do that - in the examples above user_id_0001 an comment_id_0001 are generated in this way.

Related

How to apply Break lines in React Modal?

As title.
I have an array that contains some messages that I want to show to End user:
var Errors=[
"Your name is empty!",
"Your tags are empty!",
"No zip files to upload!",
];
How could I use the Modal.error call and show a dialog with break lines:
Your name is empty!
Your tags are empty!
No zip files to upload!
That is one line for a string in the array? I've tried use <br /> to the Errors.join() function call and I see the less than and great than marks; I've tried to use "\r\n" to Errors.join() but I havent' got the effects.
Sorry about that English is not my mother language. I could add some information that I didn't provide yet.
Try this:
Modal.error({
title: 'This is an error message',
content: <div dangerouslySetInnerHTML={{__html:`${Errors.join('<br/>')}`}}/>,
});

Wordpress addon to add data to a database and then call the data

I know this question is probably going to get downvoted and I will probably get into trouble but I am hoping someone may be able to help me with my situation.
On my site I use json to download data from an external source, and then I style it beautifully.
Within the json data is an individual ID for each data set.
What I want to accomplish is to have a database where I can insert the ID and a url link.
I have created the table within the wordpress database via phpMyAdmin, but I want to create a page within the admin section where I can simply add the data in.
For displaying the json data I use a php insert addon, within that php clip i want to do a piece of code that checks the database for the id within my custom database and displays the link.
I will be honest I don't know where to start on this, even if its just a link to a source that shows me how to create an admin page and submit data to the database within wordpress dashboard.
I really appreciate any help given and like I say I know I should try harder, but when ever I do a search all I get is 100's of references to add an admin to the database manually.
Thanks,
Adam
Edit I just realized I never put any table information in my question.
The table name within wordpress is called: wp_home_tickets
within that are 3 fields: id (auto increasement), gameid (numeric) and ticketlink (text)
thanks.
For adding a custom settings page in your admin, use the Settings API https://codex.wordpress.org/Settings_API
Here is a nice tutorial using it https://deliciousbrains.com/create-wordpress-plugin-settings-page/#wp-settings-api
To fetch data from your custom table, use the wpdb class https://developer.wordpress.org/reference/classes/wpdb/. More specifically, you can use wpdb::get_results if you will have multiple rows sharing the same id https://developer.wordpress.org/reference/classes/wpdb/get_results/
Or wpdb::get_row if you will ever only have one https://developer.wordpress.org/reference/classes/wpdb/get_row/
Hope this helps you out!
For anyone wishing to see how it was done, here is how I did it.
I created a file in my theme called db_admin_menu.php and added the following to it:
<?php
function ticket_admin_menu() {
global $team_page;
add_menu_page( __( 'Tickets', 'sports-bench' ), __( 'Tickets', 'sports-bench' ), 'edit_posts', 'add_data', 'ticket_page_handler', 'dashicons-groups', 6 ) ;
}
add_action( 'admin_menu', 'ticket_admin_menu' );
function ticket_page_handler() {
$table_name = 'wp_home_tickets';
global $wpdb;
echo '<form method="POST" action="?page=add_data">
<label>Team ID: </label><input type="text" name="gameid" /><br />
<label>Ticket Link: </label><input type="text" name="ticketlink" /><br />
<input type="submit" value="submit" />
</form>';
$default = array(
'gameid' => '',
'ticketlink' => '',
);
$item = shortcode_atts( $default, $_REQUEST );
$gameid = $item['gameid'];
if ($wpdb->get_var("SELECT * FROM wp_home_tickets WHERE gameid = $gameid ")) { echo 'Ticket already exists for this game.'; goto skip; }
if (!empty($_POST)) { $wpdb->insert( $table_name, $item ); }
skip:
}
?>
I then put this code in my script that fetches and displays the json:
$matchid = $match['id'];
$ticket_url = $wpdb->get_var("SELECT ticketlink FROM wp_home_tickets WHERE gameid = '$matchid' ");
if ($ticket_url) { echo 'Get Tickets'; }
I hope someone does find it of use, i did have to use a wordpress plugin called `Insert PHP Code Snippet' by xyzscripts to be able to snippet the php to a shortcode, but that is not the purpose of this post.
Thanks again for your help.

Flask and sqlite: Failing to insert values into the database

I have the following code in the main.py file. It appears to work in all instances, note when I print out user_details, it prints out the tuple: test,test,test (filled in to the form), so the post request is working. However, somehow, it is not being actually written to the database.
Main nature of error: The insertion is not taking place.
Can someone spot an error in my code?
#ADD COMMENT GET POST REQUEST FUNCTION
#app.route('/add',methods=['GET','POST'])
def addcomment():
if request.method=="GET":
return render_template('addcomment.html')
else:
user_details=(
request.form['title'],
request.form['name'],
request.form['comment']
)
#print(user_details)
insertcomment(user_details)
return render_template('addsuccess.html')
#INSERTING comments into the actual database
def insertcomment(user_details):
connie = sqlite3.connect(db_locale)
c=connie.cursor()
sql_insert_string='INSERT INTO comments (title, name, comment) VALUES (?,?,?)';
c.execute(sql_insert_string,user_details)
connie.commit
connie.close()
print(user_details)
def query_comments():
connie = sqlite3.connect(db_locale)
c=connie.cursor()
c.execute("""
SELECT * FROM comments
""")
userdata=c.fetchall()
return userdata
My suspicion is that there is something wrong with these lines (that is the second function)
insertcomment()
connie = sqlite3.connect(db_locale)
c=connie.cursor()
sql_insert_string='INSERT INTO comments (title, name, comment) VALUES (?,?,?)';
c.execute(sql_insert_string,user_details)
The def addcomment(): function works fine as far as I can see, rendering and returning the right html page on clicking submit.
On the html side, the only thing I can think of that MAY be causing an error is the order of the fields. In the database the fields are Name, Title, Comment (in that order), but in the HTML and the query, they are Title, Name, Comment (in that order specified).
For reference, the HTML file (the form that accepts that data) is below:
<div class="form-group">
<label for="exampleInputEmail1">Title (or catchy caption!)</label>
<input type="text" class="form-control" id="title" name="title" aria-describedby="emailHelp">
</div>
<div class="form-group">
<label for="exampleInputPassword1">Name</label>
<input type="text" class="form-control" id="name" name="name">
</div>
<div class="form-group">
<label for="exampleFormControlTextarea1">Add your amazing answer here:</label>
<textarea class="form-control" id="comment" name="comment" rows="3"></textarea>
</div>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary">Submit</button>
</form>
On the home page, the data is rendered as follows. I've had to switch the numbers around as you can see, as 2= title 1=name and 3 = comment
{% for user in user_data%}
<tr>
<th scope="row">{{user[0]}}</th>
<td>{{user[2]}}</td>
<td>{{user[1]}}</td>
<td>{{user[3]}}</td>
</tr>
{% endfor %}
Whether the above has anything to do with the error, I don't know (the order)...but I cannot think why.
Finally, here is the table populate .py file. You'll notice there is one extra field - date. Again, could this be a factor?
#populate database file
import sqlite3
db_locale='users.db'
connie=sqlite3.connect(db_locale)
c=connie.cursor() #use this to create commands
#creating a multi-line instruction
c.execute("""
INSERT INTO comments (name,title,comment,date_posted) VALUES
('Ruth Marvin','42','Yeah.Someone was going to say 42','20th July 2050'),
('Jonathan Peter','Meaning?','Surely we need to first define meaning','13th August 2050')
""")
connie.commit()
connie.close()
Can anyone explain why the data is not being POSTED/INSERTED into the database.
The error is in the function insertcomment(). You are missing the brackets with commit:
connie.commit
Just change to:
connie.commit()
which will save the changes to the database. Everything else looks fine including the database query. You are right in using a parameterised query.
sql_insert_string="INSERT INTO comments (title, name, comment) VALUES (%s,%s,%s)"
c.execute(sql_insert_string, user_details)
connie.commit()
this should work. Wrap your db operations into a try, except block to figure out whats wrong with your queries.
try:
sql_insert_string="INSERT INTO comments (title, name, comment) VALUES (%s,%s,%s)"
c.execute(sql_insert_string, user_details)
connie.commit()
except Exception as e:
print(e)
You need to format your SQL insertion string using Python's format() function from the standard library.
Your code:
sql_insert_string='INSERT INTO comments (title, name, comment) VALUES (?,?,?)';
Should be like this:
sql_insert_string='INSERT INTO comments (title, name, comment) VALUES ({}, {}, {})'.format(user_details[0], user_details[1], user_details[2])
Then on your c.execute line just pass sql_insert_string as a parameter. Also, I've found that the flask-sqlalchemy module saves countless headaches, but kudos to you for taking the time to learn SQL and coding it like this.

Angular 5 disable and enable checkbox based on condition

I'm trying to implement a validation in which i want to disable the button if a specific value entered by user matches the value returned from a service, below is my code:
In the component, i call the service which returns the usernames like below, here is the console log for (UserNames):
0:{Name: "John", userId: "23432"}
1:{Name: "Smith", userId: "12323"}
2:{Name: "Alan", userId: "5223"}
3:{Name: "Jenny", userId: "124"}
in the template, i use NgFor to iterate over the usernames like below
<div *ngFor="let id of UserNames let i = index;">
<input type="radio" name="radio" [checked]="UserNames.userid" (click)="Submit(UserInput)"> <span>Submit</span>
</div>
What i want to achieve is if i enter 23432 the button should disabled because the service already returns userId with this value, unless a new user id entered the button should be enabled.
So the general case of disabling a submit button in the way you're describing would look like:
<button type="submit" [disabled]="someValidationFn()" ...>
and someValidationFn() would, according to the use case you described, contain something like
return UserNames.find(name => { return name.userId === userInput;}));
where userInput is a separate property in the component bound to some user-entered value, presumably via an open text input like
<input name="userInput" [(ngModel)]="userInput" type="text" placeholder="Enter some user id">
But, from the markup snippet you pasted*, I'm not clear that you have that "text" input separate from the radio button group. If the radio button group is meant to have submit actions attached to its individual buttons (it shouldn't), then you're actually guaranteed that the user selection will contain a userId which exists in your UserNames array: the only inputs you're offering are based on the data which came from your service in the first place.
Based on the use case you're describing, I'm not sure why you'd have the radio button group. It sounds like you would just want that text input field with a validation method to make sure that user input does not already exist in the UserNames.
Because I wrote a bunch of abstract snippets there, I thought it might be helpful to show some basic html and js where I put it all together:
// html
<form submit="someSubmitAction()">
<input name="userInput" [(ngModel)]="userInput" type="text" placeholder="Enter some user id">
<button type="submit" [disabled]="someValidationFn()">Submit</button>
</form>
// js
/* don't forget your #Component annotation and class declaration -- I'm assuming these exist and are correct. The class definition encloses all the following logic. */
public userInput: string;
public UserNames: any[];
/* then some service method which grabs the existing UserNames on component's construction or initialization and stores them in UserNames */
public someValidationFn() {
return UserNames.find(name => { return name.userId === userInput;}));
}
public someSubmitAction() {
/* presumably some other service method which POSTs the data */
}
*speaking of the snippet you pasted, there are a couple of errors there:
*ngFor="let id of UserNames <-- you won't get an id by referencing into the UserNames array here; you'll get a member of the UserNames array in each iteration -- i.e., you'd get {Name: "John", userId: "23432"}, then {Name: "Smith", userId: "12323"}, and so on. That's not necessarily an error, but I'm assuming that, b/c you used id as your variable name, you were expecting just the userId field. Otherwise you'd have to use {{id.userId}} in each iteration to access the actual id.
And bob.mazzo mentions another issue with the use of the [checked] attribute

Laravel 5.2 Validation Help Exist in Database

I'm making a simple booking system with the help of Laravel. The times that is booked is for an imaginary car company that rent cars. So you rent a car by booking the time. I'm pretty far into the project and I'm almost finished. I just have a small problem. I dont know how I can make my booked times "not bookable" so to say.
What I want to be unique is the date of the booking. In my migration for the "booked" times (the table is called "times") I have already set the column "date" to be unique:
public function up()
{
Schema::create('times', function (Blueprint $table) {
$table->integer('car_id')->unsigned();
$table->date('date');
$table->timestamps();
$table->primary(array('car_id', 'date'));
});
}
The date "integer" makes it so that it is unique and I can not book it twice. But what I want to do is check if the booked time is in the Carbon time frame of the ten days from present day. Those times is made like this:
$dt = Carbon::now('Europe/Stockholm');
for ($i = 0; $i < 10; $i++) {
$dates[$i] = $dt->addDays(1)->toDateString();
}
Then I send the $dates variable to my view and display them like this:
<ul class="list-group">
#foreach ($dates as $date)
<form method="POST" action="/{{ $car->id }}/time">
{{ csrf_field() }}
<li class="list-group-item">
<input type="hidden" name="date" value="{{ $date }}">
{{ $date }}
<input type="submit" value="Boka" class="btn btn-primary"/>
</li>
</form>
#endforeach
</ul>
So then if I press the "Boka" button the time is put in the "times" table, and because I use relationship I reach it with $car->time, like that I can get all the booked times on that specific car.
I show all the times that are booked like this in my view:
<ul class="list-group">
#foreach ($car->time as $time)
<li class="list-group-item">
{{ $time->date }}
<form method="POST" action="/delete/time/{{ $time->car_id }}/{{ $time->date }}">
{{ method_field('DELETE') }}
{{ csrf_field() }}
<input type="submit" value="Delete" class="btn btn-danger"/>
</form>
</li>
#endforeach
</ul>
So basically what I want to do now is to check if the date from Carbon is in the "times" table I want to remove the "Boka" button from the view..
My teacher tells me to use this code in some way:
$this->validate($request, [
'date' => 'exists:times,date'
]);
I know what this snippet of code does, it checks the request sent if the date from the form exist in the times table on the column date. But I just don't know where to use it. Ive tried in my "TimesController" where I add the dates to the "times" table like this:
public function update(Request $request, Car $car, Time $time) {
$this->validate($request, [
'date' => 'exists:times,date'
]);
$times = new Time;
$times->date = $request->date;
$car->time()->save($times);
return back();
}
But this doesn't work the way I want it to. It checks if the date is in the table, and if it is. It ads it. But the problem is, the date must be unique so I get an error message that says the date isn't unique. That's good but not what I want. So if I add a date that isn't booked yet. It doesn't add the date like it should. I check what error I get by writing this code in my view:
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
And the error it output said: "The selected date is invalid."
So what I get from that is that my validation code checks if the request is in the database then if it is, the date is added. But if the date isn't already in the "times" table it doesn't get added. That is the exact opposite of what I want..
I tried putting it in my CarsController to where I make up the dates with the help of Carbon as I showed earlier. But I just can't get anything out of that..
I know this post is kinda long. But I wanted to get as much information in as possible. I would really appreciate some help.
TL/DR: What I want to do is use the Validate function in Laravel to check if my dates for booking is in the booked "times" table or not. IF it is then I want the "Boka" button do disappear. The date shouldn't be able to be added to the "times" table. Alternatively the "date" could disappear entirely from the dates made with Carbon if it is in the "times" table...
I really don't know what to do so I would appreciate som help. Thanks.
And yeah, english isn't my native language so please don't bash me.
There are many ways to validate your data in Laravel. I will show you some of them, feel free to choose the one you'll like.
First of all, the basics.
You can use the validate method in the controller method of your choice. The official documentation has a nice example of it.
...
public function store(Request $request)
{
$this->validate($request, [
'title' => 'required|unique:posts|max:255',
'body' => 'required',
]);
...
Your validation rule goes in the second parameter of the method, the array with other rules.
However, this is not the only way you can deal with validation.
As the documentation says in the "Other Validation Approaches" section, you can:
manually create a validator with Validator::make();
make a FormRequest to isolate your validation rules (and, eventually, logic) in a separate class;
Hope it helps. :)
Just check after validate method that if it returns true or false and based on that use return back with errors or proceed further.

Resources