disable field from editing but not from creating view sonata bundle - symfony

I have an application using Sonata Admin for the back-office.
If I use disabled => true it will remove the field from being editable in edit and create view.
Is there a way to disable it only on the edit screen?

I think you should try the following code to get the subject of the Admin and check if subject exist then disable the field. Update your configureFormFields method inside admin.
/** #var YourClass $subject */
$subject = $this->getSubject();
if($subject) {
// DISABLE THE FIELD
} else {
// ENABLE THE FIELD
}

Related

Sonata ecommerce custom product admin

I am using sonata e commerce bundle and I have added a couple of products. I can get them list and displayed in the admin section but when I try to create a new product I only see the basic field that all the products have.
Is there any way to create an Admin class that will allow me to see the extra fields for each kind of product class?
I finally figured out how to do this looking into the sonata sandbox example.
To add the custom fields to the product in the admin I have to override the WineProductProvider class and add the following method just like an admin class.
/**
* {#inheritDoc}
*/
public function buildEditForm(FormMapper $formMapper, $isVariation = false)
{
parent::buildEditForm($formMapper, $isVariation);
$formMapper
->with('Bottle details')
->add('origin','text')
->add('year','integer')
->add('grapes','text')
->add('closure','text')
->add('food','text')
->add('style','text')
->add('size','integer');
$formMapper->end();
}
And thats it. Hope it helps someone else.

How to properly set referring entity property when creating sub entity in Sonata Admin Bundle using sonata_type_model field

I feel like I'm missing something simple here...TLDR: using sonata_type_model field, which uses modal when adding new sub entities to a parent, how do I pass the parent to the sub entity to add it to the sub entity's reference field?
#
I have two entities at play, "User" and "Role" entities.
User -> OneToMany -> Role.
I'm trying to figure out how to create, edit, and delete roles from a user's Sonata Admin Bundle page.
In my UserAdmin class, I've configured the form fields like so:
$formmapper->add('roles', 'sonata_type_model', array(
'required' => false,
'btn_delete' => true,
'btn_list' => true,
'multiple' => true,
'btn_add' => true,
))
Existing roles show up fine. If I click the "add" button under the field of roles the Modal window appears with the fields from my "role" admin form. My problem is that when I save the new Role it does not properly reference the User on which it was created. I don't know how to pass the parent USER entity to the child ROLE entity! This should be simple but. I cannot find this answer anywhere
If you want one User can have many roles ('multiple => true' option in your class), and role can be used by many users, you should prefer a ManyToMany relationship.
Use something like this for replace your actual OneToMany:
//Entity\User
/**
* #ORM\ManyToMany(targetEntity="Role", mappedBy="users", cascade={"persist"})
*/
protected $roles;
And in your child entity :
//Entity\Role
/**
* #ORM\ManyToMany(targetEntity="User", inversedBy="roles", cascade={"persist", "remove"})
* #ORM\JoinTable(name="users_roles",
* joinColumns={#ORM\JoinColumn(name="role_id", referencedColumnName="id")},
* inverseJoinColumns={#ORM\JoinColumn(name="user_id", referencedColumnName="id")}
* ) *
* #var ArrayCollection $users
*/
protected $users;
Your parent entity (User) should have methods addRole(), removeRole() and getRole().
Else, you should do php app/console doctrine:generate:entities
If it's good, you have to edit your addRole() and removeRole() methods.
She must be like this :
public function addRole(\Namespace\Bundle\Entity\Role $roles)
{
$this->roles[] = $roles;
$roles->addUser($this);
return $this;
}
public function removeRole(\Namespace\Bundle\Entity\Role $roles)
{
$this->roles->removeElement($roles);
$roles->removeUser($this);
}
Then, your addRole should work in Sonata
I don't think this is the intended way to solve this problem, but needing to set the "user" entity on the "role" entity form that opens in an modal window when editing the User entity was achieved by using the jQuery ajaxComplete() function to listen for ajax windows opening, checking to see if it was the right one, grabbing the User ID from the page URL, and setting that ID in the hidden form element
jQuery(document).ready(function() {
$(document).ajaxComplete(function (event, request, settings) {
if (settings.url.indexOf('/your-entity-admin-path-') >= 0){
var pathArray = window.location.pathname.split( '/' );
$('.modal-body .box-body input[type=hidden]').val(pathArray[3]);
}
});
});
A nasty solution but sometimes we just need things to work...

Drupal7 - How to change page title on user profile page with custom fields that were added?

