html::link to dynamic route - laravel

I am trying to output a list of users on my blade.php page. Clicking on a user's id should take you to an individual profile page.
Here is my View browse.blade.php file
<?php
$cars = DB::table('cars')->get();
foreach ($cars as $car)
{
echo "<table >" ;
echo "<tr>";
HTML::linkRoute('browse/'.$car->car_id, 'Car ID: '.$car->car_id);
echo "<td>Make: $car->make <br/ ></td>" ;
echo "</tr>";
echo "</table>";
}
?>
My Controller
public function browse()
{
return View::make('car/browse');
}
public function showProfile($car_id)
{
return View::make('car/profile')->with('car_id', $car_id);
}
My Route
Route::any('browse/{car_id}', 'BrowseController#showProfile');
I want my view page to output a bunch of cars in my Database. Clicking on a car with car_id = i should tak me to http://localhost:8000/browse/i for each respectic car_id.
Am I taking the wrong approach with my html::linkRoute?
Typing http://localhost:8000/browse/i into the browser works for any i. Therefore, my route and showProfile is working properly.
However when I load the browse.blade.php I receive the following error
10018 is my first car id. Why isn't my Route::any('browse/{car_id}' working?
edit:
Thanks to msturdy for the suggestion
changed
Route::any('browse/{car_id}', 'BrowseController#showProfile');
to
Route::any('browse/{car_id}', [
'as' => 'profile',
'uses' => 'BrowseController#showProfile']);
and changed HTML route to
HTML::linkRoute('profile', 'Car ID: '.$car->car_id, array($car->car_id));
The errors are gone but no link is displaying on the browse page.

First, update your route so that it has a 'name' you can use elsewhere in your application. We'll call it 'browse' in this example:
Route::any('browse/{car_id}', array('as' => 'browse', 'uses' => 'BrowseController#showProfile'));
Then HTML::linkRoute() takes this route name, the title of the link and the parameters as separate arguments:
HTML::linkRoute('browse', "Car ID: " . $car->car_id, array($car->car_id));

Related

yii2 not rendering to view just refreshing the page

view.php code part:
View Picture
viewgood.php
<?php
echo 'hello';
GoodsController.php
public function viewgood($id = null) {
}
After clicking on button View Picture my page just refreshing instead of going to viewgood.php
What am I doing incorrectly?
I am a begginer in Yii2
Try use
View Picture
in a anchor tag html your need use the complete route, for use shortcut you try use
<?= Html::a('View Picture', ['/goods/viewgood/', 'id' => $good['GoodGallery'][0]['id']], ['class' => 'btn btn-primary']) ?>
view.php
You can use Html:a(), or in your example use Url helper to() function to generate the proper route for your anchor tag.
View Picture
GoodsController.php
public function actionViewgood($id=null){
//fetch the data e.g.
$model = Good::findOne(id);
//Do some extra code checking when no record is found like throw an exception or set a flash error message, etc.
//render the viewgood and pass the data (if needed)
return $this->render('viewgood', [
'model' => $model
]);
}
viewgood.php
<?php
//do what you want with the data passed by the controller. E.g. print the name of the good (if applicable)
echo $model->name;
//your other code ...
?>

gridview check box multi delete in yii2

