For my personal website (online administration) I have an appointments page, with certain settings, which is just for me, so I don't need it to be secure.
For example, I can change my view (to show all appointments or to sort them by label, or status). I can also exclude a status to make sure it's not being shown. Everything works, no problem there.
My issue is this. I have a simple field in my user database called "view". When I go to my appointments page, I check the value of my "view" field and if it is "status" for example, in my controller I set "$view = status", to return my "status" view. This works, with the following simple check:
$getUserView = \Auth::user()->view;
if($getUserView){
$view = $getUserView;
}
In my view itself I have a dropdown to change the view. Now, when I go to my view, it shows the "status view" just fine. But when I want to change the view to "default" or "label" using my dropdown, it should change the view to what I selected. So basically what I want to achieve is, when I go to my appointments page for the first time, it should show the view that I have set in my database, but only that one time. I could set it in a session maybe for that but I am just not sure how to accomplish this. Any pointers would be helpful!
Edit:
Still struggling with this, because I am using GET for everything, also the dropdown. Example, when I change the value in the dropdown, a javascript simply calls the URL again, but with the status that was selected in the dropdown. So, for example, my default URL is the following:
http://example.com/appointments/status/default
Now, I select "completed" in the dropdown, the following URL is called:
http://example.com/appointments/status/completed
In my appointments controller I put the following:
$status = session()->get("status", \Auth::user()->status);
In my routes I have the following:
Route::get('appointments/status/{status}', array('as' => 'appointments', 'uses' => 'Appointments\AppointmentsController#index'));
Maybe I should change "{status}" in the route to "$status" and use the put method to set the "$status"? Not sure what the best method would be.
When using the get method on the Session, the second argument is intended for a default value, which will be returned if the session key is not found.
You could do something like this:
$user = \Auth::user();
$view = session()->get("appointments_view", $user->view);
That will get the view set in the session, and if that is not set, it'll return $user->view. Now, when the users picks another view in the dropdown, just do:
session()->put("appointments_view", $dropDownValue);
Related
In my laravel project i use hashes in the url to keep track on selections of the user, so they are able to go back to a filter result. I dont want the page to refresh so I DONT UPDATE THE URL with Page=someid (except the hash) the response of the server looks like.
if ($request->ajax()) {
//The page I want to select posted with ajax
$paginaId = $request->input('page');
//some query like
$query = Table::Query();
//get 9 items
$rooms= $query->paginate(9);
//Return the response
return Response::json(View::make('front.rooms.render', array('rooms' => $rooms))->render());
}
The $paginaId represents the selected pagination page. Everything works fine except one part. I cant set the current page of the pagination. I viewed the documentation but couldn't find any solutions.
Try the following:
$rooms = $query->paginate(9, ['*'], 'page', $paginaId);
In this case you can set $paginaId manualy
Ok, so I have views that provide summary information regarding user entries. Users can create entries for different "programs" (categories more or less) and different "vendors" etc. So the Program View will show some summary information for each program as well as how many entries each program has. The Vendor View will show summary information about each vendor as well as how many entries exist for each vendor.
How do I code a button that users can click to take them to a view of entries for that program or vendor. I'm getting confused because I don't think you are supposed to access a controller from a view but I want the user to be able to see summary information in different ways and then click to get to the detailed data.
So the Program View might look like:
Page Title: All Programs
Program: Program 1
Start Date: 5/5/13
End Date: 5/5/14
Button: |Click to view entries|
Program: Program 2
Start Date: 6/1/13
End Date: 2/15/14
Button: |Click to view entries|
What I would really like to do is call a model I created that accepts an array which acts as a filter. It works nicely when called from a controller but I don't think I can do that looks like this:
public function get_entries($filter, $option = false)
{
$this->db->where($filter);
$this->db->from('item i');
$this->db->join('program p', 'p.Id=i.program_Id');
$this->db->join('vendor v', 'v.Id=i.vendor_Id');
$this->db->join('item_type it', 'it.Id=i.item_type_Id');
$this->db->join('item_type_category itc', 'itc.item_type_Id=it.Id');
$this->db->join('category c', 'c.Id=itc.category_Id');
$this->db->select('i.*, p.programName, v.VENDNM, it.name, c.catName');
$this->db->select('(SELECT FORMAT(i.cost, "c")) AS cost', FALSE);
$query = $this->db->get();
$result = $query->result_array();
if ($option === false){
return $result;
}
elseif ($option === "count"){
return count($result);
}
}
This is easy -- just use a form that has fields that determine the ranges you want to search on. The address that you use on the form will first go to your controller -- then the method. Using Codeigniters form helper if your controller is 'reports' and a method 'search':
echo form_open('reports/search');
then in your 'reports' controller in a method called 'search'
Verify the Form Using the Form Validation class.
ALWAYS verify user input even if you are just using drop down menus.
If the form does not verify
show the form view again with an error message
Else
do the search with the values provided by the form.
Typically doing this search and passing back the results
(or False for no results) will happen in the Model
If there are no database results
show the form view again with a no results message
Else if there are results
pass results to a view page which will display them.
Form Helper
http://ellislab.com/codeigniter/user-guide/helpers/form_helper.html
Form Validation
http://ellislab.com/codeigniter/user-guide/libraries/form_validation.html
and take a look at this tutorial -- will show you many of the basic code patterns you need -
http://ellislab.com/codeigniter/user-guide/tutorial/index.html
I have some questions concering routing with Codeigniter. What I´m doing now is the following:
$route['articles/(:num)'] = 'articles/view/$1'; // $1 will contain an ID
This means that example.com/articles/123 will work perfectly and load an article with an ID of 123. But I also want to have the possiblilty to add the aticle´s title to the URL (for SEO). Example: example.com/articles/123/article-title
What I want is pretty much the same thing as Stack Overflow: stackoverflow.com/questions/123/the-title
How can I do that?
I´m also wondering how Stack Overflow works. If I go to stackoverflow/questions/111 the title will automatically be added to the url. Is that done with php redirect()?
I have done something similar in the past; I can't find it know but IIRC (it was months ago) You can use a route like you did, and also add a more specific one, like
$route['articles/(:num)/(:any)'] = 'articles/view/$1/$2';
$route['articles/(:num)'] = 'articles/view/$1';
As you can see, both map to the same method, which is kind of "overloaded"; you can make up for a missing parameter by using a default value:
function articles($id,$slug = FALSE)
{ }
and simply ignore the second parameter in your article retrieval.
As for adding the title you can:
have a "slug" field in your database, created when the article is saved. You can use the comfortable url_title($title,'dash',TRUE) function (in the url helper), which takes the $title, uses the dash as separator, and make it all lowercase;
use the above function and convert the title of the article (after you retrieved it from the database) "on-the-fly"; just check on the article() method if the 2nd parameter isn't false and you'll know if you need to create the slug or not;
As for how to show the slug even when using an url without it you can make, as you guessed, a redirect, but since both routes point to the same method it won't change anything for you.
Oh, uhm, beware of loops while calling the redirect, check carefully ;)
I suggest you to create a slug field into your table and complete it with the url you want to use as id.
Let me explain.
You have this table
id
title
slug
when you save an article into your db you can dinamically create a slug, for example:
id: 1
title: My first post
slug: 1-my-first-post
then you can use the slug (in this case 1-my-first-post) ad id for the page, you can call it:
www.example.com/articles/1-my-first-post
obviusly you need to handle it in your db slect
As we discussed on the comments.
You can create a route several times and with different parameters each, like:
$route['articles/(:num)/(:any)']
$route['articles/(:num)']
I would create a function with a redirect, adding or not the title to it.
Hope it helps.
I would like to create a button that can be used to populate a table in my db with a single click.
I am just not sure what I need to do here to make this happen. Can I assign a method to be executed by a button? Or just have values picked up in my controller? Below is something like what I want to execute but through a button.
public function addInterest($interest)
{
$interest->UserId=Yii::app()->user->id;
$interest->ItemId=$this->ItemId;
return $interest->save();
}
**Additional details in response to Jaison Justus
With this implementation I am using controller and view from Model A (ItemId) where the button is to be displayed. Then there is Model B (UserId). Taking the info from Model A (ItemId) and Model B (UserId) I want to populate Model C ($interest) with that ItemId and UserId upon clicking a button. Looks like CJuiButton might provide a means to build it from being as then I can disable/hide the button after selected once. I am just not familiar with using buttons other than on a form where user input in collected, as links, or to provide pop up messages.
The code above currently sits in Model A model. With the code below in Model A controller everything works to populate Model C if I use a form and collect input. Since I do not require any input other then selecting the button from the user the form has nothing to put into it and therefore I know I can not use if(isset($_POST['Interest'])) as I have below.
public function actionView($id) {
$items=$this->loadModel($id);
$interest=$this->newInterest($items);
$this->render('view', array(
'model' => $items,
'interest' => $interest,
));
}
protected function newInterest($items)
{
$interest=new Interest;
if(isset($_POST['Interest']))
{
$interest->attributes=$_POST['interest'];
if($items->addInterest($interest))
$this->refresh();
}
return $interest;
}
In response to VarioN
Here is an attempt at using ajax. However this does not work and gives an Error 500 when ran. Is my controller action appropriate for what I am trying to do here?
Controller
public function actionAddInterest() {
$connection = yii::app()->db;
$sql1 = "INSERT INTO interest (UserId, ItemId)
VALUES(".Yii::app()->user->id.",".$this->ItemId.")";
$connection->createCommand($sql1)->execute();
}
View
<?php
echo CHtml::ajaxLink(
'Add Interest',
array('/item/addInterest'),
array('update'=>'#req_res')
);
?>
Looking at your question I see that you don't understand how MVC in Yii works.
Look at this 15 minutes screencast (Yii Tour - 3rd Stop - CRUD County) and after you will be able to create such button in any way you need (try use Gii and than customize it in your way - it's the easiest way).
Updated:
Seems that you need AJAX request. You can add CHtml::ajaxButton() in your view.
It will work this way:
User push the button, button do request (with JavaScript) to your
site without reloading the page and invisible for user.
Your controller action will serve this request: it can make some things (for ex., save data to db) and output data that your JavaScript possibly will display to user.
Than your JavaScript get answer and can make some changes on the page
(for example, hide button or show text got from request).
You can look at simple example with ajax here
If you needn't to submit form info with your button you can user ajaxLink. Example for it is here
There are a lot of examples with ajax and yii in the internet and at yii forum. Try to find them it may be very helpful.
Ask questions if you would have any.
Second update:
First, try to do your sql query simplier:
"INSERT INTO interest (UserId, ItemId) VALUES (1, 2)"
Than enable logging of mysql queries to log: at config/main.php add "trace" to "levels"
'components'=>array(
'log'=>array(
'class'=>'CLogRouter',
'routes'=>array(
array(
'class'=>'CFileLogRoute',
'levels'=>'error, warning, trace',
),
Now you can try to press an AJAX link and look at the protected/runtime/log.txt and determine the problem.
Additional info to AJAX requests
All that outputs your ajax scripts can be viewed by browser's features:
At Chrome: press F12, go to Network, press an ajax-link and look at request response.
At Firefox with addon "Firebug".
With this you can determine whether a request is done or not.
Going a bit mad here... :)
I'm just trying to add CCK fields from a Content Profile content type into page-user.tpl.php (I'm creating a highly-themed user profile page).
There seem to be two methods, both of which have a unique disadvantage that I can't seem to overcome:
'$content profile' method.
$var = $content_profile->get_variables('profile');
print $var['field_last_name'][0]['safe'];
This is great, except I can't seem to pass the currently viewed user into $content_profile, and it therefore always shows the logged in user.
'$content profile load' method.
$account_id = arg(1);
$account = user_load($account_id);
$user_id = $account->uid;
$var = content_profile_load('profile', $user_id);
print $var->field_first_name[0]['value'];
Fine, but now I can't access the full rendered fields, only the plain values (i.e. if the field has paragraphs they won't show up).
How can I have both things at once? In other words how can I show fields relating to the currently viewed user that are also rendered (the 'safe' format in 1)?
I've Googled and Googled and I just end up going round in circles. :(
Cheers,
James
Your content profile load method seems to be the closest to what you want.
In your example:
$account_id = arg(1);
$account = user_load($account_id);
$user_id = $account->uid;
$var = content_profile_load('profile', $user_id);
print $var->field_first_name[0]['value'];
The $var is just a node object. You can get the "full rendered fields" in a number of ways (assuming you mean your field with a filter applied).
The most important thing to check is that you're field is actually configured properly.
Go to:
admin/content/node-type/[node-type]/fields/field_[field-name] to configure your field and make sure that under text processing that you've got "Filtered text" selected.
If that doesn't fix it,try applying this:
content_view_field(content_fields("field_last_name"), $var, FALSE, FALSE)
(more info on this here: http://www.trevorsimonton.com/blog/cck-field-render-node-formatter-format-output-print-echo )
in place of this:
print $var->field_first_name[0]['value'];
if none of that helps... try out some of the things i've got on my blog about this very problem:
http://www.trevorsimonton.com/blog/print-filtered-text-body-input-format-text-processing-node-template-field-php-drupal
When you're creating a user profile page there is a built in mechanism for it. just create a user template file, user_profile.tpl.php.
When you use the built in mechanism you automatically get access to the $account object of the user you are browsing, including all user profile cck fields. You have the fields you are looking for without having to programmatically load the user.
I have a field called profile_bio and am able to spit out any mark up that is in without ever having to ask for the $account.
<?php if ($account->content[Profile][profile_bio]['#value']) print "<h3>Bio</h3>".$account->content[Profile][profile_bio]['#value']; ?>
I've tried themeing content profiles by displaying profile node fields through the userpage before and it always seems a little "hacky" to me. What I've grown quite fond of is simply going to the content profile settings page for that node type and setting the display to "Display the full content". This is fine and dandy except for the stupid markup like the node type name that content profile injects.
a solution for that is to add a preprocess function for the content profile template. one that will unset the $title and remove the node-type name that appears on the profile normally.
function mymodule_preprocess_content_profile_display_view(&$variables) {
if ($variables['type'] == 'nodetypename') {
unset($variables['title']);
}
}
A function similar to this should do the trick. Now to theme user profiles you can simply theme your profile nodes as normal.