I am trying to replace the title of the user profile page, which is the username, with other fields that were added later. Trying to show the full name as the title of the page.
I edited page.tpl.php $title with following code but it doesn't work.
if(arg(0)=="user")
{
$title=$field_user_last_name;
}
Install the RealName module and go to /admin/config/people/realname to change the pattern used for the user's name.
I'm using Profile2 to add the first and last name field and the following pattern:
[user:profile-person:field_first_name] [user:profile-person:field_last_name]
But you can probably add the fields at /admin/config/people/accounts/fields without using Profile2 aswell.
A cleaner way to do this:
function mymodule_page_alter() {
global $user;
if(drupal_get_title() === $user->name) {
drupal_set_title('New value');
}
}
You can accomplish this functionality nicely using the Entity API module's metadata wrapper and hook_user_view(). Add a dependency to Entity API in your module's .info file and then the code could look something like the following (assuming you want to set the title to the user's full name and you have fields called field_first_name and field_last_name):
/**
* Implements hook_user_view().
*/
function MYMODULE_user_view($account, $view_mode, $langcode) {
// Set the page title of the user profile page to the user's full name.
$wrapper = entity_metadata_wrapper('user', $account);
$first_name = $wrapper->field_first_name->value();
$last_name = $wrapper->field_last_name->value();
if ($first_name && $last_name) {
drupal_set_title($first_name . ' ' . $last_name);
}
}
I got solution!!!
I added following code on preprocess_page function on my template.php
if(isset($variables['page']['content']['system_main']['field_name'])){
$title=$variables['page']['content']['system_main']['field_name']['#object']->field_name['und'][0]['value'];
drupal_set_title($title);
}

Programatically change price to Ubercart item when added to cart

I have built a Javascript app that provides custom configuration for a product. From that JS app I submit the relevant data to a Drupal module which I've also prepared. The purpose of the module is to validate input and submit the details to the Ubercart system.
I need to submit a custom price based on the items chosen from that module when the custom build is submitted from the module. I have looked at uc_variable_price, uc_custom_price and the hook_add_to_cart but I'm not seeing a way to add the custom price programmatically.
/**
* Implements hook_cart_item().
*/
function module_cart_item($op, &$item) {
switch ($op) {
case 'load':
$order = db_result(
db_query("SELECT price_total FROM {module_orders} WHERE id = %d",
$id)
);
if (!empty($order)) {
$item->price = $order;
}
break;
}
}
Check the logic

How to change the title of comment form in drupal

At my website there is "Login or register to post comments.."
I want to change the message to:
"Login or register to post comments(comments will be moderated).."
Because plenty of spammers are just creating logins to post spam comments.
Although all comments are moderated now. Putting this message will give clear info that spamming may not be possible and spammers will not create logins.
Assuming you are using Drupal 6, the code that creates the comment form is in the file comments.module in the Drupal module directory. Fortunately, the function allows for theming.
What you can do is copy and paste the function theme_comment_post_forbidden($node) and place it in the template.php file in your theme directory. You will also need to rename the function, replacing 'theme' with your theme name.
For example, say your theme name is 'utilitiesindia'. Then you will rename your function to utilitiesindia_comment_post_forbidden.
So, in your template.php file in a theme named utilitiesindia, use this function:
/**
* Theme a "you can't post comments" notice.
*
* #param $node
* The comment node.
* #ingroup themeable
*/
function utiltiesindia_comment_post_forbidden($node) {
global $user;
static $authenticated_post_comments;
if (!$user->uid) {
if (!isset($authenticated_post_comments)) {
// We only output any link if we are certain, that users get permission
// to post comments by logging in. We also locally cache this information.
$authenticated_post_comments = array_key_exists(DRUPAL_AUTHENTICATED_RID, user_roles(TRUE, 'post comments') + user_roles(TRUE, 'post comments without approval'));
}
if ($authenticated_post_comments) {
// We cannot use drupal_get_destination() because these links
// sometimes appear on /node and taxonomy listing pages.
if (variable_get('comment_form_location_'. $node->type, COMMENT_FORM_SEPARATE_PAGE) == COMMENT_FORM_SEPARATE_PAGE) {
$destination = 'destination='. rawurlencode("comment/reply/$node->nid#comment-form");
}
else {
$destination = 'destination='. rawurlencode("node/$node->nid#comment-form");
}
if (variable_get('user_register', 1)) {
// Users can register themselves.
return t('Login or register to post comments(comments will be moderated)', array('#login' => url('user/login', array('query' => $destination)), '#register' => url('user/register', array('query' => $destination)))
);
}
else {
// Only admins can add new users, no public registration.
return t('Login to post comments', array('#login' => url('user/login', array('query' => $destination))));
}
}
}
}
how to change the comment link text " Login or register to post comment" to be shorter ,eg " comment"
Also you can use String overrides module.
In Drupal 6:
Another option is to create a small custom module. This uses hook_link_alter(). This is a small example module to change the title of the "Login to post new comment" link: (Replace every instance of MYMODULE_NAME with the name you choose for the module)
STEP 1: Create a file called MYMODULE_NAME.info and add:
; $Id$
name = "MYMODULE_NAME"
description = "Change the appearance of links that appear on nodes"
core = 6.x
STEP 2: Create file called MYMODULE_NAME.module and add:
<?php
// $Id$;
/**
* Implementation of hook_link_alter
*/
function MYMODULE_NAME_link_alter(&$links, $node){
if (!empty($links['comment_forbidden'])) {
// Set "Login to post new comment" link text
$links['comment_forbidden']['title'] = 'NEW TEXT';
// Add this to allow HTML in the link text
$links['comment_forbidden']['html'] = TRUE;
}
}
STEP 3: Put these files in a folder called MYMODULE_NAME, place the folder in sites/all/modules, and enable the module
If you actually want to stop spammers from creating accounts, you should use something like the CAPTCHA module, since they typically use bots that will ignore instructions in any case.
http://drupal.org/project/captcha

Resources