I am currently writing an adress book and using a framework (CakePHP) an MVC for the first time. Unfortunately I have some trouble.
I want to realize the following:
In case the URL is
/contacts/view/
I want to show all contacts in a list. In case there is an id given after /view/, e.g.
/contacts/view/1
I just want to display the contact with the id 1. (complete different view/design than in the first case)
My ContactsController.php is the following
public function view($id = null){
if(!$this->id){
/*
* Show all users
*/
$this->set('mode', 'all');
$this->set('contacts', $this->Contact->find('all'));
} else {
/*
* Show a specific user
*/
$this->set('mode','single');
if(!$this->Contact->findByid($id)){
throw new NotFoundException(__('User not found'));
} else {
$this->set('contact', $this->Contact->findByid($id));
};
}
}
But "$this->mode" is always set as "all". How can I check whether the id is set or not?
I really want to avoid "ugly" URL-schemes like ?id=1
Thanks in advance!
Your code is only meeting the if part and its not going to else part. Use (!$id)..
$_GET data is retrieved through the URL. In CakePHP this means it's accessed through that method's parameters.
I'm arbitrarily picking names, so please follow! If you're in the guests controller and posting to the register method you'd access it like this
function register($param1, $param2, $param3){
}
Each of these params is the GET data, so the URL would look something like
www.example.com/guests/param1/param2/param3
So now for your question How can I check whether the id is set or not?
There are a couple of possibilities. If you want to check if the ID exists, you can do something like
$this->Model->set = $param1
if (!$this->Model->exists()) {
throw new NotFoundException(__('Invalid user'));
}
else{
//conduct search
}
Or you can just search based on whether or not the parameter is set
if(isset($param1)){ //param1 is set
$search = $this->Model->find('all','conditions=>array('id' => $param1)));
}
else{
$search = $this->Model->find('all');
}
You should only change the conditions not the whole block of code like
public function view($id = null){
$conditions = array();
$mode = 'all';
if($id){
$conditions['Contact.id'] = $id;
$mode = 'single';
}
$contacts = $this->Contact->find('all', array('conditions' => $conditions));
$this->set(compact('contacts', 'mode'));
}
Related
So I've built a small conditional to evaluate which button is pressed in my form (as there are 2). This works fine and fires off the correct method and writes the appropriate data to the DB, however my redirect is not working. It saves() to the DB and then simply stays on the page designated as the POST route.
I suspect the problem has something to do with my conditional and the use of $this.
Here is my check_submit method:
public function check_submit()
{
if(!is_null(Input::get('add_to_invoice'))){
$this->invoice_add_item();
} elseif(!is_null(Input::get('complete_invoice'))) {
$this->invoice_complete();
}
}
Here is one of the 2 methods which I am currently testing:
public function invoice_add_item()
{
$input = Request::all();
$invoice_items = new Expense;
$invoice_items->item_id = $input['item_id'];
$invoice_items->category_id = $input['category'];
$invoice_items->price = $input['price'];
$invoice_items->store_id = $input['store'];
if(Input::has('business_expense'))
{
$invoice_items->business_expense = 1;
}
else{
$invoice_items->business_expense = 0;
}
$invoice_items->save();
return redirect('/');
}
Perhaps there is a better way of handling this in my routes(web) file, but I'm not sure how to go about this.
You should add the return to the check_submit() method. Something like
public function check_submit()
{
if(!is_null(Input::get('add_to_invoice'))){
return $this->invoice_add_item();
} elseif(!is_null(Input::get('complete_invoice'))) {
return $this->invoice_complete();
}
}
Better yet, you should probably return a boolean on invoice_add_item() and based on that, redirect the user to the correct place (or with some session flash variable with an error message)
I am trying to get the value of a row in the database but not working out that well. I not sure if can work like this.
I am just trying to get the value but also make sure it from the group config and the key.
Model
function getTitle() {
return $this->db->get('setting', array(
->where('group' => 'config'),
->where('key' => 'config_meta_title'),
->where('value'=> ) // Want to be able to return any thing in the value
))->row();
}
In the controller I would do this:
function index() {
$data['title'] = $this->document->getTitle();
$this->load->view('sample', $data);
}
First, you have this line set to this:
$data['title'] $this->document->getTitle();
That should be an = assignment for $this->document->getTitle(); like this:
$data['title'] = $this->document->getTitle();
But then in your function you should actually return the setting value from your query with row()->setting:
function getTitle() {
return $this->db->get('setting', array(
->where('group' => 'config'),
->where('key' => 'config_meta_title'),
->where('value'=> ) // Should return this row information but can not.
))->row()->setting;
}
But that said, I am unclear about this:
->where('value'=> ) // Should return this row information but can not.
A WHERE condition is not a SELECT. It is a condition connected to a SELECT that allows you to SELECT certain values WHERE a criteria is met. So that should be set to something, but not really sure what since your code doesn’t provide much details.
Found Solution Working Now. For Getting Single Item From Database In Codeigniter
Loading In Library
function getTitle($value) {
$this->CI->db->select($value);
$this->CI->db->where("group","config");
$this->CI->db->where("key","config_meta_title");
$query = $this->CI->db->get('setting');
return $query->row()->$value;
}
Or Loading In Model
function getTitle($value) {
$this->db->select($value);
$this->db->where("group","config");
$this->db->where("key","config_meta_title");
$query = $this->db->get('setting');
return $query->row()->$value;
}
I have a resource:
Route::resource('artists', 'ArtistsController');
For a particular url (domain.com/artists/{$id} or domain.com/artists/{$url_tag}), I can look at the individual page for a resource in the table artists. It is controlled by this function:
public function show($id)
{
if(!is_numeric($id)) {
$results = DB::select('select * from artists where url_tag = ?', array($id));
if(isset($results[0]->id) && !empty($results[0]->id)) {
$id = $results[0]->id;
}
}
else {
$artist = Artist::find($id);
}
$artist = Artist::find($id);
return View::make('artists.show', compact('artist'))
->with('fans', Fan::all())
->with('friendlikes', Fanartist::friend_likes())
->with('fan_likes', Fanartist::fan_likes());
}
What I would like to do is have all urls that are visited where the {$id} or the {$url_tag} don't exist int he table, to be rerouted to another page. For instance, if I typed domain.com/artists/jujubeee, and jujubee doesn't exist in the table in the $url_tag column, I want it rerouted to another page.
Any ideas on how to do this?
Thank you.
In your show method you may use something like this:
public function show($id)
{
$artist = Artist::find($id);
if($artist) {
return View::make('artists.show', compact('artist'))->with(...)
}
else {
return View::make('errors.notfound')->withID($id);
}
}
In your views folder create a folder named errors (if not present) and in this folder create a view named notfound.blade.php and in this view file you'll get the $id so you may show something useful with/without the id.
Alternatively, you may register a global NotFoundHttpException exception handler in your app/start/global.php file like this:
App::error(function(Symfony\Component\HttpKernel\Exception\NotFoundHttpException $e) {
// Use $e->getMessage() to get the message from the object
return View::make('errors.notfound')->with('exception', $e);
});
To redirect to another page have a look at the redirect methods available on the responses page of the Laravel docs.
This is how I would go about doing it and note that you can also simplify your database queries using Eloquent:
public function show($id)
{
if( ! is_numeric($id)) {
// Select only the first result.
$artist = Arist::where('url_tag', $id)->first();
}
else {
// Select by primary key
$artist = Artist::find($id);
}
// If no artist was found
if( ! $artist) {
// Redirect to a different page.
return Redirect::to('path/to/user/not/found');
}
return View::make('artists.show', compact('artist'))
->with('fans', Fan::all())
->with('friendlikes', Fanartist::friend_likes())
->with('fan_likes', Fanartist::fan_likes());
}
I just started learning codeigniter and i must say its pretty easy but I have a problem dealing with wrong urls, for example:
if I have an anchor tag like this
http://example.com/info/2
in the controller if I have
public function info( $x ) {
$data['body'] = "Personal_info";
$data['details'] = $this->person_model->get_detail( $x );
$this->load->view('view', $data);
}
the controller grabs the links
segment (3)
and then grab the details of the id from the database.
now for instance if a user manually edit the link on the browser and change the
segment(3)
to lets say 7 and there is no id in the database as 4.
how do I handle such a problem? I am a beginner so please pardon me
You could use empty method to check if there is data and if not redirect away from the page.
public function info( $x )
{
$details = $this->person_model->get_detail( $x );
if(empty($details))
redirect('other/url');
$data['body'] = "Personal_info";
$data['details'] = details;
$this->load->view('view', $data);
}
This way it doesn't throw errors and potentially attempt to display something that doesn't exist.
you can check if the passed id exists in database before trying to fetch related data, like:
$data_exists = $this->person_model->data_exists( $x );
if( $data_exists ) {
$data['details'] = $this->person_model->get_detail( $x );
$this->load->view('view', $data);
}
else {
//load some view for showing no such id exists in db
}
where data_exists() can be a function in model which returns TRUE or FALSE depending on existance of your id in database.
I have an array of people that is registered as online in a html file. I am using this so that each can have an image assigned to them. But when checking to see if using name is already in use the in_array function return false and allow the script to continue.
$user = "< img src='default.jpg' />John";
$explode = array("<img src='tress.jpg' />John");
if(in_array($user, $explode))
{
//show login script if user exists
}
else
{
//continue to script
}
Now the reason this is not working is because the john in the array is not identical to the john in $user. Is there anyway of checking that the name exists in the array? When responding please explain.
Instead of asking, "How do I solve this problem?", you need to start with, "Why am I having this problem?"
$user = "< img src='default.jpg' />John";
Is < img src='default.jpg' />John a user name? Why are you using it as one? I'm guessing there's some clever thought behind this like "Well, I always display a user's image with their name, so I'll just make the image part of their name. This is going to cause far more problems than it solves. This comes back to a big concept in computer science called separation of concerns. An image is not logically a part of a user name, so don't store it as one. If you always display them together, you can use functions to display a user's information in a standard way without making the image part of the user name.
So first off, remove the image from the name. There are several ways to store this separately.
I would suggest using a class:
class User {
public $name;
public $imageSource;
// The following functions are optional, but show how a class
// can be useful.
/**
* Create a user with the given name and URL to their image
*/
function __construct($name, $imageSource) {
$this->name = $name;
$this->imageSource = $imageSource;
}
/**
* Gets the HTML to display a user's image
*/
function image() {
return "<img src='". $this->imageSource ."' />";
}
/**
* Gets HTML to display to identify a user (including image)
*/
function display() {
return $this->image() . $this->name;
}
}
$user = new User("john", "default.jpg");
// or without the constructor defined
//$user = new User();
//$user->name = "john";
//$user->imageSource = "default.jpg";
echo $user->display();
You can use an "array" if you want to be a little lazier, but I don't recommend it in the general case, since you lose the cool features of classes (like those functions):
$user = array(
name => "john",
image => "<img src='default.jpg' />";
);
echo $user["image"] . $user["name"];
In your database (if you're using one), make them separate columns and then use one of the above data structures.
Now that you have this, it's easy to see if a user name is in a given list using a foreach loop:
function userNameInList($user, $users) {
for($users as $current) {
if($user->name == $current) {
return true;
}
}
return false;
}
$newUser = new User("John", "john.jpg");
$currentUsers = array("John", "Mary", "Bob");
if(userNameInList($newUser, $currentUsers) {
echo "Sorry, user name " . $newUser->name . " is already in use!";
}
If you're new to PHP, the normal for loop may be easier to understand:
function userNameInList($user, $users) {
for($i = 0; $i < count($users); ++i) {
$current = $users[$i];
if($user->name == $current) {
return true;
}
}
return false;
}
Let me know if any of this doesn't run, I don't write PHP very often anymore..