yii button to create db entry - php

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.

Related

How do I redirect back to a specific show View after submitting a form? (Laravel)

I'm using Laravel to create an online teaching system, I have a rudimentary CRUD system that allows me to create degree paths. When I click on a degree path I'm taken to degrees/{{ degree->id }} and from there I can create modules. When I submit my form however, I don't know how to redirect back to that specific view. I can redirect back to the index page, then access the view and see that the module has been added, but I don't know how to go straight to the degree view.
I'm aware you can manually input the ID, but then what if I wanted to create a module for another degree?
Anyway, here's the store function, where my data is submitted to :
public function store(Request $request)
{
$module = new Module;
$module->title = $request->input('title');
$module->description = $request->input('description');
$module->save();
return redirect('/degrees');
The issue is in the redirect, I need to know how that can transfer me to the route (degrees/{{ degree->id }}), but if I type that out it doesn't understand what ID I actually want and throws an error.
Any advice is welcome, the functionality works, I can see the modules displayed on the degree page just need to know how to get there after submitting the data.
I'm relatively new to web-dev, so if I need to re-do things feel free to tell me I'm probably compounding errors at this point.
try this:
return back()->with('success','Submitted successfully');
return redirect()->back()->with('success', "success message");

Laravel 5 user defined settings only needs to be called once

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);

Codeigniter MVC. Going from summary information on one View to detailed Information in another View

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

PHP: Check for profile fields completedness

I have a social networking site built on a PHP framework. I'm using a plugin to award members points when they update their profile. Right now, whenever a member clicks on 'Save' it triggers the profileupdate event, and that event triggers the points being awarded. But, even if the profile fields are all empty, the event is still triggered and they still get points… so, my clever users are gaming the system to get points without really updating their profile :\
I want to add a function that checks that the profile fields aren't empty -- or, ideally, checks that a significant amount of changes have been made to at least 1 of the profile fields, but I'm not sure how to do that.
I'm still pretty new to PHP (about 1 year experience), so if anyone could help both with explaining what the checking process should be and the specifics on the code to execute the checking function, I'd really appreciate it!
Here are the current events and functions:
When the owner of the page clicks on 'Save', this is the event in the core of the PHP framework that gets triggered to notify the user of the update:
$owner->save();
trigger_event('profileupdate', $owner->type, $owner);
system_message(echo("profile:saved"));
This is the function in the points plugin that checks to see if the plugin is configured to award points based on a profile update, and then calls the points_add function to add points to the user:
function points_profile($event, $type, $object) {
if ($points = get_plugin_setting('profileupdate')) {
if (function_exists('points_add')) {
points_add(get_logged_in_user_guid(), $points, $event, $type, $object->entity_guid);
}
}
return(true);
}
This is an example of how the individual profile fields are defined/labelled -- ie, "admin_defined_profile_1"
if (save_config("admin_defined_profile_$id", $label) &&
save_config("admin_defined_profile_type_$id", $type) &&
save_config('profile_custom_fields', $fieldlist))
look on rowcount() http://www.php.net/manual/en/pdostatement.rowcount.php
it will -on single UPDATE -return 1 if anything was actually changed and 0 if nothing was changed.

Drupal - hook_menu_alter for webform

I have created a webform for client where the client information gets stored and the client can login and view the form, but when the client veiw the form it displays the submission table and then the client have to click on view in operation to display the results, i wanted to implement a function so it becomes possible to redirect the clients to the actual results directly instead of the submission table while for admin the submission table should be there...i guess i need to implement hook_menu_alter() in a custom module...was wondering if someone could help me with the code for hook_menu_alter()...the url for submission table is "node/$nid/submissions" and for the results is "node/$nid/submission/$sid". Thanks
You don't need hook_menu_alter to redirect after form submission.
You can simply add a #redirect to your $form at hook_form_submit()
It should be something like this:
function hook_form($form_state){
// $form[] definition here
$form[] = array(
'#type' => 'submit',
'#value' => 'Submit Me!',
'#submit' => array('hook_form_submit'),
);
}
function hook_form_submit($form,&$form_state){
// sanitize/save your data here!
$form_state['redirect'] = 'redirect/me/to/somewhere/else';
}
yes..both the user and the admin view the same form...n admin will be filling up the form on behalf of user and set the author as user so that user can view the filled info as we will set the user permission as "access own results". Now, the issue is when user views the webform results he gets a 'table' first which shows the 'date' and 'Operations' and in operation if user click on 'view' then the filled info is being displayed. so, i was just wondering if we can use hook_menu_alter to change that and instead of that 'table' it directly shows the filled info to the user...thanks andre..

Categories