This is probably a really, really simple issue, but it's got me stumped...
So, I've got an article saved in the database with a form, including a field to save a published date. The data entered in this field is successfully saving in the database, along with the rest of the data.
I'm successfully pulling all the saved data back out into the edit form, EXCEPT the published_date field.
I've tried using the same format as the other fields, eg title, both show below
{!! Form::text('title', null) !!}
{!! Form::input('date', 'first_published', null) !!}
This puts dd/mm/yy in the input box, rather than the saved date. If this value isn't changed, the date is saved in the database as today's date.
I've also tried removing the 'date' attribute
{!! Form::input('first_published', null ) !!}
This results in a totally empty box (and no datepicker), which doesn't overwrite the value in the form if not saved. Better, but still not what I want, as I want to show the saved date, which can be changed if required.
I've also tried echoing the $article->published_date in various ways in this field, but only end up with the same results as those above. I can echo out this data elsewhere in the form no problem though using {!! $article->first_published !!}
The form references the model as so:
{!! Form::model($article, ['method' => 'PATCH', 'url' => 'articles'.'/'. $article->id]) !!}
And the relevant controller functions are
//page containing form to edit article, pulls in existing data
public function edit($id)
{
$article = article::findOrFail($id);
return view('articles.edit', compact('article'));
}
//responsible for updating the article record
public function update($id, Request $request)
{
$article = article::findOrFail($id);
$article->update($request->all());
return redirect('articles');
}
The field is set as a timestamp in the migration, and in the model I have
protected $dates = [
'first_published'
];
So, if anyone can shed any light on how to get the saved data value into the form field as in the other fields, it would be much appreciated! :) I'm pretty new to laravel so apologies if there's some blindingly obvious issue I've missed...
On the offchance anyone else has a similar issue - I've now found the solution, which was embarrassingly simple!
I changed the date field as below:
{!! Form::date('first_published', $article->first_published, ['class' => 'nameofclasshere']) !!}
So that the field's default value is the value pulled from my database (which I was able to access elsewhere in the page as detailed in the question). When I submit the form the date remains as the value from the database, unless I change the form value, in which case it's updated.
Don't know if this is the correct or recommended way to do this (and is still different to how I've done the other fields), but it seems to do the trick!
What I did is replaced the Form::input('date', 'published_at', ... line related segment with the following code section (referring to your Laracast Partials and Forms Reuse tutorial) specifically:
<!-- Published_at Form Text Input -->
<div class="form-group">
{!! Form::label('published_at', 'Publish On:') !!}
{!! Form::date('published_at', (isset($article) && $article->published_at ? $article->published_at : date('Y-m-d')), ['class' => 'form-control']) !!}
</div>
In the above replaced code section (isset($article) && $article->published_at ? $article->published_at : date('Y-m-d')) would check if the Form has given an $article object, so then use its existing published_at date or other wise create date with current time and use it.
Hope this would be helpful to somebody out there.
Clearly this question is closed already, but maybe it can help someone.
I was using a form to both edit and create, so I did the following:
<div class="form-group">
<label class="control-label" for="date_">Proyect Date </label>
<input class="form-control" id="datepicker" name="date" placeholder="DD/MM/AA" value="
#if (isset($proyect->date))
{!!date('d-m-Y', strtotime($proyect->date))!!}
#endif" type="text">
Related
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.
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.
Hey guys I've been working on this for a few days now but I can't seem to get it to work :(
Here is the situation.
I have an "edit profile" page.
On that page you can, like the name implies, edit profile information.
for the example here is what I'm trying to do.
Database record:
||-------||----------||-----------||
|| name || surname || email ||
||-------||----------||-----------||
|| Amy || Nuts || an#no.com ||
||-------||----------||-----------||
I have a form that gives the user the ability to enter their own data and change some of the fields.
The form fields all have names that corrospond with the database fields.
<input name="name" ......
<input name="surname" ......
<input name="email" .....
This is all very logical and easy.
The problem that I have is when I submit the form.
I build my website with HTML5 and use placeholders for the form fields.
I do this because it looks nice imo and I can experiment some with it.
When I just want to update the surname, the other fields stay empty.
Codeigniter by default returns a "false" in the case of an empty post item.
Maybe you can see my problem.
When I send the post data to the model and it updates the database record, it will remove the data from the "name" and "email" fields and update the surname.
The array looks like this:
array(
"name" =>
"surname" => NEW
"email" =>
)
After running this through the update function of codeigniter the database record looks like this
||-------||----------||-----------||
|| name || surname || email ||
||-------||----------||-----------||
|| || NEW || ||
||-------||----------||-----------||
what I want to know is, if there is a posibility to let codeigniter ignore the array items that do not have data.
I hope you guys can help out.
I'm at a loss here.
use array_filter($data) to remove any empty fields before sending it to database.
also it looks like you dont validate your data for update ?
can you please show the code in your model to store updates ?
example
$data['name']=$this->input->post('name');
$data['lastname']=$this->input->post('lastname');
$data=array_filter($data); //will remove empty keys
Or
if($this->input->post('name')) $data['name']=$this->input->post('name');
if($this->input->post('lastname')) $data['name']=$this->input->post('lastname');
in all cases you should really always validate your data before submitting it to database;
just a general note:
i would recommend you always have 2 layers of validations;
at controller to validate form (using CI form_validation)
at model to validate DATA (also using CI form_validation)
never trust your controller alone. the best DRY method i use in CI is that in my model
i use variable
models/demo_model.php
public $validate =array(
['field' => 'login','label' => 'lang:user_login','rules' => 'trim|required|min_length[5]|max_length[100]|xss_clean'],
['field' => 'password','label' => 'lang:user_password','rules' => 'trim|required|min_length[5]|max_length[35]|xss_clean']);
function is_valid($data,$mode=null){
if(!$this->validate || empty($data) )return false; //nothing to validate !
$config=array();
//if updating then its normal that some variables will be missing
//so lets apply rules for only data we going to update; to make sure its xss_clean, not exceed database size, trim, etc;;
if($mode = 'update'){
foreach($this->validate as $rule)if( ! empty( $data[ $rule['field'] ] )$config[]=$rule
}else{
$config = $this->validate
}
$this->form_validation->reset_validation();
$this->form_validation->set_data($data); #we are not using $_post;
$this->form_validation->set_rules($config);
return ($this->form_validation->run() === TRUE)
}
now in every database call before you use $this->db->insert; or update; u just use
$this->is_valid($data,'update'); // dont set 2nd param if you are inserting and want all rules to apply;
and this will validate all your requests;
also note that codeigniter form_validation can be used for modifing submitted values also;
for example using trim rule, or md5 rule on password field
well sorry i might hv extended my answer too long, i hope i answered you question.
I have a helper which generates a custom form input.
Helper (simplifed code)
public function customInput($field, array $options = array()) {
$defaultOptions = array(
'class' => 'custom-input',
'label' => false
);
$options = array_merge($defaultOptions, $options);
return $this->Form->input($field, $options);
}
Now how can I modify the name attribute of the input by prefixing it with another 'model'. For example, the input will by default have the following name attribute:
<input type="text" name="data[MyModel][field]" />
But I want it to be:
<input type="text" name="data[_custom][MyModel][field]" />
Mainly, what seems tricky is that I don't know how to get the model name that will be used by default. Also, I need something that works if the default model hierarchy is more complicated, like:
<input type="text" name="data[MyModel][AssociatedModel][field]" />
Would need to be modified to:
<input type="text" name="data[_custom][MyModel][AssociatedModel][field]" />
You want name
echo $this->Form->input('whatever', array('name' => 'data[_custom][MyModel][field]'));
There is nothing like data[_custom][MyModel][AssociatedModel][field] in cakes form helper. Your options as far as automation go is:
field // normal, use current model
Model.field // used with not default model / relations
Model.$i.field // User hasMany Post would be Post.$i.field
For the input helper, CakePHP uses $this->model() to get the name of the current model.
You can see it inside lib\Cake\view\FormHelper, or directly from the online API:
http://api20.cakephp.org/view_source/form-helper#line-942
$modelKey = $this->model();
Maybe that helps.
well you can do: $this->Form->input('_custom.MyModel.field'); to create an input in the format you require.
It becomes a case of passing the appropriate model name and associated model with it.
I don't know how you could do this automatically as obviously each relation is different/may have multiple associations.
So using your helper: echo $this->YourHelper->CustomInput('_custom.MyModel.MyAssociation.field', $options) might do the trick.
How to you extend a cakePHP project so it can use a new field in the database?
I just given a CakePHP Project that I am trying to extend the model to include a new field. I The original Developer is no longer available, and I haven't worked with CakePHP previously. The problem is that all of the other fields are being saved correctly, but the new field is being saved as an empty string.
The database has been extended to include the new field:
class_time varchar(30)
I extended the original view to support the new field
<?=$form->input('release', array('type' => 'radio', 'legend' => false, 'div' => 'radio', 'options' => array('Agree' => 'Agree ', 'Disagree' => 'Disagree')))?>
<?=$form->input('class_time', array('type' => 'radio', 'legend' => false, 'div' => 'radio', 'options' => array('No preference' => 'No preference ', '6:00-8:30 P.M. ' => '6:00-8:30 P.M. ', '6:30-9:00 P.M.' => '6:30-9:00 P.M.')))?>
As near as I can tell, the page is rendering the HTML correctly
<div class="radio"><input type="hidden" name="data[Account][release]" id="AccountRelease_" value=""><input type="radio" name="data[Account][release]" id="AccountReleaseAgree" value="Agree"><label for="AccountReleaseAgree">Agree </label><input type="radio" name="data[Account][release]" id="AccountReleaseDisagree" value="Disagree"><label for="AccountReleaseDisagree">Disagree</label></div>
<div class="radio"><input type="hidden" name="data[Account][class_time]" id="AccountClassTime_" value=""><input type="radio" name="data[Account][class_time]" id="AccountClassTimeNoPreference" value="No preference"><label for="AccountClassTimeNoPreference">No preference </label><input type="radio" name="data[Account][class_time]" id="AccountClassTime6:00-8:30P.m." value="6:00-8:30 P.M. "><label for="AccountClassTime6:00-8:30P.m.">6:00-8:30 P.M. </label><input type="radio" name="data[Account][class_time]" id="AccountClassTime6:30-9:00P.m." value="6:30-9:00 P.M."><label for="AccountClassTime6:30-9:00P.m.">6:30-9:00 P.M.</label></div>
But when it saves, it is saving the selection for the "release" field (and the others), but not the class_time.
From what I can find in the cakePHP documentation, app/models/account.php is where I believe I would need to define the new field, but it only consists of the following:
<?php
class Account extends AppModel {
var $name = 'Account';
}
?>
Which makes me wonder how the original developer got the "release" to save, even though it doesn't appear to be defined.
Is there something that I am missing, or that still needs to be done?
Whenever you make any changes to your database, please make sure that your app/config/core.php file debug value is 2. Configure::write('debug', 2);
If it is 0 database changes will not be detected.
In CakePHP application, whenever you add a new field or modify the structure in database, you should delete all files inside YourApplication/app/tmp/cache/models folder.
Whenever you do any database change follow the following steps :
Clear files under \app\tmp\cache\models
If you are using any cache engines like memcache, restart the cache service.
Set the debug to 2 in core.php
Quite a bit later, but I was looking for a way to do this today in Cake 3.x. Easiest way, imo:
bin/cake orm_cache build
which will rebuild the cache w/ the current db structure.
Or to just clear w/o rebuild:
bin/cake orm_cache clear
http://book.cakephp.org/3.0/en/console-and-shells/orm-cache.html
Try to clear all models under cache directory.
app/tmp/cache/models
clear cache at /app/tmp/cache
if raising debug level to 2 or 3 is not working.
check if, on using debug($Model), shows your new field under schema attribute of model.
You can also delete cache file if your database changes are not working.
path of your application\app\tmp\cache\models
In cakephp 3 you should also check your entity file for that model, and make sure that the field is under the $_accesible property.
Example:
protected $_accessible = [
'name' => true,
'topic' => true,
'new_field' => true
];
You need to inform cakephp that you have new fields in your db. Why you need to do so is coz cakephp scans the db only once and generates the schemas. Once refers to first time it's run. You can find the schemas in app\tmp\cache\models.
So if you clear the files in the above folder cake will re generate the schema. Now there is a exception to it, if you are in development/debug mode cakephp scans it everytime.
Actually, any changes to database, anytime , you should change debug mode to 2 in app/config/core.php if it is zero. Otherwise it will take values from cache.