i simply want to have a gridview that has checkbox column in front of each row and my admins can delete row by check all or check one or check how many box they disire and then by click on delete button all checked row remove from their view
in the back its important to update their delete column to 1 a row not delete
here is my code for delete one id
controller(ignore persian words)
public function actionDelete($id=[])
{
$model = \Yii::$app->db->createCommand()
->update('tbl_post',['Delete'=>1],['id'=>$id])->execute();
if($model==true){
\Yii::$app->session->setFlash('با موفقیت نیست شد');
}else{
\Yii::$app->session->setFlash('با موفقیت نیست نشد');
}
return $this->redirect('index');
}
here is view(ignore persian words)
//in baraye ine ke form taiid shod payam bede
foreach (Yii::$app->session->getAllFlashes() as $key => $message) {
echo '<div class="alert alert-' . $message . '">' . $key . '</div>';
}
//-------------------------table it self
echo \yii\grid\GridView::widget([
'dataProvider' => $adp,
'caption' => 'لیست تمامی محتوا ها',
'captionOptions' => ['id' => 'atro-caption'],
'headerRowOptions' => ['class' => 'atro-th'],
'columns' => [
['class' => \yii\grid\SerialColumn::className(),],
['class' => \yii\grid\CheckboxColumn::className(),
'checkboxOptions' => function ($a) {
return ['value' => $a->id];
}],
'Title',
'FK_PostType',
'FK_Author',
]
]);
Before I suggest you anything about your problem you should know the basic rules of programming that never use reserved keywords for function naming variable or database field names, you have used the Delete as a column name you should change it immediately to something like is_deleted. i will be using this name in my example reference.
About your problem, you have 2 ways to do it.
Add a button and bind javascript click event to it which will serialize all the selected checkboxes and then use an ajax post request to submit the selected ids and mark them delete.
Wrap your Gridview inside a form tag and then use a submit button to submit that for to the delete action.
I will demonstrate the first option to you
add the button on top of your GridView
<?=Html::button('Delete', ['class' => 'btn btn-danger', 'id' => 'delete'])?>
Then assign an ID to the pjax container
<?php Pjax::begin(['id' => 'my-grid']);?>
Paste this javascript on top of your view but update the url of the ajax call to your actual controller/delete action
$this->registerJs('
$(document).on("click","#delete",function(e){
let selected=$(".grid-view>table>tbody :input");
let data=selected.serialize();
if(selected.length){
let confirmDelete = confirm("Are you sure you want to delete?");
if(confirmDelete){
$.ajax({
url:"/test/delete",
data:data,
dataType:"json",
method:"post",
success:function(data){
if(data.success){
$.pjax({container:"#my-grid"});
}else{
alert(data.msg);
}
},
error:function(erorr,responseText,code){}
});
}
}else{
alert("select someitems to delete");
}
});
', \yii\web\view::POS_READY);
And change your delete action to the following, try using transaction block so that if something happens in the middle of the operation it will revert all the changes back, change the model name and namespace to the appropriate model, I assumed your model name is Post.
public function actionDelete()
{
if (Yii::$app->request->isPost) {
$selection = Yii::$app->request->post('selection');
$response['success'] = false;
$transaction = Yii::$app->db->beginTransaction();
try {
\frontend\models\Post::updateAll(['is_deleted' => 1], ['IN', 'id', $selection]);
$response['success'] = true;
$transaction->commit();
} catch (\Exception $ex) {
$transaction->rollBack();
$response['msg'] = $ex->getMessage();
}
echo \yii\helpers\Json::encode($response);
}
}

Laravel 4 - Deleting a record from the database

Once again, i am stumped.
I have a table of letters, each with the following link attached
Delete {{ $letter->lettername }}
From the docs i can see i have to run the following from my routes.php
$letter = Letter::find(1);
$letter->delete();
My question is, what do i have to enter in the href to pass the letters ID onto the routes file, and then how do i pass that to the find() parameter?
Do i do something like this
Delete {{ $letter->lettername }}
If so, how do i put that ID into the find paramter.
Im confused.
Any help would be greatly appreciated
Cheers
My Routes file is as follows:
Route::get('letters', array(
'before' => 'auth|userdetail',
function()
{
// Grab the letters, if any, for this user
$letters = Letters::forUser(Auth::user())->get();
$data = [
'letters' => $letters
];
return View::make('letters', $data);
}
));
You could do it like this
Delete {{ $letter->lettername }}
But it would be better if you have a named route
Delete {{ $letter->lettername }}
Then in your routes
Route::get('letters/delete/{id}', array('as' => 'letters.delete', 'before' => 'auth|userdetail', function($id)
{
echo ("You want to delete letter id: " . $id . " from the system");
// Put your delete code here
}

CakePHP setting up dependent AJAX dropdown

I have done a lot of research, tried to apply a few different examples but it seems that nothing really works.
So I have the following 3 models: Customers, Projects and Events. Customers have many Projects and Projects have many Events.
While creating an Event, I would like a user to select a Customer from a dropdown list and then the user should be provided with a list of Projects that belong to the selected Customer. The closest I have got to is the following. I do not have experience with AJAX, so that really is a hard nut to brake.
Action in the Porject's controller:
public function getbycustomer(){
$customer_id = $this->request->data['Event']['customer_id'];
$projects = $this->Project->find('list', array('conditions'=>array('Project.customer_id' => $customer_id), 'recursive' => -1));
$this->set('projects', $projects);
$this->layout = 'ajax';
}
View for this action is the following:
<?php foreach ($projects as $key => $value): ?>
<option value="<?php echo $key; ?>"><?php echo $value; ?></option>
<?php endforeach; ?>
And here is the snippets from the view for adding an event:
echo $this->Form->input('customer_id');
echo $this->Form->input('project_id');
//form continues and at the end of a page there is the AJAX call
$this->Js->get('#EventCustomerId')->event('change',
$this->Js->request(array(
'controller'=>'projects',
'action'=>'getbycustomer'
), array(
'update'=>'#EventProjectId',
'async' => true,
'method' => 'post',
'dataExpression'=>true,
'data'=> $this->Js->serializeForm(array(
'isForm' => true,
'inline' => true
))
))
);
Any help is much much appreciated as I do not even know the proper way for debugging it, so I could provide more valuable information.
go to this. this helped me to do the dependent drop down list. it provies a details step by step process.
I think you need to set autoRender to false otherwise it will try to render the template at app/View/Project/getbycustomer.ctp. Also, you probably want to return or print JSON. Ther are probably several ways to do this, but I have something similar that is working and the controller action is basically this:
public function getbycustomer() {
$this->autoRender = $this->layout = false;
$customer_id = $this->request->data['Event']['customer_id'];
$projects = $this->Project->find('list', array('conditions'=>array('Project.customer_id' => $customer_id), 'recursive' => -1));
$this->set('projects', $projects);
echo json_encode(array('html' => $this->render('your_partial_template')->body())); // This template would be in app/View/Project/json/
}
Then in your Ajax call there should be a 'success' callback that handles the JSON returned:
success: function(data) {
$('#EventProjectId').html(data.html); // assuming this an empty container
}
Also, unless your projects table is only two columns the result of your find is probably not what you're expecting. Change it to
$projects = $this->Project->find('list', array('conditions'=>array('Project.customer_id' => $customer_id), 'fields' => array('id', 'name_or_whatever', 'recursive' => -1));
Then in your partial template you can use the form helper:
<?php echo $this->Form->input('Projects.id', array('options' => $projects)); ?>

Action not running with CakePHP Js->submit()

I'm using CakePHP 1.3, and trying to make a simple message posting board with ajax. I'm trying to use the Js helper to submit a form on the index page, then refresh the message board's div to include the new message. This is all on a single page.
I have previously posted on this, but I wanted to rephrase the question and include some updates. The previous question can be seen here How to use Js->submit() in CakePHP?
When I came back to this project after a couple days, I immediately tested and the form worked (sort of). Submitting the form added a message to the database (it didn't display the message, but I haven't attacked that part yet). It worked 2 times, adding 2 messages. Then I opened the controller file and commented out some debug code, and it stopped working. It appears the action is not being called.
Here is my messages_controller.php:
<?php
class MessagesController extends AppController {
function index() {
$messages = $this->Message->find('all');
$this->set('messages',$messages);
}
function add() {
$this->autoRender = false;
$this->Session->setFlash('Add action called');
if($this->RequestHandler->isAjax()) {
$this->Session->setFlash('Ajax request made');
$this->layout = 'ajax';
if(!empty($this->data)) {
if($this->Message->save($this->data)) {
$this->Session->setFlash('Your Message has been posted');
}
}
}
}
}
?>
Here is the index.ctp for my Message class
<div id="guestbook" class="section_box">
<h3 id="toggle_guestbook"><div class="toggle_arrow"></div>Sign our Guestbook</h3>
<?php
echo $this->Form->create('Message');
echo $this->Form->input('name', array('label' => 'From:'));
echo $this->Form->input('text', array('label' => 'Message:'));
echo $this->Js->submit('Post Your Message', array(
'url' => array(
'controller' => 'messages',
'action' => 'add'
),
'update' => '#message_board'
));
echo $this->Form->end();
echo $this->Js->writeBuffer(array('inline' => 'true'));
?>
<div id="message_board">
<?php foreach($messages as $message) { ?>
<div class="message">
<p class="message_txt">
<?php echo $message['Message']['text']; ?>
</p>
<div>
<div class="message_name">
<?php echo $message['Message']['name']; ?>
</div>
<div class="message_date">
<small>
<?php echo $message['Message']['date']; ?>
</small>
</div>
</div>
</div>
<?php } ?>
</div>
</div>
When the submit button is clicked, I can see in the console that a POST is made to http://localhost/messages/add with the correct data. But there doesn't appear to be a response. The flash message "Add action called" is NOT set from the controller (or any of the flash messages, for that matter) and the contents of #message_board are emptied.
If I refresh the page at this point, the SECOND flash message appears ("Ajax request made"), and the contents of the #message_board are restored. However the new message was not saved, its the same 2 messages from before.
I'm stumped. I have a feeling maybe there are bigger issues causing my problem, but I can't see it. Any help would be appreciated.
But there doesn't appear to be a
response ... and the
contents of #message_board are
emptied.
That is because you haven't set what action/view to render. You have to do this manually since you have $this->autoRender set to false. You could use render() to do this. More info can be found at its respective cookbook page.
If you have $this->autoRender set to true, then it'll replace the contents of #message_board with the contents of add.ctp
The flash message "Add action called"
is NOT set from the controller (or any
of the flash messages, for that matter)
I think you have to refresh the page or the part which contains the $this->Session->flash() bit for flash messages to appear.
The fact that the flash message appeared when you refreshed the page means that it did call and run the action.
AFAIK, you can only put/print one message from the flash key in the Messages array. The flash key is where the flash messages are stored by default. Each call to setFlash() will overwrite the flash message set by older calls.
Since only the second flash message was displayed, we could say that it failed at passing at least one of the conditions following the second call to setFlash() in the controller. You might want to put debug($this->data) statements near the conditions related to $this->data to help yourself in debugging your problem.
You could also use debug() to know if your application went through a certain action or path since it will almost always be displayed.
So you could do the following to check if it passed this condition:
if(!empty($this->data)) {
debug('Passed!');
If 'Passed!' will be printed after submitting the form, we would know that it passed that condition.
However the new message was not saved
It might be because $data is empty or it failed at validation. If your $data is not empty, it might have failed at validation and since your form doesn't display the validation errors; you might never have noticed them. One way to know if it passed validation is to do the following:
$this->Message->set($this->data);
if ($this->Message->validates()) {
debug('it validated logic');
} else {
debug('didn't validate logic');
}
Ramon's solutions worked for me. Here's the updated code.
Controller add function
function add() {
$this->autoRender = false;
if($this->RequestHandler->isAjax()) {
$this->layout = 'ajax';
if(!empty($this->data)) {
if ($this->Message->validates()) {
if($this->Message->save($this->data)) {
$this->render('/elements/message_board');
} else {
debug('didn\'t validate logic');
}
}
}
}
}
Heres the add form view:
<?php
echo $this->Form->create('Message');
echo $this->Form->input('name', array('label' => 'From:'));
echo $this->Form->input('text', array('label' => 'Message:'));
echo $this->Js->submit('Post Your Message', array(
'url' => array(
'controller' => 'messages',
'action' => 'add'
),
'update' => '#message_board'
));
echo $this->Form->end();
echo $this->Js->writeBuffer(array('inline' => 'true'));
?>
<?php pr($this->validationErrors); ?>
<div id="message_board">
<?php echo $this->element('message_board'); ?>
</div>
I tried to use the same solution as you used but it's not working. Ajax is ok when I access it directly in the URL, and I have the impression that the click is doing nothing. When I use
<fieldset><legend><?php __(' Run 1');?></legend>
<div id="formUpdateID"><div id="#error-message"></div>
<?php
$orders=array_merge($emptyarray,$orders['r1']['Order']);
echo $this->Form->create('Order');
echo $this->Form->input('id', array('value'=>$orders['id'],'type' =>'hidden'));
echo $this->Form->input('race_id', array('value'=> $orders['race_id'],'type' =>'hidden'));
echo $this->Form->input('driver_id', array('value'=>$session->read('Auth.User.driver_id'),'type' =>'hidden'));
echo $this->Form->input('run', array('value'=>$run,'type' =>'hidden'));
echo $this->Form->input('pm', array('value'=>$orders['pm'],'error'=>$err[$run]));
echo $this->Form->input('pr', array('value'=>$orders['pr'],'error'=>$err[$run]));
echo $this->Form->input('fuel', array('value'=>$orders['fuel'],'error'=>$err[$run]));
echo $this->Form->input('pit', array('value'=>$orders['pit'],'label' => __('Pit on lap '),'error'=>$err[$run]));
echo $this->Form->input('tyre_type', array('value'=>$orders['tyre_type'],'error'=>$err[$run]));
echo $this->Js->submit('Modify', array(
'url' => array(
'controller' => 'orders',
'action' => 'ajax_edit'
),
'update' => '#error_message'
));
echo $this->Form->end();
?>
<?php pr($this->validationErrors); ?>
</div></fieldset>
in view and in controller "orders":
function ajax_edit($id=null){
$this->autoRender = false;
if($this->RequestHandler->isAjax()) {
die(debug('In Ajax'));
$this->layout = 'ajax';
debug('didn\'t validate logic');
}
echo 'hi';
}
None of the messages are displayed.
I have some hard coded JS/ajax before which is not targeting this code part.
I did copy ajax layout in th webroot/view folder.
I can see the AJAX code displayed in formatted source code
<div class="submit"><input id="submit-1697561504" type="submit" value="Modify" /></div> </form><script type="text/javascript">
//<![CDATA[
$(document).ready(function () {$("#submit-1697561504").bind("click", function (event) {$.ajax({data:$("#submit-1697561504").closest("form").serialize(), dataType:"html", success:function (data, textStatus) {$("#error_message").html(data);}, type:"post", url:"\/Webmastering\/form1C\/frame\/orders\/ajax_edit\/1"});
return false;});});
//]]>
</script>
BTW, I start getting bored of the lack of doc in cakephp and its non efficacity to realize task more complicated than just posting a post in a blog. So thank you for your help before I start destroying my computer ;)
I know it's an old topic, but I stumbled acros the same problem in my application, so now I think what Thrax was doing wrong, namely he didn't put echo $this->Js->writeBuffer(array('inline' => 'true')); in the view (or in the layout) file, like Logic Artist did, so the scripts for handling the submit button's click weren't generated.

Resources