I'm working on an AJAXy autocomplete widget. I'm trying to create a symfony URL with a placeholder, which I can then pass to my Javascript, so that the JS can inject the ID of records it has retrieved via AJAX. For example:
$this->widgetSchema['sons_list'] = new ynWidgetAjaxAutocomplete(
array(
'item_url' => url_for( 'person/edit?id=%' ),
// OR
'item_url' => url_for( 'person/%/edit' ),
)
);
But neither of these works - I am looking for /person/%25/edit, but the first yields /person/edit/action?id=%25 and the second yields /person/%25/action. It does work if I pass a placeholder of digits, but this seems like a narsty hack to me:
$this->widgetSchema['sons_list'] = new ynWidgetAjaxAutocomplete(
array(
'item_url' => url_for( 'person/edit?id=999999999999' ),
)
);
Anyone know a cleaner way? Thanks!
If you want to pass only one parameter, you can probably use url_for('person/edit?id=') and then just append dynamic parameter with js.
update
Another way - how about replacing %25 with js?
The main problem was that the auto-generated action was using $this->getRoute()->getObject(), but symfony wasn't able to resolve the URL to sfDoctrineRoute and was stuck with sfRoute, which doesn't have a getObject() method. I have now adjusted my action to retrieve the record based on the id parameter, and started using url_for( 'person/edit' ), appending ?id=123 in the JS, similar to Darmen. I am satisfied with this.
Good question!
Here is my solution (pass to url number and replace it it JS)
function preview_document(NODE, TREE_OBJ) {
var url_to = '<?php echo url_for(sprintf('#document_preview?id=%s', '-999999'));?>';
$.get(url_to.replace('-999999', $(NODE).attr('id').replace('phtml_', '')), function (data) {
$('#document-viewer').html(data);
});
}
Related
In my computer I've set the link as following in kartik sidenav
'url' => 'http://localhost:8080/advanced/frontend/web/index.php?r=batchno/productbatch/create',
'label' => 'New Batch',
'icon' => 'glyphicon glyphicon-plus-sign',
'visible'=>Yii::$app->user->can('c_billing-person'),
It Works Fine. But in other computer with same database setup it's not working as I need to give the URL as below
http://localhost/advanced/frontend/web/index.php?r=batchno/productbatch/create
So the difference is in the port.
My question is that how can I set the URL dynamically?
A correct method for setting the url with yii2 (included kartik sidenav) is base on Url Helper
use yii\helpers\Url;
$menuItems[] = ['label' => 'my_label', 'url'=>Url::to(['/your-controller/your-action'])];
in you case
'url'=>Url::to(['/batchno/productbatch/create'])
The Url Helper Url::to function provide the corretc routing for controller action in every environment ..
How to display Page Name in the url instead of Page ID
For example, It Should be
localhost/mysite/index.php/page/about
Instead of
localhost/mysite/index.php/page/1
I have tired from edit actionview()
public function actionView($id)
{
$this->render('view',array(
'model'=>$this->loadModel($id),
));
}
You can create links to ANY url that you like. The issue is how you deal with the data that is passed.
So in your view, create a link.
About Us
This will call the controller action actionView(). You can then handle the page in there.
public function actionView($page)
{
// Load the model with the required page tag.
$pageDetails = Article::model()->findByAttributes(
array('page_name' => $page)
);
// Display the page
$this->render('view',array(
'model'=>$pageDetails
));
}
Updated Answer
Hope you are making your website SEO friendly with pretty URL. If your pages are static web pages such as about, faq, privacy..., you can implement the above answer provided by crafter. In this case page names should unique.
Another way (but not exactly what you want) is url rewriting with native yii feature urlManager. In this case page id will appear in URL like bellow.
localhost/mysite/index.php/page/1/about
localhost/mysite/index.php/page/2/britain-to-support-italys-intelligence-effort-on-migrants
If you observe, most of the News website following the same url structure.
Ex: http://www.telegraph.co.uk/finance/economics/11682277/Greeks-admit-they-will-default-at-the-end-of-the-month-as-central-bank-turns-on-government.html
To do this this in application, you have to write urlManager rules.
'urlManager' => array(
'urlFormat'=>'path',
'showScriptName'=>true,
'rules' => array(
'<controller:\w+>/<id:\d+>' => '<controller>/view',
'<controller:\w+>/<action:\w+>/<id:\d+>' => '<controller>/<action>',
'<controller:\w+>/<action:\w+>' => '<controller>/<action>',
//We are adding pretty url for article
'page/<id:\d+>/<title:[a-zA-Z0-9\-_]>' => 'page/view',
),
I am assuming bellow is you Article database table
id title description keywords status
-------------------------------------------------------
1 about some big text some keys active
Now i am making the URl dynamically
<?php
//In Controller
//Fetch articles and send them to view
$articles=Articles::model()->findAll();
?>
<?php
//In View
//Iterate articles
foreach($articles as $article)
{
$id=$article->id;
$title=$article->title;
//Make structured Url.
// Replaces all spaces with hyphens and change text to lowercase .
$titleInUrl= strtolower(str_replace(' ', '-', $title));
// Removes special chars.
$titleInUrl=preg_replace('/[^A-Za-z0-9\-]/', '', $titleInUrl);
?>
$title
<?php
}
?>
You can also change URL pattern as you want. Ex i need url like
localhost/mysite/index.php/page/about-1
For this i have write/change rule in urlManager as
'page/<title:[a-zA-Z0-9\-_]>-<id:\d+>' => 'page/view',
Hope it will help you for your problem.
am actually having some issue with url routing while using TbMenu widget,i am using the format of /moduleId/ControllerId/ActionId in accessing module Controllers,here is an example
<?php $this->widget('bootstrap.widgets.TbNavbar', array(
'type'=>'inverse', // null or 'inverse'
'brand'=>'mysite',
'brandUrl'=>'#',
'collapse'=>true, // requires bootstrap-responsive.css
'items'=>array(
array(
'class'=>'bootstrap.widgets.TbMenu',
'items'=>array(
array('label'=>'Home','url'=>array('/site/index'), 'active'=>true),
array('label'=>'About', 'url'=>array('/site/page')),
array('label'=>'Contact us','url'=>array('/site/contact')),
),
),
'<form class="navbar-search pull-left" action=""><input type="text" class="search-query span2" placeholder="Search"></form>',
array(
'class'=>'bootstrap.widgets.TbMenu',
'htmlOptions'=>array('class'=>'pull-right'),
'items'=>array(
array('label'=>'Sign in', 'url'=>'/user/auth','visible'=>Yii::app()->user->isGuest),
'---',
[b] array('label'=>'Profile', 'url'=>'/user/user','visible'=>!Yii::app()->user->isGuest, 'items'=>array([/b]
[b]array('label'=>'Settings', 'url'=>'user/user/index'),[/b]
[b]array('label'=>'Logout', 'url'=>'user/user/logout')[/b],
)),
),
),
),
he three last line are the ones that are causing problem,when i try to access those links after clicking on home,page,contact us(using the Site controller actions that are auto-generated by the Yii) the route is appended to the existing url in stead of creating a new url to the module,for example if am on home page(after clicking home it has this as url localhost/mysite/index.php/site/index)**it gives me this url localhost/mysite/index.php/site/index/user/user/index,if i go the same link again with this as url it gives me **localhost/mysite/index/user/user/index/user/user/index if i click again it add another one again and again..but the strange in all is that it works fine with CMenu,here is snippet of CMenu that works fine,
<?php $this->widget('zii.widgets.CMenu',array(
'items'=>array(
array('label'=>'Home', 'url'=>array('/site/index')),
array('label'=>'About', 'url'=>array('/site/page', 'view'=>'about')),
array('label'=>'Contact', 'url'=>array('/site/contact')),
array('label'=>'Login', 'url'=>array('//user/auth'), 'visible'=>Yii::app()->user->isGuest),
array('label'=>'Logout ('.Yii::app()->user->name.')', 'url'=>array('//user/user/logout'), 'visible'=>!Yii::app()->user->isGuest),
array('label'=>'My profile ', 'url'=>array('/user/user/'), 'visible'=>!Yii::app()->user->isGuest),
),
)); ?>
i am assuming that it might be caused by the fact that those links are submenu but i am not sure since the first in those links is not submenu and has the same problem!thank you again
The TbMenu component is using CHtml::link to display the links...
CHtml::link(label, url, options)
CHtml::link method has one check
if url is an array ... then use controller->createUrl(...) method
if url is a string ... then just return that string.
So, I think, #dInGd0nG suggestion would work.
if not then you should be using array ...something like ( don't forget to prefix / )
array('label'=>'Settings', 'url'=> array('/user/user/index') ),
array('label'=>'Logout', 'url'=> array('/user/user/logout') )
I'm currently toying with updating page content via the following:
<%= link_to(content_tag(:span, 'Settings'), edit_admin_store_path, :remote => true)%>
With the javascript as such:
$('nav li a').bind("ajax:success", function(event, data){
console.log(event + data);
$('div#loading').hide();
$('div#container div#content').html(data).hide().fadeIn('100');
});
And was wondering if there is a 'rails way' to also update the address url as well?
Thanks a plenty for any help/advice!
Basically, you are asking for the HTML5 history.pushState method. Great documentation can be found here, at the mozilla developers network.
To be simple, you would push into the history by doing something like this:
var stateObj = { foo: "bar" };
history.pushState( stateObj, "new page title", "forbear.html" )
This will cause the URL to display http://www.yoursite.html/whatever/foobar.html depending on what the URL currently looks like.
Cheers!
My first post here, hopefully It will be right! =)
I am creating a site to manage web application development using symfony 1.4 and doctrine.
My records consist for this problem of Project and ProjectFeatures
Now what I want to do is use the admin generator to let users manage the features for one project thru a link constraining all the returned features by project_id, that would look like: http://mysite/member/project/:project_id/features
in my routing.yml configuration, I have:
member_project_feature:
class: sfDoctrineRouteCollection
options:
model: ProjectFeature
module: memberProjectFeature
prefix_path: /member/project/:project_id/features
with_show: true
column: id
with_wildcard_routes: true
project_id is an existing column in the model ProjectFeature,
I will use a custom query to retrieve features only by that project_id.
Now I can generate a url to link to that admin generator module without error using:
url_for('member_project_feature', array('project_id' => $project['id']))
And the routing system does recognise the url:
May 04 14:30:59 symfony [info] {sfPatternRouting} Match route "member_project_feature" (/member/project/:project_id/features.:sf_format) for /member/project/1/features with parameters array ( 'module' => 'memberProjectFeature', 'action' => 'index', 'sf_format' => 'html', 'project_id' => '1',)
But the admin generator can't generate it's links inside it's templates with that prefix_path and returns error InvalidArgumentException with message The "/member/project/:project_id/features/:action/action.:sf_format" route has some missing mandatory parameters (:project_id).
Any idea?
Well I found my answer at this url: http://www.blogs.uni-osnabrueck.de/rotapken/?s=symfony
But I will give it here and shorten it because, stackoverflow is awesome and it should be there for a long time =)
1st - The routing configuration I used in my question is valid.
2nd - You need to add a method in the action file generated by the admin
public function execute($sfRequest)
{
// taken from http://www.blogs.uni-osnabrueck.de/rotapken/?s=symfony
$this->forward404Unless(
$project_id = $sfRequest->getUrlParameter('project_id'));
$this->forward404Unless(
$this->project = Doctrine::getTable('ttcWebProject')->find($project_id));
$this->getContext()->getRouting()
->setDefaultParameter('project_id', $project_id);
if ($id = $sfRequest->getUrlParameter('id'))
{
$this->getContext()->getRouting()->setDefaultParameter('id', $id);
}
$result = parent::execute($sfRequest);
return $result;
}
At this point the url gets generated correctly but here is the last step to get to the end result you most probably want to achieve:
3rd - To get the list by project_id I can either provide a table method in the generator.yml, a default value to the getFilterDefaults or this method in the action file:
protected function buildQuery ()
{
$q = parent::buildQuery();
$rootAlias = $q->getRootAlias();
$q->andWhere("{$rootAlias}.project_id = ?",
$this->getRequest()->getUrlParameter('project_id'));
return $q;
}
I'm not 100% certain about what you're trying to do here, but it sounds like you need the ProjectFeature::toParams method return the project_id.